JQuery的。检查具有相同类的选择框和文本框的值,是否可以?

时间:2010-05-07 11:38:29

标签: jquery jquery-selectors

我有几个具有相同类的选择框和文本框,我有以下声明。 已更新

//This goes through each visible tr of the table with class notEmptyTable
$('.notEmptyTable tr:visible').each(function(index) {

    //This checks that the elements with class checkTextBox1IsNotEmpty its not Empty.
    if ($('.checkTextBox1IsNotEmpty ').val() != "") {
        if ($('.selTxtClass:visible').val() == "") {
            $('.selTxtClass:visible').focus();
        }
    }    
});

更新HTML

<table>
    <tr>
      <td><input type="text" id="txtBoxa1" class="checkTextBox1IsNotEmpty"/></td>
      <td><input type="text" id="txtBoxb1" /></td>
      <td><select id="selc1" class="selTxtClass" onchange="javascript:if (this.value = "other")txtBoxd1.style.display = 'block'"/>
          <input id="txtBoxd1" style="display:none;" class="selTxtClass"/>
      </td>
    </tr>

    <tr>
      <td><input type="text" id="txtBoxa1" class="checkTextBox1IsNotEmpty"/></td>
      <td><input type="text" id="txtBoxb1" /></td>
      <td><select id="selc1" class="selTxtClass" onchange="javascript:if (this.value = "other")txtBoxd1.style.display = 'block'"/>
        <input id="txtBoxd1" style="display:none;" class="selTxtClass"/>
      </td>
    </tr>

    <tr>
      <td><input type="text" id="txtBoxa1" class="checkTextBox1IsNotEmpty"/></td>
      <td><input type="text" id="txtBoxb1" /></td>
      <td><select id="selc1" class="selTxtClass" onchange="javascript:if (this.value = "other")txtBoxd1.style.display = 'block'"/>
        <input id="txtBoxd1" style="display:none;" class="selTxtClass"/>
      </td>
    </tr>

 </table>

如果我使用($('。selTxtClass:visible')。val())进行警报,则它是未定义的。

我想检查这些元素的值是否为空,但是我不知道这个if语句有什么问题,请问你能帮我个忙吗?

非常感谢。

2 个答案:

答案 0 :(得分:4)

试试这个

$('.selTxtClass:visible').each( function(i,e){
    if(e.val()==''){
        e.focus();
        return false;
    }
});

答案 1 :(得分:2)

我认为这是较大循环的一部分,目前虽然您正在检查所有元素与这些类,而不是那一行中的那些,调整它给出$() consutrctor a上下文,在这种情况下的行,像这样:

$('.notEmptyTable tr:visible').each(function(index) {
    //Other loop stuff
    if ($('.checkTextBox1IsNotEmpty', this).val() != "") {
        if ($('.selTxtClass:visible', this).val() == "") {
            $('.selTxtClass:visible', this).focus();
        }
    }    
});

这会检查class="checkTextBox1IsNotEmpty" 当前行,我认为这就是你所追求的......如果不是只是忽略这个无用的答案:)另外,不是直接与问题相关,但不要多次使用相同的ID,在无效的HTML中使用的内容可能会导致许多其他副作用。