开发者

Why am I getting "undefined" with jquery.val()?

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" v开发者_如何学Goalue="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;
         }
      }      
   }


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.


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

  });
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜