开发者

How to clear a input array all elements using jQuery

I have defined my form elements using the html array method like this:

<input type开发者_高级运维="text" maxlength="45" name="Apikey[key]">
<select name="Apikey[developer]">

How can I clear all Apikey array using jQuery?

The question is how to clear them? All possible forms fields must be cleared.


Try ^(starts with) in the selector instead of |. Also to reset the fields appropriately storing the initial values using data. i.e:

$(function(){
    $("input[name^=Apikey]").each(function(){
      var $this = $(this);
      $this.data("initial-val", $this.val());
    });
});
.
.
.
function resetApiValues(){
   $("input[name^=Apikey]").each(function(){
     var $this = $(this);
     $this.val($this.data("initial-val"));
   });
}


The easiest thing to do would be to use the "standard" form plugin and call clearForm() or clearFields():

$('#formId').clearForm();
$('#formId [name^=Apikey]').clearFields();

Or, if you don't want or need all the extra form plugin machinery, just grab the source and figure out how clearForm() and clearFields() work. clearFields() is actually quite simple:

$.fn.clearFields = $.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea') {
            this.value = '';
        }
        else if (t == 'checkbox' || t == 'radio') {
            this.checked = false;
        }
        else if (tag == 'select') {
            this.selectedIndex = -1;
        }
    });
};


here you go:

$("input[name^='Apikey']").attr("name", "");

to clear the values:

$("input[name^='Apikey']").val("");

I see that you have edited to include different HTML elements, in that case:

$("*[name^='Apikey']")).each(function() { 
    switch(this.type) { 
        case 'password': 
        case 'select-multiple': 
        case 'select-one': 
        case 'text': 
        case 'textarea': 
            $(this).val(''); 
            break; 
        case 'checkbox': 
        case 'radio': 
            this.checked = false; 
    } 
}); 


$('input[name^="Apikey"]')...

See the official jQuery API here. bye


You cant just clear all the values. Some elements like SELECT have to have a value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜