JQuery - list of strings

In jQuery, why am I getting information Undefined with the following code?

JS - right side Undefined

 var s = $("[name='CountAnswer']").val(); 

HTML

 <input style="width:150px" type="text" id="CountAnswer_1_" name="CountAnswer[1]"> <input style="width:150px" type="text" id="CountAnswer_2_" name="CountAnswer[2]"> <input style="width:150px" type="text" id="CountAnswer_3_" name="CountAnswer[3]"> 
+6
source share
3 answers

You are using equality matching, but you should use a wild card, probably the j query attribute begins with ^ , but the above statement will give the value of the first matching element. You can use each to repeat all elements.

 var s = $("[name^='CountAnswer']").val(); 

Iterate using each () .

Live demo

 $("[name^='CountAnswer']").each(function(){ alert($(this).val()); //or alert(this.value); }); 

Edit Based on comments on the OP. To get the values โ€‹โ€‹of all matches.

Live demo

 strValues = $("[name^='CountAnswer']").map(function(){ return this.value; }).get().join(','); 
+6
source

Since you do not have an element named == CountAnswer . You need to specify a specific name, for example:

 $("[name='CountAnswer[1]']").val(); 

Alternatively, you can use the โ€œStart withโ€ ( ^ ) wildcard to match all elements whose name begins with CountAnswer :

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

This, of course, only returns the value of the first element in the matched set, since this is val() behavior.

+5
source

jsFiddle demo

You must set up an array for your string values, and then use a jquery mismatch selector on some event, "starts with" (^) to iterate over the list of inputs indicated by your name.

demo html:

 <input value="a" style="width:150px" type="text" id="CountAnswer_1_" name="CountAnswer[1]"> <input value="b" style="width:150px" type="text" id="CountAnswer_2_" name="CountAnswer[2]"> <input value="c" style="width:150px" type="text" id="CountAnswer_3_" name="CountAnswer[3]"> <br><input type="button" id="b" value="show string list" /><div id="console"></div> 

demo js:

 var stringList = []; $('#b').click(function(){ stringList = []; $("[name^='CountAnswer']").each(function(){ stringList.push(this.value); }); var c = $("#console"); for( var i = 0; i < stringList.length; i++ ){ var d = $("<div>"); d.html(stringList[i]); c.append(d); } console.log(stringList); }); 
+3
source

All Articles