Getting the value of an element in jQuery
My code is working good thanks to the help of members here. Now I have one last step / request. I have the following code that some may have seen before just in the last hour:
<script type="text/javascript">
$(document).ready(function () {
$("[id^=topic]").change(function () {
var a = 'pk' + $(this).attr('id').replace('topic', '');
var b = $(a).val()
alert(b);
});
});
</script>
and then later on:
<td id='开发者_StackOverflowpk_1'>Cat</td>
<td id='pk_2'>Dog</td>
This code picks out pk_1, pk_2 etc and places into the variable named "a". What I would like is not to get the value of the element pk_1. I tried some different ways of getting this and putting into "b". For example I added "#". None work. Sometimes the alert box shows the word "undefined" sometime nothing. Anyone have any suggestions?
Thank you all
Use .html()
instead of .val()
:
...
var a = '#pk' + $(this).attr('id').replace('topic', '');
var b = $(a).html();
alert(b);
A couple of things
$(document).ready(function () {
$("[id^=topic]").change(function () {
var a = '#pk_' + $(this).attr('id').replace('topic', ''); //add # and _
var b = $(a).html(); //use .html and not .val
alert(b);
});
})
This should work for you.
Since it's an id the selector should start with #
. Prepend that to the selector. Also, a td
element doesn't have a value
, only input
elements do. You probably want the inner text
(or, perhaps, the html
). If that's not working, then check that the ids are what you expect.
<script type="text/javascript">
$(document).ready(function () {
$("[id^=topic]").change(function () {
var a = '#pk' + $(this).attr('id').replace('topic', '');
var b = $(a).text()
alert(a + ' has value ' + b);
});
});
</script>
Based on the fact that a very specific id, say id='topic_1' corresponds to exactly id='pk_1', I would say that you should be skipping over the whole replacing/manipulating id tags to find another.
Instead use the metadata plugin.
<input type=text id="topic1" class="topic {pk:#pk_1}"/>
<input type=text id="topic2" class="topic {pk:#pk_2}"/>
In script:
$(document).ready(function () {
$(".topic").change(function () {
alert($($(this).metadata().pk).html());
}
}
metadata can be downloaded here:
http://plugins.jquery.com/project/metadata
精彩评论