Reputation: 11187
Goal: read in the current value of a set of text boxes. if the value is "None" replace the value with the value provided. Once a value is changed stop.
When I use span and .text() instead of a textbox and .val() everything works. However, the textboxes are part of a form.
Any idea why it would return as "undefined"?
(basically i'm making a list from user input)
html:
<input type="text" name="class1" value="None" ><br>
<input type="text" name="class2" value="None" ><br>
<input type="text" name="class3" value="None" ><br>
<input type="text" name="class4" value="None" ><br>
<input type="text" name="class5" value="None" ><br>
jquery:
function compareClass(a)
{
var input = a;
for(x=1;x<6;x++)
{
var classText = $('.class'+x).val();
if(classText == "None")
{
$('.class'+x).val(input);
break;
}
}
}
Upvotes: 1
Views: 26637
Reputation: 11444
Use selectors in jQuery to simplify your code. [name^=Class]
means all inputs with a name
attribute starting with Class
(Quotes not required)
function compareClass(a)
{
$('input [name^=Class]').each(function() {
if ($(this).val() === 'None') $(this).val(a);
});
}
Upvotes: 1
Reputation: 449485
You are telling jQuery to look for elements with class class[x]
but you are assigning name s.
You could change the name
properties to id
s:
<input type="text" id="class1" value="None" ><br>
<input type="text" id="class2" value="None" ><br>
<input type="text" id="class3" value="None" ><br>
<input type="text" id="class4" value="None" ><br>
<input type="text" id="class5" value="None" ><br>
and fetch by ID:
var classText = $('#class'+x).val(); // Note the #!
(obviously, "class" won't make any sense now as a name probably)
Alternatively, you could in fact use the class
property but CSS classes can be be assigned to multiple elements, so it's not really suitable here.
Upvotes: 9