简体   繁体   English

检查使用:input时是否选中复选框/收音机

[英]Check if checkbox/radio selected when using :input

I want to post the data of a HMTL form using ajax so that it posts the same data as if I had submitted it normally. 我想使用ajax发布HMTL表单的数据,以便它发布与我正常提交的数据相同的数据。

Before HTML5 I would do something like this: $("input[type='radio']:checked, input[type='checkbox']:checked, textarea, input[type='text']") 在HTML5之前,我会做这样的事情: $("input[type='radio']:checked, input[type='checkbox']:checked, textarea, input[type='text']")

So I have been using $('form :input') so that it is more future proof for all the different type=email/search/etc. 因此,我一直在使用$('form :input')以便为所有不同的type = email / search / etc提供更多的未来证明。

The problem is that it will still send the value for checkbox/radio even though it hasn't been selected. 问题在于,即使未选中复选框/无线电,它仍将发送其值。 What is the best way to get around this? 解决此问题的最佳方法是什么?

CODE: 码:

$('#button').on('click', function(){
    $.ajax({
        url: 'myurl.com',
        type: 'post',
        data: $('form :input'),
        dataType: 'json',
        success: function() {
            alert('success');
        },
        error: function(xhr, ajaxOptions, thrownError) {
            alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
        }
    });
});

have you tried out: 您是否尝试过:

$('#button').on('click', function(){
$.ajax({
    url: 'myurl.com',
    type: 'post',
    data: $('form').serialize(),
    dataType: 'json',
    success: function() {
        alert('success');
    },
    error: function(xhr, ajaxOptions, thrownError) {
        alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
    }
});

}); });

http://api.jquery.com/serialize/ http://api.jquery.com/serialize/

As Tiago Reis's answer you can serialize form. 作为Tiago Reis的答案,您可以序列化表格。 If you want to more flexible way, then you can go-through each form element like below. 如果您想要更灵活的方式,则可以遍历每个表单元素,如下所示。 This is incomplete code segment so try to get the idea. 这是不完整的代码段,因此请尝试理解。

    function getFormData()
    {
        var retObjectc = {};
        $("#myform").find( 'input[type=text],input[type=time], input[type=hidden],input[type=checkbox],input[type=radio], textarea, select' )
        .each( function (key,value)
        {
            if( $(value).prop("tagName") == "INPUT" )
            {
                if( $(value).prop("type") == "checkbox" )
                {
                    retObjectc[$(value).prop("name")] = $(value).is(":checked");
                }
                else
                {
                    retObjectc[$(value).prop("name")] = $(value).val();
                }
            }
            else if( $(value).prop("tagName") == "SELECT" )
            {
                retObjectc[$(value).prop("name")] = $(value).val();
            }
        });

        return JSON.stringify(retObjectc);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM