Michael Gulik Michael Gulik - 11 months ago 39
Javascript Question

Difference between $this.text and $this.value and why 1 returns a null value?

I am having an issue with a script containing the lines below (top is commented out right now). They are in a loop to do a sum on the textboxes on a form. However, I get: 'Uncaught TypeError: Cannot read property '0' of undefined' when this runs. If I comment out the bottom line and uncomment the top line, it works fine.

I still want to keep the replace function though and I am not sure how to go about this.

total += $(this).text();

//difference and why the previous works, but the below returns null, but if

total += ($(this).all[0].value.replace(/\D/g, '')) * 1

EDIT: Should have mentioned that this was something I needed to debug and found this error.

Answer Source

.text() gets or sets the text inside an element.

For example: <p>Hello World</p>

console.log($('p').text()) will return Hello World

.value() isn't a jquery method, instead use .val()

.val() is used to get or set the value of an input field.

For example <input type="text"> If you wanted to get or set the value of the input, say on form submit, you would use something like $('input').val()