Search code examples
jquerylabelselectorcontainsstartswith

jquery selector for label content


I would like to find a jquery selector for a label with a specific content.

So with the following html

<label for="foo1">Name</label>
<input type="text" name="foo1" id="foo1" value="Fadime"/>

<label for="foo2">SecondName</label>
<input type="text" name="foo2" id="foo2" value="Alice"/>

I want to be able to get the content "Fadime" by accessing it through the content of the preceeding label. I don't want to use the name of the input or the id since they are autogenerated and may change. The content of the label though will remain the same. For the second name I know I can use:

var second_name = $("label:contains('SecondName')").next().val();

However, I can't get the content of the first name with:

var name = $("label:contains('Name')").next().val();

since that will match both labels (since both contain "Name").

Is there some equals-method or startsWith so I could use

var name = $("label:equals('Name')").next().val();

Thanks in advance!


Solution

  • The :contains is used for elements. Not for text. You need to use a .filter():

    $(function () {
      $("label").filter(function () {
        return $(this).text().indexOf("SecondName") > -1;
      }).next("input").val("Ha ha ha!");
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label for="foo1">Name</label>
    <input type="text" name="foo1" id="foo1" value="Fadime"/>
    
    <label for="foo2">SecondName</label>
    <input type="text" name="foo2" id="foo2" value="Alice"/>

    Getting the second name printed to the console:

    $(function() {
      console.log(
        $("label").filter(function() {
          return $(this).text().indexOf("SecondName") > -1;
        }).next("input").val()
      );
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <label for="foo1">Name</label>
    <input type="text" name="foo1" id="foo1" value="Fadime" />
    
    <label for="foo2">SecondName</label>
    <input type="text" name="foo2" id="foo2" value="Alice" />