简体   繁体   English

如何获取选中元素的单选按钮值

[英]How to get radio button value of checked elements

I have a page which is having Continent/Countries/City. 我有一个页面正在浏览大陆/国家/城市。 Checkboxes are there for continent/Country. 有用于大洲/国家/地区的复选框。 I want to get the city details only where country is checked. 我只想获取检查国家的城市详细信息。 And is there any way other than using fieldset in html. 除了在html中使用fieldset之外,还有什么其他方法。 Below is the code and also how to select all Country in 'select All' check box. 以下是代码,以及如何在“全选”复选框中选择所有国家/地区。

<form>
    <input type="checkbox" class="mainCheckBox" /> Select All <br />
    <fieldset>
        <input type="checkbox" class="parentCheckBox" /> North America <br />
        <div class="content">
            <input type="checkbox" value="" name="country"
                class="childCheckBox" /> Canada<br /> &nbsp; &nbsp;<input
                type="radio" name="cnstates" id="OT" checked />Ontario<br />
            &nbsp; &nbsp;<input type="radio" name="cnstates" id="AT" checked />Alberta
            <br /> <input type="checkbox" value="" name=""country""
                class="childCheckBox" /> United States<br /> &nbsp; &nbsp;<input
                type="radio" name="usstates" id="NY" checked />New York<br />
            &nbsp; &nbsp;<input type="radio" name="usstates" id="DC" />Washington
            DC
        </div>
    </fieldset>

    <fieldset>
        <input type="checkbox" class="parentCheckBox" /> Asia <br />
        <div class="content">
            <input type="checkbox" value="" name="country"
                class="childCheckBox" /> India<br /> &nbsp; &nbsp;<input
                type="radio" name="instates" id="MU" checked />Mumbai<br />
            &nbsp; &nbsp;<input type="radio" name="instates" id="DL" checked />Delhi
            <br /> <input type="checkbox" value="" name="country"
                class="childCheckBox" /> Russia<br /> &nbsp; &nbsp;<input
                type="radio" name="rustates" id="MW" checked />Moscow<br />
            &nbsp; &nbsp;<input type="radio" name="rustates" id="DC" />Aldan
        </div>
    </fieldset>

</form>

Jquery to select all countries when Continent is checked 选中大陆后,jQuery将选择所有国家

 $(document).ready(
function() {
   $('input.childCheckBox').change(function() {
        $(this).closest('fieldset').find('.parentCheckBox').prop('checked',
            $('input.childCheckBox').length === $('input.childCheckBox:checked').length 
        ); 
    });

    //clicking the parent checkbox should check or uncheck all child checkboxes
    $(".parentCheckBox").click(
        function() {
            $(this).parents('fieldset:eq(0)').find('.childCheckBox').prop('checked', this.checked);
        }
    );
    //clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
    $('.childCheckBox').click(
        function() {
            if ($(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked') == true && this.checked == false)
                $(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', false);
            if (this.checked == true) {
                var flag = true;
                $(this).parents('fieldset:eq(0)').find('.childCheckBox').each(
                    function() {
                        if (this.checked == false)
                            flag = false;
                    }
                );
                $(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('checked', flag);
            }
        }
    );
}
); 

jsfiddle here jsfiddle在这里

you can do like this: 您可以这样:

$('.mainCheckBox').change(function(){

    if(this.checked)
    {
        $('.parentCheckBox').prop("checked","checked");
        $('.childCheckBox').prop("checked","checked");
    }
    else
    {
        $('.parentCheckBox').attr("checked",false);
        $('.childCheckBox').attr("checked",false);
    }

})

Here is DEMO 这是演示

You can try this: 您可以尝试以下方法:

$('.mainCheckBox').on('change', function(){
    $(this).closest('form').find(':checkbox').prop('checked', this.checked);
});

Demo 演示


You can add this script in your document.ready block. 您可以将此脚本添加到document.ready块中。


You can get the values with this: 您可以通过以下方式获取值:

$('.childCheckBox').on('change', function () {
    var checkedRadioVal = $(this).nextAll(':radio:checked').val();
    console.log(checkedRadioVal);
});

But this won't give you values because you have not placed any value="" attribute to your radios, instead what i get to know that you want the ids you have assigned to your radios then for this you can use .attr() method you can update this var in above event: 但这不会给您带来价值,因为您没有在收音机中放置任何value=""属性,而是我知道您想要分配给收音机的ID,然后可以使用.attr()您可以在上述事件中更新此var的方法:

var checkedRadioVal = $(this).nextAll(':radio:checked').attr('id');

Demo with getting values. 演示如何获取价值。

To start with, just don't bother about the fieldset . 首先,只要不用理会fieldset All it does is group the elements and add a box around them. 它所做的只是将元素分组并在它们周围添加一个框。 Also, I would suggest you to use a dropdown to select the country. 另外,我建议您使用dropdown选择国家。 It will be easier as the countries are mutually exclusive. 由于这两个国家是相互排斥的,因此会更容易。 You can append the city list on the form after selecting the country. 选择国家/地区后,您可以在表格上附加城市列表。 Here is a similar code I did with a bit of django and ajax. 这是我用django和ajax做的类似代码。

When you select the region number, it gets the list of registered countries from server table and updates the form fields. 当您选择区域号时,它将从服务器表中获取注册国家的列表并更新表单字段。 You can replace the logic as per your requirements. 您可以根据需要替换逻辑。

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#id_region").change(function() {
                $.post("jq_get_natty",
                    {
                        'region' : $('#id_region').val(),
                    },
                    function(data) {
                        $("#id_natty").empty();
                        for(var k in data) {
                            buf = (k + ". " + data[k] + "\n");
                            $("#id_natty").append("<option value=" + k + ">" + data[k] + "</option>");
                        }
                    }
                );
            });
        });
    </script>
</head>
<body>
<h2>Register</h2>
<hr />
<form action='add_person' method='post'>{% csrf_token %}
    <p><label for="id_name">Name:</label> <input id="id_name" maxlength="30" name="name" type="text" /></p>
    <p><label for="id_region">Natty:</label> <select id="id_region" name="region">
        <option value="" selected="selected">---------</option>
        {% for k in region %}
            <option value="{{ k }}">{{ k }}</option>
        {% endfor %}
        </select></p>
    <p><label for="id_natty">Natty:</label> <select id="id_natty" name="natty">
        <option value='1'>1</option>
        <option value='2'>2</option>
        </select></p>
<input type="submit" value="Register"/>
</form>
</body>
</html>

The following is my view: 以下是我的看法:

def jquery_natty_regn(request):
    print("Entered the jQuery server function")
    print("post: ", request.POST)
    regn = request.POST.get('region')
    nat = m1.objects.filter(number=regn)
    print("Acquired jQuery AJAX")
    print("regn = ", regn)
    data = serializers.serialize("json", nat)
    response_data = {}
    for k in nat:
        print("k.pk = ", k.pk, "\t", "k.name", k.name, "k.number", k.number)
        response_data[k.pk] = k.name
    print(response_data)
    json_data = json.dumps(response_data)
    return HttpResponse(json_data,content_type="application/json")

You can do like 你可以喜欢

  $('.parentCheckBox').is(':checked')
  $('.childCheckBox').is(':checked')

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

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