Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use JQuery to get siblings

Tags:

jquery

I'm trying to get the a tag below to grab the value from the select and paste it into the input.

<td class="ms-formbody" style="width:385px">
    <input name="ctl00$PlaceHolderMain$dlFields$ctl00$txtSource" type="text" id="ctl00_PlaceHolderMain_dlFields_ctl00_txtSource" class="ms-input" />
    <select name="ctl00$PlaceHolderMain$dlFields$ctl00$ddlSourceFields" id="ctl00_PlaceHolderMain_dlFields_ctl00_ddlSourceFields" class="ms-input">
        <option value="Some Field Name 1">Some Field Name 1</option>
        <option value="Some Field Name 2">Some Field Name 2</option>
        <option value="Some Field Name 3">Some Field Name 3</option>
        <option value="Some Field Name 4">Some Field Name 4</option>
    </select>
    <a href="javascript: appendField();">append</a>
</td>

I can't seem to figure out how to grab siblings. I tried $(this).siblings("input").val() but that errored Webpage error 'parentNode.firstChild' is null or not an object.

Tried $(this).prev().prev().val() and that comes back undefined. What's the best way to grab these things?

Thanks, David

like image 524
David Lozzi Avatar asked Feb 18 '11 05:02

David Lozzi


3 Answers

Your issue stems from your approach. Calling a function directly won't do what you're expecting, which is to have a jquery object representing the <a> tag. Rather than call a function directly you can register a function to respond to a click event on the <a>.

First, give your link an id:

<a href="#" id="appendSelect">append</a>

Then use replace your appendField() function with a jQuery select that responds to click

$(document).ready(function() {
  $("#appendSelect").click(function() {
    var $thatInput = $(this).siblings("input");
    var $selectValue = $(this).siblings("select").val();
    $thatInput.val($selectValue);
  })
});

With this approach $(this) will represent your <a>.

You can see what I'm talking about to a greater depth by using a javascript debugging console (chrome has one by default, and you can use Firebug on Firefox). Try your original function based approach again and add a console.log($(this)); statement. You should see it printing out a DOMWindow object. Now put the same log statement in the click function and you'll see that jQuery has given you a $(this) representing what you expected it to be.

like image 70
Tim Bielawa Avatar answered Oct 13 '22 08:10

Tim Bielawa


try:

$(this).parent().children("input:first").val();
like image 31
Darko Z Avatar answered Oct 13 '22 07:10

Darko Z


The appendfield method does not access to $(this).

Here is the working code: http://jsfiddle.net/NBf4d/2/

like image 23
krishna Avatar answered Oct 13 '22 08:10

krishna