Home » Html » jQuery: Change element type from hidden to input

jQuery: Change element type from hidden to input

Posted by: admin November 30, 2017 Leave a comment

Questions:

I’ve got an input which it’s type is set to hidden, I need to change it’s type to text. Can’t seem to figure this out or if it’s possible with jQuery

Answers:

With jQuery 1.4 you can change the type of an input while it’s detached.

marker = $('<span />').insertBefore('#myInput');
$('#myInput').detach().attr('type', 'text').insertAfter(marker);
marker.remove();

Questions:
Answers:

I’m not sure this is possible, so I would suggest using a hidden div to contain the input element, which can be shown as needed. The text input field can still hold data even if it’s hidden.

Questions:
Answers:

IE won’t allow you to change the type of a form element for security reasons so I would go with Aram’s hidden div suggestion.

Questions:
Answers:

Here’s how I would do this:

$("input[type='hidden']").each(function(){
  var name = $(this).attr('name'); // grab name of original
  var value = $(this).attr('value'); // grab value of original
  /* create new visible input */
  var html = '<input type="text" name="'+name+'" value="'+value+'" />';
  $(this).after(html).remove(); // add new, then remove original input
});

If you want to filter some of the elements call filter() before each(), like this:

$("input[type='hidden']").filter("[name='whatever']").each(function...

Questions:
Answers:

easy man…

$('input[type="hidden"]').each (function() { this.type = 'text'; });          

Trigger it on a event

Questions:
Answers:
Overlay.toAnyType = function (c, type) {

    var shadow = jQuery(document.createElement(c.context.nodeName));

    // Clone attributes to new object.
    for (var i = 0; i < c[0].attributes.length; i++) {
        var attr = c[0].attributes[i].name;
        var val = c[0].attributes[i].value;

        if (attr == "type") val = type;
        shadow.attr(attr, val);
    }


    shadow.insertAfter(c);
    c.remove();
};

When c is a jQuery object; the function above changes type attribute. Usage:

var inputElemt = jQuery("#input");
Overlay.toAnyType(inputElemt, "text");

Questions:
Answers:

Old thread, but I recently needed to do something similar but with file fields and clearing them… I think the same solution could apply, but at least you can grab the contents in this case.

var temp = $('#hidden-field').val();
$("#container-for-field").html("<input id='not-hidden' type='text' value='"+temp+"'/>");

That should also solve the problem :).

Leave a Reply

Your email address will not be published. Required fields are marked *