我有几个选择框让用户输入我传递给另一页的时间:
<p class="apptmar">
<label for="from">Appointment Starts:</label><br />
<input type="text" name="from" id="from" class="appt" /><br />
<select name="fromh" class="apptselect">
<option>1</option>
...
<option>12</option>
</select>
<select name="fromm" class="apptselect">
<option>00</option>
<option>05</option>
...
<option>55</option>
</select>
<select name="froma" class="apptselect">
<option>AM</option>
<option>PM</option>
</select>
</p>
<p class="apptmar">
<label for="to">Appointment Ends:</label><br />
<input type="text" name="to" id="to" class="appt" /><br />
<select name="toh" class="apptselect">
<option>1</option>
...
<option>12</option>
</select>
<select name="tom" class="apptselect">
<option>00</option>
..
<option>55</option>
</select>
<select name="toa" class="apptselect">
<option>AM</option>
<option>PM</option>
</select>
</p>
我想要做的是,当“约会来自”下的框改变时,“约会到”下的框的值将被更改为相同的框。我已设法使用以下内容完成此任务:
$('select[name="fromh"]').change( function() {
$('select[name="toh"]').val($(this).val());
});
这可以按预期工作。我现在要做的是更改分钟,但不是将其更改为相同的值,我希望它转到下一个。防爆。我挑选05下,10下将被选中。我尝试使用以下但它没有用:
$('select[name="fromm"]').change( function() {
$('select[name="tom"]').val($(this).val() + 1);
});
答案 0 :(得分:5)
我会使用jQuery的filter函数,该函数具有接受函数的重载。
$('select[name="fromm"]').change( function() {
var $that = $(this);
var $targetNode = $('option', 'select[name="tom"]').filter(function() {
return $(this).text() === $that.val();
}).next();
$('select[name="tom"]').val($targetNode.text());
});
或者说真的很安全:
$('select[name="fromm"]').change( function() {
var $that = $(this);
var $targetNode = $('option', 'select[name="tom"]').filter(function() {
return $(this).text() === $that.val();
}).next();
if ($targetNode.length === 1)
$('select[name="tom"]').val($targetNode.text());
});
答案 1 :(得分:0)
您可以在当前select
中获取所选索引,然后获取下一个选项的值。如果用户选择“55”,则翻转为零:
$('select[name="fromm"]').change(function() {
var index = (this.options.selectedIndex+1)%this.options.length;
$('select[name="tom"]').val(this.options[index].value);
});
JSFiddle:http://jsfiddle.net/eZBNG/1
答案 2 :(得分:0)
我不是专家,几乎不知道我在做什么,但这也不行吗?
$('select[name="fromm"]').change( function() {
$('select[name="tom"]').val($(this).next().val());
});
也许需要一点逻辑来看看是否有下一个?