views:

45

answers:

2

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;
         }
      }      
   }
+5  A: 

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.

Pekka
:::facepalm::: that's what I get for looking at code for hours on end by myself. lol. thanks.
dcp3450
A: 

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);

  });
}
James Westgate