change type of input field with jQuery

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


        
29条回答
  •  情歌与酒
    2020-11-22 05:29

    Here is a little snippet that allows you to change the type of elements in documents.

    jquery.type.js (GitHub Gist):

    var rtype = /^(?:button|input)$/i;
    
    jQuery.attrHooks.type.set = function(elem, value) {
        // We can't allow the type property to be changed (since it causes problems in IE)
        if (rtype.test(elem.nodeName) && elem.parentNode) {
            // jQuery.error( "type property can't be changed" );
    
            // JB: Or ... can it!?
            var $el = $(elem);
            var insertionFn = 'after';
            var $insertionPoint = $el.prev();
            if (!$insertionPoint.length) {
                insertionFn = 'prepend';
                $insertionPoint = $el.parent();
            }
    
            $el.detach().attr('type', value);
            $insertionPoint[insertionFn]($el);
            return value;
    
        } else if (!jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input")) {
            // Setting the type on a radio button after the value resets the value in IE6-9
            // Reset value to it's default in case type is set after value
            // This is for element creation
            var val = elem.value;
            elem.setAttribute("type", value);
            if (val) {
                elem.value = val;
            }
            return value;
        }
    }
    

    It gets around the issue by removing the input from the document, changing the type and then putting it back where it was originally.

    Note that this snippet was only tested for WebKit browsers – no guarantees on anything else!

提交回复
热议问题