big
big

Reputation: 1938

Selecting elements with special characters in the ID

In html code I am using code <input type = "text" id = "[email protected]"> 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 ?

Upvotes: 27

Views: 37700

Answers (7)

Gleno
Gleno

Reputation: 83

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)

Upvotes: 0

Joseph Jojo John
Joseph Jojo John

Reputation: 551

Use the function CSS.escape() to select that DOM element. In your case for the id [email protected] you can use the below code.

$("#" + CSS.escape('[email protected]'));

Upvotes: 2

kappamaki
kappamaki

Reputation: 676

It looks like JQuery has a useful method for this as of version 3 called escapeSelector.

$('#' + $.escapeSelector(my_id_with_special_chars));

https://api.jquery.com/jQuery.escapeSelector/

Upvotes: 13

user3840288
user3840288

Reputation: 181

$(document.getElementById('[email protected]')) also works.

Upvotes: 7

ysrb
ysrb

Reputation: 6740

Try escaping it:

$('#abc\\@def.com').val();

First paragraph of http://api.jquery.com/category/selectors/

Upvotes: 31

user250145
user250145

Reputation:

Instead of trying for ID using #, try this to match attribute like this,

$('[id=ID]')

or

$('[id='+ID+']')

so instead of

bidID = "#" + idVal + "bid"

you can try

bidID = "[id=" + idVal + "bid]"

Upvotes: 38

daryl
daryl

Reputation: 15197

Have a shot at this, not 100% on whether this is what you're after. Let me know:

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

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

Upvotes: 0

Related Questions