1

我需要通过将复选框的值与select.

例如,如果我选择国家名称,则应自动选中USA标记的复选框。USA

以下是我尝试过的:

<html>
    <head>
        <script type="text/javascript" src="jquery.js"></script>
        <script>
            $(document).ready(function(){
                $(".e_p_country").change(function() {
                    var len = $('input[id="chk_c"]').length;
                    $('input[name="chk_c"]').each(function(len) {                 
                        if ($(this).val()==$(input[id="chk_c"]).val()) {
                            $('input[name="chk_c"]').attr('checked',true);
                        }
                        else {
                            $('input[name="chk_m"]').attr('checked',false);
                        }
                    });
                });
            });
        </script>
    </head>

    <body>
        <p>
            Country:
            <select id="e_p_country" class="e_p_country" name="e_p_country">
                <option value="">Select</option>
                <option value="91">India</option>
                <option value="65">Singapore</option>
                <option value="1">USA</option>
            </select>
        </p>
        <input type="checkbox" class="chk_c" value="1" id="chk_c">USA
        <input type="checkbox" value="65" id="chk_c">Singapore
        <input type="checkbox" value="91" id="chk_c">India
    </body>
</html>

我怎样才能做到这一点?

4

3 回答 3

2

你可以这样做。JsFiddle 上的演示

$(".e_p_country").change(function(){
 $('input[type=checkbox]').attr('checked', false);
 $("input[type=checkbox][value='"+$(this).val()+"']").attr('checked', true);
});​
于 2012-05-29T09:57:34.150 回答
1

尝试这个:

$("#e_p_country").change(function() {
    var country = $(this).val();
    $(".chk_c").prop("checked", false).filter(function() {
        return $(this).val() == country;
    }).prop("checked", true);
});
于 2012-05-29T09:52:51.953 回答
0

*I want to point out that you cannot add the same id to multiple html elements, you could use the class attribute for that, also i edited your code like this*

HTML:

<span>Country:</span>

<select id="e_p_country" class="e_p_country" name="e_p_country">
    <option value="">Select</option>
    <option value="91">India</option>
    <option value="65">Singapore</option>
    <option value="1">USA</option>
</select>

<input type="checkbox" class="chk_c" value="USA" id="chk_c">USA
<input type="checkbox" value="Singapore" id="chk_c">Singapore
<input type="checkbox" value="India" id="chk_c">India

脚本

$(".e_p_country").change(function(){

    var selected = $(this + ':selected').text();
    $('input[type="checkbox"]').each(function(){ 

        if (selected == $(this).val()){
            $(this).attr('checked',true);
        }
        else{
            $(this).attr('checked',false);
        }
    });
});
于 2012-05-29T10:15:01.417 回答