JJ Beck
JJ Beck

Reputation: 5283

No method 'val' in JQuery

I have an HTML form

<div class="field"> 
  <label for="num1">Number 1</label> 
  <input id="num1" type="text" /> 
</div> 
<div class="field"> 
  <label for="num2">Number 2</label> 
  <input id="num2" type="text" /> 
</div> 

When "Number 1" is changed, I'd like to change "Number 2" to match it. So this JQuery code:

$('#num1').change(function() {
  var one = this.val();
  $('#num2').val(one);
});

but it says:

Uncaught TypeError: Object #<HTMLInputElement> has no method 'val'

on the line

var one = this.val()

What am I doing wrong?

Upvotes: 1

Views: 5515

Answers (3)

Vishal Suthar
Vishal Suthar

Reputation: 17194

Use: $(this).val(); instead of this.val();

DEMO: JSFIDDLE

Upvotes: 1

Blender
Blender

Reputation: 298206

.val() is only defined on jQuery objects. this returns the DOM object, which does not have this property.

To fix your code:

  1. Use $(this).val(), or
  2. Use this.value

Upvotes: 12

YogeshWaran
YogeshWaran

Reputation: 2281

this is DOM object not jquery object. you can use either this.value or $(this).val()

$('#num1').change(function() {
  var one = $(this).val();
 $('#num2').val(one);
 });

Upvotes: 4

Related Questions