0

Trying to add a class to a button if there has been any input in one of six text fields on the page. Getting a console error that says "Uncaught TypeError: Object [object Object] has no method 'value'" referring to my var val line.

Syntaxual? Thanks for your help.

HTML:

<input id="a" class="answer" type="text">
<input id="b" class="answer" type="text">

JavaScript:

var val = $('.answer').each(function(){
    $(this).value();
});

if (/^\s*$/.test(val)){
    $('#theOne').addClass('show');
}
4

3 に答える 3

2

The method is val, not value:

var val = $('.answer').each(function(){
    $(this).val();
});

You may have been thinking of the native value property (which is probably preferable in terms of efficiency):

var val = $('.answer').each(function(){
    this.value;
});

However, none of this helps seeing as your each loop doesn't actually do anything. You could use filter to see if any of your inputs have a value:

var inputs = $(".answer").filter(function() {
    return this.value;
});
if(inputs.length) {
    $('#theOne').addClass('show');
}
于 2012-05-23T07:33:23.267 に答える
0
if ($('.answer').filter(function(){return $(this).val() != '';}).length) {
   $('#theOne').addClass('show');
}
于 2012-05-23T07:36:49.487 に答える
0
$('.answer').each(function(){
    $.trim($(this).value()).length>0? $('#theOne').addClass('show') : '';
});
于 2012-05-23T07:48:28.483 に答える