Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why isn't my element:contains(variable) work when using variable instead of string? jquery

I have a code to get the value of option element and when a button is clicked, it'll find where that value exist in the page so I can add more things into that table / container.

Somehow if I store the value into a variable, it doesn't work. If I type in the string directly into $("blah:contains('blabhblah')" it will work. why?

My example here in html

        <div class="shipping-time-city">
            <label>City: </label>
            <select>
                <option value='bby'>Burnaby (本拿比)</option>
                <option value='van'>Vancouver (温哥华)</option>
                <option value='rmd'>Coquitlam (高贵林)</option>
            </select>
        </div>

other places in the body I have something like

<caption>Coquitlam (高贵林)</caption> <caption>Burnaby (本拿比)</caption> <caption>Vancouver (温哥华)</caption>

so in jquery I used click function and this is what I have inside click function

var getCity = $( ".shipping-time-city option:selected" ).text();
($("caption:contains(getCity)").text('bye')  //just for testing

the above wouldn't work but if I do it like this

($("caption:contains('Burnaby (本拿比)')").text('bye')

it will work, but I tried console.log(getCity) which gives me the output of Burnaby (本拿比)

can someone give me a hand on what I am doing wrong here?

Thanks a lot.

like image 628
Dora Avatar asked Mar 22 '26 06:03

Dora


1 Answers

since getCity is a variable, would it not be:

($("caption:contains('" + getCity + "')").text("bye");
like image 100
gavgrif Avatar answered Mar 24 '26 18:03

gavgrif



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!