user3390251 user3390251 - 1 year ago 120
jQuery Question

JqueryTrigger / click anchor tag click from a variable

I created a variable that pulls the value from a div. This works.

<input type="text" id="myDiv" class="input"> FOO </input>

var whatsInMyDiv = $('#myDiv').val();

That value will match the text of any one of my list items below.

<li><a href="#FOO" value="#FOO">FOO</a></li>
<li><a href="#BAR" value="#BAR">BAR</a></li>

How do I trigger the 'clicking' of the correct anchor tag from my dynamic variable?

Something like this, which doesn't work obviously:


Answer Source

You need to give an ID selector with #

$("#" + whatsInMyDiv).click()

And add those ids to your a elements maybe instead of useless value.

<li><a href="#FOO" id ="FOO">FOO</a></li>
<li><a href="#BAR" id ="BAR">BAR</a></li>

Or if you really need to leave html like it is use another selector:

$("a[value='#" + whatsInMyDiv + "']").click()
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download