0

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/

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Ben
  • 4,281
  • 8
  • 62
  • 103
  • http://jsfiddle.net/QQLvX/2/ – Satpal Apr 30 '14 at 16:26
  • You aren't passing `this` to the `editMode()` function which is why the second version of `editMode()` that is trying to use `this` doesn't work as `this` is reset on each function call. I'd suggest passing the starting point as an argument to `editMode(where)` and using that. – jfriend00 Apr 30 '14 at 16:38
  • Essentially the same as [How to reach the element itself inside jQuery’s `val`?](/q/16710521/4642212). – Sebastian Simon Feb 08 '22 at 04:33

2 Answers2

3

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

Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use .each()

$('.editableField').each(function(){
    $(this).val($(this).siblings(".staticField").html());
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95