views:

76

answers:

4

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.

+1  A: 

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:

Sarfraz
+1 for quickness
Richa
No need to the "starts with selector". It's absolutely valid to use the square brackets in the selector: `$('input[name="mobileno[]"]')`
RoToRa
A: 

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/

RoToRa
I'm not sure if *serialize()* would work here, because the value of the *name* attribute is uri-encoded, so `[]` becomes `%5B%5D`.
Andy E
Would that matter? I would have thought that could only be a good thing.
RoToRa
There is no such thing as an array in HTML, but there **is** in JavaScript. (Usually when dealing with 'arrays' of elements you'll actually have a NodeList, but that rarely makes a great deal of difference).
David Dorward
A: 

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.

boss
A: 
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.

Reigel