【问题标题】:Toggle checkbox before send a form在发送表单之前切换复选框
【发布时间】:2012-03-31 18:50:02
【问题描述】:

我想在单击复选框旁边的标签后发送表单。所以我在下面创建了简单的函数。 html代码:

 <input class="myinput" type="checkbox" name="photo"id="photo" value="1" />
 <label class="autosend" for="photo">Photos</label>
 <input class="myinput" type="checkbox" name="text"id="photo" value="1" />
 <label class="autosend" for="text">Text</label>

jQuery 代码:

 $('.autosend').click(function() {
 $('form#search').submit();
 });

主要问题是 - 单击标签表单后正在发送,但没有选中复选框。这是为什么?我在我的网络浏览器中看到复选框在发送前检查了几秒钟。有什么方法可以使用上面的这个 jquery 代码,可以选中或取消选中属于特定标签的复选框?

我知道我可以在发送表单之前添加额外的行:

 $(this).prev(".myinput").attr('checked','checked');

但这不是解决方案,因为我需要检查是否检查了先前的输入并只是切换(在状态检查和未检查之间)。

【问题讨论】:

  • 所以你想在检查文本时不检查照片?如果是这样,收音机不是更好吗?

标签: jquery


【解决方案1】:
$('input:checkbox').change(function() {
 $('form#search').submit();
});

【讨论】:

  • 哇,原来如此简单。工作知府。非常感谢!
【解决方案2】:

您可以在复选框的更改事件上发送表单:

$('input[name=text]').on('change', function(){
  $(this).parents('form').submit();
});

【讨论】:

  • 这是一个很好的解决方案,但我的输入比名为“文本”的输入要多。
  • 不仅在文本输入上,而且在两个复选框上。
【解决方案3】:

首先应将label元素的for属性设置为相关输入的id

<input class="myinput" type="checkbox" name="photo" id="photo" value="1" />
<label class="autosend" for="photo">Photos</label>

<input class="myinput" type="checkbox" name="text" id="text" value="1" />
<label class="autosend" for="text">Text</label>

其次,您应该使用change 事件来覆盖用户通过键盘输入选择框,并且您还应该检查以确保该框被选中,而不是未选中

$('input:checkbox').change(function() {
    if ($(this).is(":checked")) {
        $('form#search').submit();
    }
});

Example fiddle

【讨论】:

    【解决方案4】:

    问题在于&lt;label&gt; 元素的for 属性对应的是ID,而不是您希望它引用的元素的名称。您的标签和复选框未连接,因此单击标签不会切换复选框。

    【讨论】:

    • 是的,我有,我忘了把它放到这里的代码中。但是我已经找到了其他人在下面提到的解决方案。感谢您的回答。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    • 2016-12-15
    • 1970-01-01
    相关资源
    最近更新 更多