Ben
Ben

Reputation: 4319

How do I get an elements sibling in JQuery, in a function?

I am trying to set an element to have the same value as its sibling in JQuery.

I have a table with a number of fields in, and when I click an Edit button I want to copy the value of a label to it's neighbouring input field:

<table style="width:90%">
  <tr>
    <td>Start</td>
    <td>
       <span ID="lblSprintStart" class="staticField">01/01/2001</span>
       <input class="editableField" id="sprintStart" />
    </td>
   </tr>
   <tr>
     <td>End</td>
     <td>
       <span ID="lblSprintEnd" class="staticField">02/02/2002</span>
       <input class="editableField" id="sprintEnd" />
     </td>
    </tr>
 </table>
<button id="editButton">Edit</button>

I can do it by targeting each individual element by ID:

$(function () {
 $("#editButton")
  .click(function (event) {
   event.preventDefault();
   editMode();
 }); 
});

function editMode() {     
  $("#sprintStart").val($("#sprintStart").siblings(".staticField").html());
}

But I want to do it by class so all fields are updated. If I change the function to use the $(this) selector and do it by class it doesn't work:

function editMode() {     
   $(".editableField").val($(this).siblings(".staticField").html());
}

http://jsfiddle.net/QQLvX/1/

Upvotes: 0

Views: 47

Answers (2)

Satpal
Satpal

Reputation: 133403

You can use .val( function(index, value) )

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

Code

$(".editableField").val(function(){
    return $(this).siblings(".staticField").html();
});

DEMO

Upvotes: 3

Amit Joki
Amit Joki

Reputation: 59232

Use .each()

$('.editableField').each(function(){
    $(this).val($(this).siblings(".staticField").html());
});

Upvotes: 1

Related Questions