23

I have the following code, where I am selecting all matching elements that start with the same name, excluding one I do not want included in the group.

var myInputBoxes= $('input[id ^= "SubjectText"]').not('#SubjectTextNew');
for (i = 0 ; i < myInputBoxes.length; i++){
    var SubjectId = myInputBoxes[i].id.replace('SubjectText', '');
    var Subject = myInputBoxes[i].val();
}

This gives me the following error in firefox

TypeError: myInputBoxes[i].val is not a function

Why would it fail on the val function?

2 Answers 2

58

Accessing a jQuery object using bracket notation returns a DOMElement which does not have the val() function. If you want to retrieve an element by its index within a matched set you need to use eq():

var Subject = myInputBoxes.eq(i).val();

Alternatively you can retain the DOMElement and use the value property:

var Subject = myInputBoxes[i].value;
8
  • Also you can convert DOMElement to jQuery object like so $(subjectBoxes[i]).val(); Apr 24, 2015 at 11:10
  • While that would work, what's the point of taking a jQuery object, getting a DOMElement from it, then converting that back to a jQuery object? Apr 24, 2015 at 11:11
  • Out of curiosity, can I change my query to return jQuery objects? (and be able to query on only a partial id?)
    – Neil P
    Apr 24, 2015 at 11:11
  • I'm not sure what you mean. You appear to already be doing that? Apr 24, 2015 at 11:14
  • 1
    In that example they're using the square brackets in the selector string, not on a JS object, hence the difference. Sep 18, 2015 at 9:20
1

Because subjectBoxes[i] is not a jQuery object, if it is a jQuery object then you can use .eq() to get a jQuery wrapper reference to the element at the passed index

var myInputBoxes = $('input[id ^= "SubjectText"]').not('#SubjectTextNew');
myInputBoxes.each(function (e, el) {
    var SubjectId = this.id.replace('SubjectText', '');
    var Subject = subjectBoxes.eq(i).val();
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.