【发布时间】:2017-10-26 11:28:48
【问题描述】:
我正在使用 jQuery 构建一种小型“滑动”表单模板,但我遇到了一些可能非常愚蠢的问题。
脚本文件中正在进行一些简单的验证,基本上最初禁用“下一步”按钮,然后在您回答问题后启用它(无论是收音机、复选框还是文本输入)。
即使我切换前两个<li> 元素,表单也会卡在第二个问题上(下一个按钮永远不会启用)。这是一个jsfiddle。如果你能让我停止用头撞墙,我将不胜感激。
https://jsfiddle.net/ntnr/6szynjqj/1/
HTML
<ul id="rom">
<li class="active">
<div class="form-group checkbox-group" required>
<h3>CHECKBOX! What is Your Favorite Pet? (1)</h3>
<div class="checkbox">
<label><input type="checkbox" name="pet" value="cat">Cats</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="pet" value="dog">Dogs</label>
</div>
<div class="checkbox">
<label><input type="checkbox" name="pet" value="rabbit">Rabbits</label>
</div>
</div>
</li>
<li>
<div class="form-group radio-group" required>
<h3>RADIO! What is Your Favorite Book? (2)</h3>
<div class="radio">
<label><input type="radio" name="book" value="this">This one</label>
</div>
<div class="radio">
<label><input type="radio" name="book" value="that">That one</label>
</div>
<div class="radio">
<label><input type="radio" name="book" value="other">The other one</label>
</div>
</div>
</li>
<li>
<div class="form-group input-group" required>
<h3>INPUT! What is Your Favorite Time of the Day? (3)</h3>
<div class="input">
<label><input #superbutton type="input" name="time" value="morning"></label>
</div>
</div>
</li>
</ul>
JS
$(document).ready(function() {
var prev_button = $('<button class="btn prev" style="margin-right:5px;">Prev</button>');
var next_button = $('<button class="btn next" disabled>Next</button>');
$('#rom > li').append(prev_button);
$('#rom > li').append(next_button);
$('#rom > li').first().find('button.prev').hide();
$('#rom > li').last().find('button.next').hide();
$('.prev').on('click', function() {
$(this).closest('li').removeClass('active');
$(this).closest('li').prev().addClass('active');
});
$('.next').on('click', function() {
$(this).closest('li').removeClass('active');
$(this).closest('li').next().addClass('active');
});
// Validation (non-empty) for Input fields
$('.input-group input').keyup(function() {
var empty = false;
$('.field input').each(function() {
if ($(this).val().length == 0) {
empty = true;
}
});
if (empty) {
$(this).closest(button.next).attr('disabled', 'disabled');
} else {
$(this).closest(button.next).attr('disabled', false);
}
});
// Validation (non-empty) for Checkboxes
var checkBoxes = $('#rom > li.active').find('.checkbox-group input[type="checkbox"]');
checkBoxes.change(function () {
$(this).closest('li').find('button.next').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
$('.checkbox-group input[type="checkbox"]').change();
// Validation (non-empty) for Radio Buttons
$('#rom > li.active').find('input:radio').click(function() {
$(this).closest('li').find('button.next').removeAttr('disabled', 'disabled');
});});
【问题讨论】:
-
控制台有错误吗?
-
请点击
<>并在此处创建一个sn-p -
closest(button.next)应该做什么?你也需要引号,最接近的是 dom -
你为什么使用keyup?该事件永远不会在鼠标单击时触发
-
是的,我在这里的“最接近”位是失败的。然而,它不是不起作用的。