TypeError: .val is not a function

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?

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;

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();
})


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .
Read More:   ReactJS vs NodeJS - Why do I need to create both?

Similar Posts