开发者

How to replace the text of an element with the value of another inside of a specific parent tag using jQuery?

开发者 https://www.devze.com 2023-02-04 17:39 出处:网络
High level: How do I replace the text of an element with the value of another inside of a specific parent tag?

High level: How do I replace the text of an element with the value of another inside of a specific parent tag?

Specific: Using the HTML below, I want to replace the html of "span.number" with the value of "input.someOtherNumber". I can have multipul of these list items on a page so it needs to be narrowed down using the parent.

<ul>
 <li class="list-item">
    <span class="number">0</span>
    <input class="someOtherNumber" type="text" value="10" />
 </li>

 <li class="list-item">
    <span class="number">0</span>
    <input class="someOtherNumber" type="text" value="99" />
 </li>
</ul>

The following JS works to replace the "span.number" value with the value of "inout.someOtherNumber" but it doesn't limit it to the parent. How can I limit it to the parent?

    $(".someOtherNumber").keyup(function () { 
      var value = $(this).val();
      $(".number").text(value);
    }).keyup();

EDIT:

If the input is wrapped in a span then how do I accomplish it? I am really looks for a solution that checks for a parent because in my real code I have multipul elements that can nested inside of each other so the ".sibling" or ".prev/.next" will not work. The updated HTML would look like this:

<ul>
 <li class="list-item">
    <span class="number">0</span>
    <span><input class="someOtherNumber" type="text" value="10" /></span>
 </li>

 <li class="list-item">
    <span class="number">0</span>
    <span><input class="someOtherNu开发者_开发技巧mber" type="text" value="99" /></span>
 </li>
</ul>

You can see it here: http://jsfiddle.net/8bXbx/


Replace:

$(".number").text(value);

With:

$(this).prev(".number").text(value);

..fredrik


You can use siblings:

$(".someOtherNumber").keyup(function() {
    $(this).siblings(".number").text(this.value);
}).keyup();

Example: http://jsfiddle.net/jonathon/j9aaX/

Also, because this is a HTML Input element, you can just access the value using this.value


Just in reply to your comment. In order to get the element based on the common parent, you'd use closest to go up the tree to the parent element and then children to go back down the tree and get the element you want.

$(".someOtherNumber").keyup(function() {
    $(this).closest(".list-item").children(".number").text(this.value);
}).keyup();

Example: http://jsfiddle.net/jonathon/j9aaX/1/

0

精彩评论

暂无评论...
验证码 换一张
取 消