Changing the <input> type in IE with JavaScript

前端 未结 4 1919
旧巷少年郎
旧巷少年郎 2020-11-28 15:15

This code below works in all web browsers except IE:



        
4条回答
  •  情书的邮戳
    2020-11-28 15:50

    you can do this. However, doing a replace on the outerhtml essentially re-declares the element, so any attribute not explicitly defined in the tag declaration will be forgotten. That is why the text value is saved to a variable first. Unlike jQuery's attr and prop, this works in all versions of IE. I used a real IE10, and I used IETester for 5.5 thru 9.

    Here is a fiddle, code below:

    HTML

    
    
    

    JS

    //attach a click handler to the button to make it transform 
    //when clicked, via our transform() function below
    document.getElementById('transformButton').addEventListener("click", transform);
    
    //flag of whether or not it is a password field or text field
    var isPassword = true;
    //this function will toggle the input between being a password or a text input
    function transform() {
        //copy the element itself, its html source, and value text to a variable
        var myInput = document.getElementById("myinput");
        var oldHtml = myInput.outerHTML;
        var text = myInput.value;
        if (isPassword)
        {
            //replace "password" with "text" in the html if it is a password field
            var newHtml = oldHtml.replace(/password/g, "text");
        }
        else
        {
            //replace "text" with "password" if it is a text field
            newHtml = oldHtml.replace(/text/g, "password");
        }
        //update the html
        myInput.outerHTML = newHtml;
        //restore the text value
        myInput = document.getElementById("myinput");
        myInput.value = text;
        //toggle the isPassword flag
        isPassword = !isPassword;
    }
    

提交回复
热议问题