Reputation: 8071
I'm new to javascript and jquery, and stumbled upon an issue while writing a script.
My script is generated by php code which reads lines from a file, parses it and prints them out using arrays. js then validates form input, and outputs useful messages to the user.
I have successfully used js and jquery on $('#id').blur
on various elements. However when I tried doing it on my indexed element, I came across this problem.
Code:
$('#NS_IN[0]').blur(function() {
alert("Called");
CopyNStoMain();
});
I noticed that this function would never get executed. I tried looking at the variables in console.
typeof($('#NS_IN[0]'))
is an object; but typeof($('#NS_IN[0]').val())
is Undefined.
In my html code, I have:
<input type="text" id="NS_IN[0]" value="" name="NS[0]">
What am I doing wrong? If the id NS_IN[0]
is defined and $(NS_IN[0])
refers to an object, shouldnt $(NS_IN[0]).val()
exist and hold the value of the input box?
Upvotes: 0
Views: 98
Reputation: 325
It works when you use a different selector, as jquery uses the []
as an attribute selector itself. So use e.g. (see fiddle: http://jsfiddle.net/rePQm/1/ ):
$('input').click(function() { alert("clicked " + this.id); });
an element selector that selects all input elements and adds the click handler to all of them. See the selectors section of the jquery documentation at http://api.jquery.com/category/selectors/ for more possible selectors .
Upvotes: 0
Reputation: 944
You need to escape the jquery selector characters.
$('#NS_IN\\[0\\]').blur(function() {
alert("Called");
CopyNStoMain();
});
Upvotes: 3
Reputation: 9348
In jQuery, the []
works in a different way, like:
div[id^="player_"]
So, one of the solutions, is to select the items which ID starts with something:
$("input[id^=NS_IN]").val();
Upvotes: 0