Selecting elements with special characters in the ID

Viewed 33389

In html code I am using code <input type = "text" id = "abc@def.com"> to get text now it need to get its value which is entered in text field. I am using jquery to do that:

$( document ).ready( function() {
    $( ".bid" ).click( function() {
        idVal = this.id
        bidID = "#" + idVal + "bid"
        spanID = "#" + idVal + "cbid"
        bidValue = $(bidID).val();

        alert(idVal)
        alert(bidID)
        alert(bidValue) //this alert says undefined
        $( spanID ).html( '&nbsp;' ).load( '{% url online_machines %}?id=' + idVal + '&bidvalue=' + bidValue);
    });
});

By doing this i get the value error undefined. I tried to remove special characters from the id to get its value. But I need the id with special characters. How can I get its value using jquery ?

7 Answers

Use the function CSS.escape() to select that DOM element. In your case for the id abc@def.com you can use the below code.

$("#" + CSS.escape('abc@def.com'));

This solution below worked for me, it is pretty clean:

//your HTML id has special characters: 
var option= "Some option with (parenthesis or @ )";
//use this type of jquery query:
$(`[id="order_${option}"]`).prop('checked',true)
Related