开发者

How to set link to check checkbox with variable name,id,value

I have a long list of checkboxes each with a link next to it. Something like:

<form name="checkboxlist" action="..." >
    <input type="checkbox" id="1" name="pageCB" value="1"/>
    <a id="1" href="#" onclick="sub(id)>click here</a>
    <input type="checkbox" id="2" name="pageCB" value="2"/>
    <a id="2" href="#" onclick="sub(id)>click here</a>
    ...
    ...
    <input type="submit" />
</form>

I am currently开发者_如何转开发 trying to use:

<script>
    function sub(id){
        $("input:checkbox[value=id]").attr("checked", true);
        document.checkboxlist.submit(); 
    }
</script>

But this obviously does not read the variable id and I would really like to avoid making if statements for each id as there are several hundred of them. Is there some way to do this?


You shouldn't use a link you should use a <label> tag.

That's what it's made for.

<input type="checkbox" name="mybox" id="mybox">
<label for="mybox">Click this box</label>

This works for all form fields and is way better than having to build JS to do something that already exists.


EDIT: I see you're also using duplicate IDs. This is invalid, and things will not work properly when selecting by ID.


Numeric IDs are invalid in HTML4.

Anyway, change this:

$("input:checkbox[value=id]")

to this:

$("input:checkbox[value='" + id + "']")

This concatenates the value of id into the selector string, and I also added quotation marks around the attribute selector value since they're required by the docs.

And change your inline handlers to this:

<a id="2" href="#" onclick="sub(this.id)>click here</a>

...because this is a reference to the element clicked, so this.id is a reference to its ID attribute.


If I understand correctly, you want to support selecting checkboxes by clicking on an associated element, and to submit the form on click. I would suggest a) Use a <label> element in place of <a> as they can be associated with inputs by id and b) don't use numeric, duplicate id attributes.

<form name="checkboxlist" action="#">
    <input type="checkbox" id="a" name="pageCB" value="1"/>
    <label for="a">Click here</label>
    <input type="checkbox" id="b" name="pageCB" value="2"/>
    <label for="b">Click here</label>
</form>    

<script>
    $(document).ready(function() {
        $('input:checkbox').change(function(){
            $(this).parent('form').submit();
        });
    });
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜