Reputation: 1
I have a ID with special characters. I need to get the value of this input with JQUERY.
<input style="text-align:center; width:50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_#@HELLO DAVID%VSOP1240%6X0.7LFIG">
<script>
function jq(str) {
var id = str.replace(/[%#;&,\.\+\@*~':"!\^\$\[\]\(\)=>|\/\\]/g, '\\\\$&');
var value = $("#"+id).val();
alert(value);
}
</script>
I try with this, but i dont have response in the alert. Help! please!
Upvotes: 0
Views: 3545
Reputation: 106
Get the answer from fiddle here I have written in both javascript & jquery. There is an option fot trying // before every special character in ID, but that doesn't worked for me. So on the other way you can get the answer. Check & let me know.
$("#clickID").on('click', function(){
getVal = $(document.getElementById('adhocGlobal_#@HELLO DAVID%VSOP1240%6X0.7LFIG')).val();
console.log(getVal);
alert(getVal);
});
Upvotes: 1
Reputation: 337560
Normally you can use jQuery's escape sequence in a selector, \\
, to escape special characters. However that won't work in this case as the id
you have specified in the element is invalid as it contains spaces.
Due to that you will have to use the attribute selector in jQuery to retrieve it:
var $el = $('[id="adhocGlobal_#@HELLO DAVID%VSOP1240%6X0.7LFIG"]');
console.log($el.val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input style="text-align: center; width: 50px;" type="text" onKeyPress="jq(this.id);" value="5" id="adhocGlobal_#@HELLO DAVID%VSOP1240%6X0.7LFIG">
A much better solution would be to fix the id
of your elements before they are output in to the page to remove the spaces and special characters.
Upvotes: 1
Reputation: 2540
function jq(str) {
var element = document.getElementById("adhocGlobal_#@HELLO DAVID%VSOP1240%6X0.7LFIG");
var value = $(element).val();
alert(value);
}
Upvotes: 0