javascript - 如何使用 click() 继续下一个表单元素并隐藏当前元素

标签 javascript jquery html forms show-hide

我的意思是我会有一种问题形式,但每个问题只能在单击下一步按钮后继续。所以假设第一个问题出现,点击下一步,它会隐藏第一个问题并显示第二个问题,依此类推。

我成功地展示了第 2 题,但无法继续进行第 3 题,最终导致逻辑困惑。我需要继续第三个问题。到达第 3 个问题后,即最后一个问题,下一步按钮将切换为提交按钮。

如何更改 js 以进行第 3 个问题?

HTML

<div id="container">
    <form action="" id="theform">
        <div class="qn 1st">
            <p>Qn 1</p>
            <input type="radio" name="qn1" id="one" value="one"><label for="one">one</label><br>
            <input type="radio" name="qn1" id="two" value="two"><label for="two">two</label>
        </div>
        <div class="qn 2nd">
            <p>Qn 2</p>
            <input type="radio" name="qn2" id="yes" value="yes"><label for="yes">yes</label><br>
            <input type="radio" name="qn2" id="no" value="no"><label for="no">no</label><br>
            <input type="radio" name="qn2" id="neutral" value="neutral"><label for="neutral">no</label>
        </div>
        <div class="qn 3rd">
            <p>Qn 3</p>
            <input type="radio" name="qn3" id="ohyeah" value="ohyeah"><label for="ohyeah">ohyeah</label><br>
            <input type="radio" name="qn3" id="ohno" value="ohno"><label for="ohno">ohno</label>
        </div>
        <button type="button" id="next">Next</button>
        <input type="submit" value="submit">
    </form>
</div>

JS

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){

    $("#next").click(function(){
        $(".qn").each(function(i){

            if($(this).is(":visible")){
                $(this).hide();
            }
            else if($(this).next().is(":hidden")){
                $(this).show();
            }
        });
    });

});
</script>

JsFiddle 在这里,http://jsfiddle.net/wcogrmpq/1/

最佳答案

$("#next").click(function () {
    var current = $(".qn:visible"),
        total = $(".qn").length,
        last = $(".qn:last");
    $(current).next().show();
    $(current).hide();
    if ($(current).next().is(last)) {//check if it is last question
        $("#next").hide();
        $("input[type='submit']").show();
    }
});

参见 updated fiddle在这里。

关于javascript - 如何使用 click() 继续下一个表单元素并隐藏当前元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25460002/

相关文章:

javascript - jQuery 警报代码不起作用

javascript - Lightbox 2.51 - 如何将关闭按钮和图像编号移至顶部?

html - 如何链接到另一个页面上的 <div>?

Html/CSS - 图像大小和文本内容大小相等

javascript - chrome.infobars Chrome 工具栏 API 的发布时间表

括号的 Javascript 优先级

javascript - Fullcalendar AJAX 调用多次触发,无需重新加载页面

javascript - 当滚动到内容或内容出现在窗口上时如何执行某些操作?

javascript - 当用户在提交之前键入输入时动态更新表单的值

javascript - 即使表单无效, Bootstrap 模式也会加载?