tags:

views:

74

answers:

2

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 ($(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>
+1  A: 
MikeWyatt
Thanks for the suggestion. That variable was a problem but it is not the actual problem. Problem I know is that the following won't work because obj has 'every' node apart from the text nodes. So, the childnode of the label is null and hence I cannot compare it with meta[3]. Any suggestions on this? <code>$(obj).find("label").text() == meta[3]</code>
AJ
See the firebug screenshot here. http://docs.google.com/View?id=atq8cnxdprj_478fr49zqdc
AJ
See my test page: http://www.stupidbydesign.com/custom.htmlIt does not work. Am I doing something wrong?
AJ
My answer works, but I think K Prime's answer is simpler and better. I think you should accept his answer.
MikeWyatt
+2  A: 

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 ();
K Prime
Spot on! Oh me dumb. Thanks to all the helpful people here.
AJ