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 forhtml()
? – Tim M. Commented Oct 3, 2012 at 7:54
8 Answers
Reset to default 6You 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 onlythis
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
版权声明:本文标题:javascript - get the div val() where the input was changed - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742381467a2464180.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论