Reference HTML Elements by name (with square brackets in them) via javascript

[亡魂溺海] 提交于 2021-01-27 07:51:11

问题


Hey everyone, I am trying to hide/show different html elements (div, etc...) based on whether a checkbox is checked or if a specific value is chosen from a dropdown box. I was wondering if someone can help me out. The html element is defined along the lines of this (below), and i'm not sure how to reference it by name with brackets in it. The page i'm using has jquery enabled, and i'd like to use it if possible. Thanks!

<input type="checkbox" name="addons[2]" />

Also - I cannot modify the checkbox's code.


回答1:


jQuery to check if element is checked:

$("input[name='addons[2]']").attr("checked")

jQuery to loop over such elements that are checked:

$("input[name^='addons']:checked").each(function() {
    // ...
});



回答2:


Thanks for the help, here is the final code I used

$("input[name='customfield[4]']").click(

    function()
    {
        if ($("input[name='customfield[4]']").is(":checked"))
        {
            $("#addons").hide();
        }
        else
        {
            $("#addons").show();
        }
    }
);



回答3:


Here is an inline non-jQuery solution that bypasses the need to reference the square brackets entirely by using the javascript this keyword. Assuming you want to show/hide a <div> with id="mydiv":

<input type="checkbox" name="addons[2]" onclick="document.getElementById('mydiv').style.display = (this.checked ? 'block' : 'none');" />



回答4:


avoid using [] in naming html elements



来源:https://stackoverflow.com/questions/2068503/reference-html-elements-by-name-with-square-brackets-in-them-via-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!