fightstarr20
fightstarr20

Reputation: 12568

jQuery - div:contains not working

I am trying to have jquery automatically fill an input if there is a specific phrase in a div

Here is what I have so far....

<li>
    <div>
        <div class="gfield_admin_header_title">Orange</div>
            <div>
                <ul>
                    <li><input type="text" id="field_css_class" /></li>
                </ul>
            </div>
        </div>
    </div>
</li>
<li>
    <div>
        <div class="gfield_admin_header_title">Apple</div>
            <div>
                <ul>
                    <li><input type="text" id="field_css_class" /></li>
                </ul>
            </div>
        </div>
    </div>
</li>
<li>
    <div>
        <div class="gfield_admin_header_title">Pear</div>
            <div>
                <ul>
                    <li><input type="text" id="field_css_class" /></li>
                </ul>
            </div>
        </div>
    </div>
</li>

$("div > div:contains('Orange')").find("#field_css_class").val('DesiredVal');

This isn't working for me, if I use...

$("div").find("#field_css_class").val('DesiredVal');

Then it does change the input but does it for all instances of #field_css_class (as expected)

So i am assuming its my div:contains that it doesn't like, can anyone help?

Upvotes: 0

Views: 275

Answers (3)

Felix
Felix

Reputation: 38102

You can use:

$.each($('.gfield_admin_header_title'), function () {
    if ($(this).text() == "Orange") {
        $(this).next().find('.field_css_class').val('DesiredVal');
    };
});

Some notes:

1) id should be unique, you should use class instead (in this case .field_css_class)

2) Your HTML markup seem wrong, you have redundant closing </div> tag before last div inside each li

3) Above code check whether the text inside your expected div is orange or not, if yes then change the next input value.

Fiddle Demo

Upvotes: 1

Paulo Lima
Paulo Lima

Reputation: 1238

I think you should use the class, because id is not advisable to be repeated and there you can take it directly

$(".className").val("value")

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

First id must be unique so use field_css_class as a class attribute instead of using it as an id then

$("div").has('> div:contains("Orange")').find(".field_css_class").val('DesiredVal');

Demo: Fiddle

The problem is the element field_css_class is not an descendant of the div containing the text Orange, it is a descendant of a sibling element

Note: In your markup there is an extra </div> at the end of each li element

Upvotes: 1

Related Questions