use JQuery to get siblings
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$ddlSou开发者_如何转开发rceFields" 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
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.
try:
$(this).parent().children("input:first").val();
The appendfield method does not access to $(this).
Here is the working code: http://jsfiddle.net/NBf4d/2/
use .children() or .find()
.children only looks for direct children of the parent, find looks at all levels below the parent.
$('.ms-formbody').find('select').val();
This will only work for these IDs, but you can easily change them:
$('#ctl00_PlaceHolderMain_dlFields_ctl00_txtSource').val($('#ctl00_PlaceHolderMain_dlFields_ctl00_ddlSourceFields').val());
try this...
$(this).parent().find('input:first').val(selectedOptionValue);
精彩评论