我有一个表单,用户可以选择时间间隔。但我只想要只选择一个选项。在从下拉列表中选择值时,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);
}
});
答案 0 :(得分:2)
jQuery中有一个.not()
方法,它从匹配元素集中删除元素。
$('select.span1').change(function() {
$('select.span1').not($(this)).val('');
});
文档here。
PS1:使用唯一ID!我已将您的ID选择器更改为类选择器。
PS2:如果可能,请避免使用内联JavaScript。我的例子是unobtrussive。
答案 1 :(得分:1)
我删除了你的onchange-function并在jQuery中添加了一个事件:
$('select').change(function () {
$('select').not($(this)).val('');
});
请参阅此处的工作示例:http://jsfiddle.net/4pqdx/
编辑注意到我有错误的jsfiddle-link。新的有效!
答案 2 :(得分:0)
首先,你不应该在同一个html文档中有两个具有相同id的元素 在所有选择框上添加相同的类,并为它们提供所有不同的ID 一旦你的选择框上的所有ID都不同,你就可以使用以下内容之外的所有目标:
function disableOther(callerId){
$('.selectBoxesClass:not('+caqllerId+')').val(0);
});