change type of input field with jQuery

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


        
29条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-22 05:39

    This will do the trick. Although it could be improved to ignore attributes that are now irrelevant.

    Plugin:

    (function($){
      $.fn.changeType = function(type) {  
        return this.each(function(i, elm) {
            var newElm = $("");
            for(var iAttr = 0; iAttr < elm.attributes.length; iAttr++) {
                var attribute = elm.attributes[iAttr].name;
                if(attribute === "type") {
                    continue;
                }
                newElm.attr(attribute, elm.attributes[iAttr].value);
            }
            $(elm).replaceWith(newElm);
        });
      };
    })(jQuery);
    

    Usage:

    $(":submit").changeType("checkbox");
    

    Fiddle:

    http://jsfiddle.net/joshcomley/yX23U/

提交回复
热议问题