【问题标题】:jQuery reset all Selectboxes excluding the calling onejQuery重置所有选择框,不包括调用框
【发布时间】:2012-10-22 10:54:30
【问题描述】:

我有一个表单,用户可以在其中选择时间间隔。但我只希望他们只能选择一个选项。在从下拉列表中选择一个值时,jQuery 应该重置其他下拉列表。 HTML(和 php,但不相关):

<select class="span1" name="repeatminute" id="repeatIntervalTiming" onChange="disableOther(this)">
            <?php for($i=0; $i<61;$i++){ echo "<option>$i</option>"; } ?>
            </select>
            minute(s)</label>
              <label>
            <select class="span1" name="repeathour" id="repeatIntervalTiming" onChange="disableOther(this)">
            <?php for($i=0; $i<25;$i++){ echo "<option>$i</option>"; } ?>
            </select>
             hour(s)</label>
            <label>
            <label>
                 <select class="span1" name="repeatday" id="repeatIntervalTiming" onChange="disableOther(this)">
            <?php for($i=0; $i<32;$i++){ echo "<option>$i</option>"; } ?>
            </select>
            day(s)</label>
            <label>
            <select class="span1" name="repeatmonth" id="repeatIntervalTiming" onChange="disableOther(this)">
            <?php for($i=0; $i<13;$i++){ echo "<option>$i</option>"; } ?>
             </select>
             month(s)</label> 

这是我的 jQuery 尝试:

function disableOther(caller){
    $('#repeatIntervalTiming').each(function(index) {
        if ($(this).text() != caller.textContent){
            $(this).val(0);
        }
    });

【问题讨论】:

  • 首先不要为所有&lt;select&gt; 提供相同的ID。
  • id 应该始终是唯一的!改用类。

标签: javascript jquery


【解决方案1】:

在 jQuery 中有一个 .not() 方法,它从匹配的元素集中删除元素。

$('select.span1').change(function() {
    $('select.span1').not($(this)).val('');
});

文档here

PS1:使用唯一 ID!我已将您的 ID 选择器更改为类选择器。

PS2:尽可能避免使用内联 javascript。我的例子是unobtrussive

【讨论】:

  • val('') 会比数字好
  • 你是对的,谢谢。我已经检查了 OP 的标记。更新了。
  • $('#repeatIntervalTiming') 更改为 $('name^=repeat') 以便删除重复的 id...
【解决方案2】:

我删除了你的 onchange-function 并在 jQuery 中添加了一个事件:

$('select').change(function () {
  $('select').not($(this)).val('');
});​​

在此处查看工作示例:http://jsfiddle.net/4pqdx/

edit 注意到我有错误的 jsfiddle-link。新的工作!

【讨论】:

    【解决方案3】:

    首先,你不应该在同一个 html 文档中有两个具有相同 id 的元素 在所有选择框上添加相同的类并给它们所有不同的 id 一旦您的选择框上的所有 id 都不同,您就可以将所有 id 定位到除了您所在的那个之外:

    function disableOther(callerId){
        $('.selectBoxesClass:not('+caqllerId+')').val(0);
    });
    

    【讨论】:

      猜你喜欢
      • 2013-05-31
      • 1970-01-01
      • 2013-01-24
      • 2013-08-10
      • 2013-01-29
      • 2012-05-08
      • 1970-01-01
      • 2014-06-29
      相关资源
      最近更新 更多