通过javascript终止HTML表单

时间:2015-05-24 16:51:46

标签: javascript

我已经提出了一个表格,我要求"你是否使用这项服务?"。我不希望出现剩下的问题如果用户点击单选按钮"无&#34 ;.我怎样才能使用javascript来做到这一点?

3 个答案:

答案 0 :(得分:1)

将表单的其余部分放入div中,然后包含此js。我建议将它放在文档末尾的脚本标签中,否则你必须将它全部包装在window.onload{}中。

此外,这适用于复选框,这对我来说对于是/否问题更有意义。我已经添加了一个注释,您需要进行轻微编辑才能使其适用于单选按钮。

// give the radio button an easy name
var r_b = document.getElementById("radio-button's-id-here");
// and give the div a nice selector
var serv = document.getElementById("the-div's-id");
// listen to when it is clicked
r_b.addEventListener("click",checked,false);
// optional: you originally specified radio buttons which means you'll need to add an event listener for the no option
// lastly include a function to handle everything
function checked (){
    // check its status
    if (r_b.checked){
        // hide the form
        serv.style.display = "none";
    }else{
        serv.style.display = "inline";
    }
}

免责声明:我在手机上,所以这是未经测试的,可能有拼写错误。

编辑:您不需要使用Cookie,除非表单位于其他页面上,或者您希望用户多次看到此页面而不会被提示

答案 1 :(得分:1)

在这里,请查看:http://jsfiddle.net/58urhgen/

<form>
    Do you make use of this service?
    <input type="radio" name="my-radio" value="Yes" onclick="document.getElementById('service-used').style.display='block';document.getElementById('service-not-used').style.display='none';" /> Yes
    <input type="radio" name="my-radio" value="No" onclick="document.getElementById('service-used').style.display='none';document.getElementById('service-not-used').style.display='block';" /> No
    <div id="service-used" style="display:none;">
        <p>You use the service!</p>
    </div>
    <div id="service-not-used" style="display:none;">
        <p>Doesn't use the service!</p>
    </div>
</form>

我只是使用单选按钮的事件处理程序来显示/隐藏表单中受尊重的部分,具体取决于用户的选择。我认为这是你想要实现的目标。

PS:这不是最好的做法,但这只是为了向您展示如何实现。您可以使用函数来使代码整洁。

答案 2 :(得分:-1)

您可以使用Cookie来存储表单状态。 http://www.w3schools.com/js/js_cookies.asp