jQuery replace text of element
I am trying to replace a div in a jQuery dropdown box. The value to be replaced is the "header" of the dropdown box that says "Pick alternative:" when nothing is picked. Then when the user chooses an alternative from the dropdown, that alternative gets highlighted and also replaces "Pick alternative:" so that the user can see what they chose when closing the dropdown.
How would I do this?
The HTML:
<div class="step_content">
<div class="vertical_text">Choose alternative</div>
<div class="vertical_content dropdown_fade">
<div class="menu_corner top_left_vertical"></div>
<div class="menu_corner top_right_vertical"></div>
<div class="button_slide" rel="slide1">Pick alternative:</div>
<div class="content_slide slide1">
<input id="Button19" class="button_vertical damage_button" type="button" value="Alternative 1" size="10px" />
<input id="Button20" class="button_vertical damage_button" type="button" value="Alternative 2" />
</div>
<div class="menu_corner bottom_left_vertical"></div>
<div class="menu_corner bottom_right_vertical"></div>
</div>
</div>
I have the following lines of JavaScript. 开发者_如何学GoI'm not sure how to continue doing this.
$(function () {
$('.damage_button').click(function () {
$('.button_slide').replaceWith("<div class='some_class' >" + $(this) + "</div>");
});
});
I get it to replace what I want to be replaced but it just shows "[Object object]".
$(function () {
$('.damage_button').click(function () {
$('.button_slide').replaceWith("<div class='some_class' >" + $(this).val() + "</div>");
});
});
Use val()
for INPUT
elements (a button is an INPUT
element), and html()
or text()
for a non-INPUT
elements.
The reason you get [Object object]
is because when you simply do $(this)
and concatenate it to a string, you are calling the jQuery object's toString()
which doesn't return what you want. You want the actual text of the button, which you get by using val()
.
Use .val()
to get the clicked <input>
element's value, like this:
$(function () {
$('.damage_button').click(function () {
$('.button_slide').replaceWith("<div class='some_class' >" + $(this).val() + "</div>");
});
});
In this case this
refers to the <input>
you want, but $(this)
is a jQuery object..which gives a .toString()
of [Object object]
, you want .val()
to get the value.
精彩评论