问题:
选择单选按钮并将文本字段中的数字与数组中的数字进行比较。如果为真,则不采取任何行动,否则将 div 与另一个 div 切换。
HTML 代码:
<!-- Step 1 - Choose level -->
<label class="control-label">Level:</label>
<label class="radio"><input type="radio" name="level" id="level" value="1">C-level</label>
<label class="radio"><input type="radio" name="level" id="level" value="2">D-level</label>
<!-- Step 2 - This apply only if choice 1 (C-level) is chosen -->
<label class="control-label">Number of authors:</label>
<label class="radio"><input type="radio" name="authors" id="authors" value="1">1 author</label>
<label class="radio"><input type="radio" name="authors" id="authors" value="2">2 authors</label>
<!-- Step 2 - This apply only if choice 2 (D-level) is chosen -->
<label class="control-label">Credits:</label>
<label class="radio"><input type="radio" name="credits" id="credits" value="1">15 credits</label>
<label class="radio"><input type="radio" name="credits" id="credits" value="2">30 credits</label>
<!-- Step 3 - This apply for both choice 1 and 2 -->
<label class="control-label">Type of study:</label>
<label class="radio"><input type="radio" name="study" id="study" value="1">Within</label>
<label class="radio"><input type="radio" name="study" id="study" value="2">Between</label>
<!-- Check the number in this input field against the criteria in $within or $between -->
<label class="control-label">Participants:</label>
<input class="input-small" id="participants" name="participants" type="text">
jQuery代码:
<script type="text/javascript">
$(document).ready(function()
{
var numbers = {
'1': { // whithin
'1': { // C
'1': 36,
'2': 63
},
'2': { // D
'1': 54,
'2': 63
}
},
'2': { // between
'1': { // C
'1': 60,
'2': 105
},
'2': { // D
'1': 90,
'2': 105
}
// ...
}
};
$('#participants').change(function()
{
var choice1 = $('input[name=level]:checked').val();
if (choice1 == '1')
{
var choice2 = $('input[name=authors]:checked').val();
}
else
{
var choice2 = $('input[name=credits]:checked').val();
}
var choice3 = $('input[name=study]:checked').val();
var number = numbers[choice3][choice1][choice2];
if ($(this).val() < number)
{
$('#part').addClass('error');
}
else
{
$('#part').removeClass('error');
}
}
});
</script>
扩展解释:
这个想法是获取每个选择的值并将它们相加,以查看它们是否对应于其中一个数组中给出的值。
设想:
- 用户选择“C-level”(值=1),然后选择“2 个作者”(值=2),连接时等于 12。
- 用户选择“Between”(值=2)并在文本字段中输入数字95(id/name=number)。
- 当用户将焦点从文本字段移开时,jQuery 应该进行比较。
结果:
jQuery 进入数组 $between,查找值 12 并看到它是 105。95 小于且不等于 105,因此 DIV 1 应替换为 DIV 2(同时保留用户输入的值)。
分区代码:
<div id="part" class="control-group">
<label class="control-label">Participants:</label>
<div class="controls">
<div class="input-prepend">
<input class="input-small" id="participants" name="participants" type="text">
</div>
</div>
</div>
如果用户键入不同的值并移动焦点,则应重新计算。如果文本字段中的值等于或大于数组中的值,则什么也不做。
任何帮助表示赞赏,如果我不是真的被卡住,我就不会输入这个!提前致谢。