【问题标题】:separate two html forms分开两个 html 表单
【发布时间】:2014-03-05 22:01:52
【问题描述】:

我在这里创建了两个表单http://jsfiddle.net/B9r22/8/,当你提交它们时,它们会转换为 JSON,问题是当你提交第一个表单然后提交第二个表单时,JSON 中的表单都有数据,如何我重置表单还是将它们分开?

<form name="first" id="1" action="" method="post">
Which city is in Great Britain?<br/>
London:<input type="radio" name="first" data-questionid="1" value="11"/><br/>
New York:<input type="radio" name="first" data-questionid="1" value="12"/><br/>
<p><input type="submit" /></p>
</form>

<form name="second" id="2" action="" method="post">
Which city is in USA?<br/>
Washington:<input type="radio" name="second" data-questionid="2" value="13"/><br/>
Tokio:<input type="radio" name="second" data-questionid="2" value="14"/>
<p><input type="submit" /></p>
</form>

【问题讨论】:

    标签: javascript html json forms


    【解决方案1】:

    获取单选按钮时使用表单作为范围:

    $('input[type="radio"]:checked', this)
    

    演示:http://jsfiddle.net/B9r22/11/

    【讨论】:

    • 是的,它可以工作......我还有另一个小问题,当有一个文本 jsfiddle.net/B9r22/13 并且没有填充我想要空的 JSON 时,是否有类似 input[type="收音机"]:检查文本
    • @user3357400:您可以使用filter 方法仅获取包含内容的输入:$('input[type="text"]', this).filter(function(i, e){ return $(e).val().length &gt; 0; })
    【解决方案2】:

    您可以使用表单重置,这会将输入设置为其默认值,但会忽略一些字段,例如type=hidden

    $('#1')[0].reset();

    【讨论】:

      【解决方案3】:

      据我所知,问题出在第 6 行。您的脚本使用无线电类型从整个 DOM(文档)中的所有 input 字段收集数据。相反,为选择器提供当前提交表单的上下文以仅匹配那些特定字段(使用$(this).find,其中$(this) 指的是提交的表单):

      将第 6 行更改为 $(this).find('input[type="radio"]:checked').each(function(){

      http://jsfiddle.net/B9r22/12/

      【讨论】:

        【解决方案4】:

        你需要限制

        $('input[type="radio"]:checked')

        提交的表单:

            $('form').submit(function() {
                var form = $(this);
                //....
        
                $('input[type="radio"]:checked', form).each(function(){
                    //...
        

        http://jsfiddle.net/B9r22/9/

        【讨论】:

          【解决方案5】:

          你应该使用 $(this)

          $(this).find('input[type="radio"]:checked').each(function(){
          

          http://jsfiddle.net/B9r22/10/

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-19
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多