jQuery not selecting id containing “<” angular bracket?

走远了吗. 提交于 2021-02-19 06:10:35

问题


I am not able to select checkbox which has id="check stage<lead>" in jQuery Selector.


HTML:

<input id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">

Javascript:

// escape jquery selectors
    function jQueryEscape(str) {
        if (str)
            return str.replace(/([ #;?%&,.+*<>~\':"!^$[\]()=>|\/@])/g, '\\$1');

        return str;
    }


      var StageName = "<lead>";

  $("[id='check stage" + jQueryEscape(StageName) + "']").prop("checked", true);

Equivalent JsFiddle : https://jsfiddle.net/vuw43uav/5/

Note: I'm using jQuery 1.7 and we can select id with spaces in jQuery. refer this jsFiddle: https://jsfiddle.net/vuw43uav/7/


回答1:


I know you asked to make it work using jQuery Selector, but you can do it using javascript.

Just select the element using javascript and make it checked.

document.getElementById("check stage"+StageName).checked = true;

Here is the working fiddle for your 1.7 jquery version. Fiddle

In case you want jquery selector, just select the element using javascript and then convert it to jquery selector, I know this is lame but should work fine for you.

var y = $(document.getElementById("check stage"+StageName));
y.prop("checked",true);



回答2:


Id attribute must not have any space characters, check this spec

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

use data-id instead

<input data-id="check stage<lead>" type="checkbox" title="Select/Unselect Column" name="chk-stage-column-select" value="" onchange="">

 $("[data-id='check stage" + StageName + "']").prop("checked", true);

Demo



来源:https://stackoverflow.com/questions/36057759/jquery-not-selecting-id-containing-angular-bracket

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