最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - No method 'val' in JQuery - Stack Overflow

programmeradmin3浏览0评论

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
Add a ment  | 

3 Answers 3

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:

  1. Use $(this).val(), or
  2. 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

发布评论

评论列表(0)

  1. 暂无评论