0

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?

Joel G Mathew
  • 7,561
  • 15
  • 54
  • 86

4 Answers4

3

You need to escape the jquery selector characters.

$('#NS_IN\\[0\\]').blur(function() {
        alert("Called");
        CopyNStoMain();     
    });
css
  • 944
  • 1
  • 9
  • 27
  • I'm ignoring my own answer and up-voting yours. Perfect. – emerson.marini Jul 24 '13 at 12:59
  • Also you could try wrapping your form in a `
    ` and use `$("#foo input")` as your selector. See http://api.jquery.com/category/selectors/ for more possible selectors.
    – til_b Jul 24 '13 at 13:20
0

You already have the answer here...I don't know how to tag your question as a duplicate.

//get
bla = $('#txt_name').val();
//set
$('#txt_name').val('bla');
Community
  • 1
  • 1
Alko
  • 672
  • 10
  • 21
  • No not exactly. I do know how to get the value of an input element. See how I included the check for `typeof($('#NS_IN[0]').val())`. My question is regarding the unexpected output, and the undefined variable. – Joel G Mathew Jul 24 '13 at 12:57
  • Oh, sorry...do you want to check if the input is string or int or...? – Alko Jul 24 '13 at 13:01
  • 1
    I'm trying to use the value, but the square brackets are messing up the logic. – Joel G Mathew Jul 24 '13 at 13:02
0

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();
emerson.marini
  • 9,331
  • 2
  • 29
  • 46
0

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 .

til_b
  • 327
  • 5
  • 15