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?
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?
Share Improve this question asked Oct 25, 2012 at 5:06 JJ BeckJJ Beck 5,2837 gold badges34 silver badges36 bronze badges 1- this is object of your element so it will have all the property which your element have like value ,id etc whereas is val() is available with jQuery object – rajesh kakawat Commented Oct 25, 2012 at 5:20
3 Answers
Reset to default 12.val()
is only defined on jQuery objects. this
returns the DOM object, which does not have this property.
To fix your code:
- Use
$(this).val()
, or - Use
this.value
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);
});
Use: $(this).val();
instead of this.val();
DEMO: JSFIDDLE