I am trying to create a custom jQuery selector that will put focus() on a input text field whose label text is provided by the user.
It is simple, I take the text provided by the user, search for the text node of all labels, get the matching label's 'for' attribute value and use that as an id to get the input element.
My problem is that I am unable to access the text node as the nodes being passed in stack are everything except the text nodes. I checked the child element of the label and it says null in firebug.
Here is what part of the code looks like:
$.expr[':'].findipfromlabel = function(obj, index, meta, stack) {
if($(obj).find("label").text() == meta[3]) {
var forattr = $(obj).attr('for');
}
return 开发者_JAVA技巧($(input).attr('id' == forattr));
};
$(document).ready(function() {
$(': findipfromlabel(Male)').focus();
});
In above, label elements are present but there is no child element of that label. There is a next sibling, but how to confirm with label to use unless I know the text node value equals what the user has entered? HTML is:
<form>
<label for="v">test</label>
<input type="text" name="v" id="v" /><br/>
<label for="male">Male</label>
<input type="text" name="m" id="male" />
<br />
<label for="fe">Female</label>
<input type="text" name="f" id="fe" />
</form>
You're kinda going about it the wrong way.. it would be much more efficient to search for the appropriate label and then get the id - like so:
var id = $('label:contains(Male)').attr('for');
if (id)
$('#' + id).focus ();
I see two one problems: First, the "forattr" variable is being defined inside the scope of the if block, so it isn't available to your return statement. Second, Your return statement is returning the value of the "true" attribute of the last input on the page, which is probably not what you want.
Try something like this:
$.expr[':'].findipfromlabel = function(obj, index, meta, stack)
{
if($(obj).find("label").text() == meta[3])
{
return $('input#' + $(obj).attr('for'));
}
return null;
};
EDIT: Removed incorrect assumption regarding JavaScript scoping rules.
EDIT: Really works this time:
Okay, I think I have it figured out now for sure. This would be obvious for an expert on custom expressions, but I actually just learned how to write them now. The key is you should simply return true if "obj" is the node you're looking for (i.e. the input), or false if it is not. This works with my test page:
$.expr[':'].findipfromlabel = function(obj, index, meta, stack)
{
var label = $('label').filter( function() { return $(this).text() == meta[3]; } );
if( label.length > 0 )
{
return $(obj).attr('id') == label.attr('for');
}
return false;
};
精彩评论