Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery - list of string

In JQuery, why do I get information Undefined with the following code?

JS - right part is 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]">
like image 574
Rafał Developer Avatar asked Mar 25 '13 10:03

Rafał Developer


3 Answers

You are using equality comparion but you have to use wild card probably jquery attribute starts with ^ but the above statement will give value of first matched element. You can use each to iterate through all elements.

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

Iterating using each().

Live Demo

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

Edit Based on OP comments. For getting the values of all matches.

Live Demo

strValues = $("[name^='CountAnswer']").map(function(){  
   return this.value;
}).get().join(',');
like image 87
Adil Avatar answered Nov 15 '22 06:11

Adil


Because you don't have an element whose name is == CountAnswer. You need to specify a specific name, for example:

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

Alternatively, you could use the "Begins With" wildcard (^) to match all elements whose name begins with CountAnswer:

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

This will of course, only return the value of the first element in the matched set, since that is the behaviour of val().

like image 33
BenM Avatar answered Nov 15 '22 06:11

BenM


jsFiddle demo

You should set up an array for your string values, and then on some event use the jquery partial match selector, "starts with"(^), to iterate on the list of inputs denoted 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);
});
like image 20
Travis J Avatar answered Nov 15 '22 06:11

Travis J