change type of input field with jQuery

后端 未结 29 2781
青春惊慌失措
青春惊慌失措 2020-11-22 05:13
$(document).ready(function() {
    // #login-box password field
    $(\'#password\').attr(\'type\', \'text\');
    $(\'#passwo         


        
29条回答
  •  感动是毒
    2020-11-22 05:48

    An ultimate way to use jQuery:


    Leave the original input field hidden from the screen.

    $("#Password").hide(); //Hide it first
    var old_id = $("#Password").attr("id"); //Store ID of hidden input for later use
    $("#Password").attr("id","Password_hidden"); //Change ID for hidden input
    

    Create new input field on the fly by JavaScript.

    var new_input = document.createElement("input");
    

    Migrate the ID and value from hidden input field to the new input field.

    new_input.setAttribute("id", old_id); //Assign old hidden input ID to new input
    new_input.setAttribute("type","text"); //Set proper type
    new_input.value = $("#Password_hidden").val(); //Transfer the value to new input
    $("#Password_hidden").after(new_input); //Add new input right behind the hidden input
    

    To get around the error on IE like type property cannot be changed, you may find this useful as belows:

    Attach click/focus/change event to new input element, in order to trigger the same event on hidden input.

    $(new_input).click(function(){$("#Password_hidden").click();});
    //Replicate above line for all other events like focus, change and so on...
    

    Old hidden input element is still inside the DOM so will react with the event triggered by new input element. As ID is swapped, new input element will act like the old one and respond to any function call to old hidden input's ID, but looks different.

    A little bit tricky but WORKS!!! ;-)

提交回复
热议问题