Pentium10
Pentium10

Reputation: 207893

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.

Upvotes: 2

Views: 7425

Answers (5)

Kris Ivanov
Kris Ivanov

Reputation: 10598

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; 
    } 
}); 

Upvotes: 1

mu is too short
mu is too short

Reputation: 434665

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;
        }
    });
};

Upvotes: 2

Chandu
Chandu

Reputation: 82903

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"));
   });
}

Upvotes: 3

Ivan
Ivan

Reputation: 3645

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

Upvotes: -1

aefxx
aefxx

Reputation: 25249

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

See the official jQuery API here. bye

Upvotes: 0

Related Questions