Michael Gulik
Michael Gulik

Reputation: 151

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.

Upvotes: 0

Views: 1044

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

1. .text does not exist as a property of a textbox. To retrieve its value, use val() (see 2)

2. You're mixing vanilla JS with your JQuery. .value should be .val().

3. What are you trying to attempt with .all...? This is the null that your error is referring to.

4. I think this may be what you want:

var total = 0;

$('input[type="text"]').each(function() {
   total += ($(this).val().replace(/\D/g, '')) * 1
});

alert("Your total is " + total);

Example: JSFiddle

Upvotes: 0

Kolby
Kolby

Reputation: 2865

.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()

Upvotes: 1

Related Questions