admin管理员组

文章数量:1335361

HTML

<div>my content of the div1
  <input/>
</div>​

<div>my content of the div2
  <input/>
</div>​

<div>my content of the div3
  <input/>
</div>​

JS

$('input').on('change',function(){
  var x = $('this').parent('div').val();
    alert(x);
})​​​;

My problem is why cannot I get the content of the div which the input was changed ?

HTML

<div>my content of the div1
  <input/>
</div>​

<div>my content of the div2
  <input/>
</div>​

<div>my content of the div3
  <input/>
</div>​

JS

$('input').on('change',function(){
  var x = $('this').parent('div').val();
    alert(x);
})​​​;

My problem is why cannot I get the content of the div which the input was changed ?

Share Improve this question asked Oct 3, 2012 at 7:53 TechieTechie 45.1k44 gold badges164 silver badges247 bronze badges 1
  • 3 val() is for form fields. Are you looking for html()? – Tim M. Commented Oct 3, 2012 at 7:54
Add a ment  | 

8 Answers 8

Reset to default 6

You need to pass the value of this, not a string "this", to jQuery, and call .text() to get the text content of an element, not .val() (which gets the value of an input element):

$('input').on('change',function(){
    var x = $(this).parent('div').text(); //`text` method gets contents of div
    //        ^ no quotes around `this`
    alert(x);
})​​​;

Corrected Script

$('input').on('change',function(){
  var x = $(this).parent('div').html();
  alert(x);
})​​​;
  • val() is for form fields only
  • this should not be quoted.

Alternative

If you only want the text of the parent, you can use text(). However, browsers can differ on how they implement it (see the notes here). In this case, it's probably cleaner to wrap the content you want in another element, like:

<div>
  <span>my content of the div1</span>
  <input/>
</div>​

And use script like:

$('input').on('change',function(){
  var x = $('this').siblings("span").html();
  alert(x);
})​​​;

You can ge the contents of the div with .html(), not with .val() method. The .val() method is primarily used to get the values of form elements such as input, select and textarea. See here for details.

jQuery val() only works on inputs not on generic html elements.

Change $('this') to $(this). (remove the quotes).

.val() doesn't exist for others tags than select/input/textarea tags. I'll suggest that you use .text() function or .html(), depending on what you would like to retrieve.

your code should be like this

$('input').on('change',function(){
  var x = $(this).parent('div').text();
// OR var x = $(this).parent('div').html();
    alert(x);
})​​​;

use this

$('input').bind('keyup',function(){ 
alert($(this).parent().html());
})

本文标签: javascriptget the div val() where the input was changedStack Overflow