bin
bin

Reputation: 61

How to fetch textbox array value using javascript/jquery

I have an array of text inputs like this:

<input type="textbox" name="mobileno[]"><br>
<input type="textbox" name="mobileno[]"><br>
<input type="textbox" name="mobileno[]"><br>

They are generated at run time using an "add more" button.

Is there a way I can use jQuery to fetch the text input value and pass it in ajax request?

I have created an ajax request but I'm not able to fetch the value of text input array in name=value pattern.

Upvotes: 6

Views: 22418

Answers (4)

Reigel Gallarde
Reigel Gallarde

Reputation: 65254

var data = $('input[name="mobileno[]"]').map(function(){
  return this.name + '=' + this.value;
}).get().join('&');
alert(data);

this will give you a something like mobileno[]=value&mobileno[]=value&mobileno[]=value. You can then pass it in your ajax request.

Upvotes: 1

Sarfraz
Sarfraz

Reputation: 382666

You can do like this:

$('input[name="mobileno[]"]').each(function(){
  alert($(this).val());
});

The ^= finds elements whose name starts with mobileno text and later each is used to loop over all the elements to get their value.

More Info:

Upvotes: 7

Murugesh
Murugesh

Reputation: 820

Try this:

var text= new Array();
$("input[name='mobileno[]']").each(function(){
    text.push($(this).val());
});  

If u alert the variable text you will get the comma separated output.

Upvotes: 3

RoToRa
RoToRa

Reputation: 38390

First off: That's not an "array of textbox[es]". There is no such thing as an array in HTML. It's just multiple text boxes which all happen to have the same name, and that name just happens to have square brackets in the name. The square brackets in the name have no special meaning in HTML. (PHP needs them, but that's a whole other thing).

Second: type="textbox" is wrong. It's just type="text". You are lucky it's working because "text" is the default value that browsers fall back to when finding an invalid value such as textbox.

If you need to get the vales of a form in the standard name=value pattern (separated with &) jQuery provides the serialize method for forms:

alert($("#your-form-id").serialize());

http://api.jquery.com/serialize/

Upvotes: 1

Related Questions