0

I have this menu. When I click on a dropdown item, I need to do something.

<div class="navbar-collapse collapse" style="float:right;">
        <ul class="nav nav-tabs" role="tablist">

          <ul class="nav nav-tabs" role="tablist">
              <li class="active"><a href="#home" role="tab" data-toggle="tab">Home</a></li>
              <li><a href="#about" role="tab" data-toggle="tab">About</a></li>

            <li class="dropdown">
              <a href="#" class="dropdown-toggle" data-toggle="dropdown">Applications <span class="caret"></span></a>
              <ul class="dropdown-menu" role="menu">
                <li><a role="tab" data-toggle="tab"href="#test1">app1</a></li>
                <li><a role="tab" data-toggle="tab"href="#test2">app2</a></li>
                <li><a role="tab" data-toggle="tab"href="#test3">app3</a></li>
                <li><a role="tab" data-toggle="tab" href="#test4">app4</a></li>
                <li><a role="tab" data-toggle="tab"href="#test5">app5</a></li>
              </ul>
            </li>
          </ul>

        </div>

when I pick test1 from the dropdown menu, I need to do something, run a function.

I have done this:

<script>
$('#test1').on('click', function () {
  // do something…
  alert(this.val());
});
</script>

Does not seem to be working, no errors. Any ideas? I'd appreciate any insight.

1
  • 2
    The selector #test1 is looking for an element with the ID test1, not an href. Change your selector to $("a[href='#test1']").on...., or simply give the a tags an id like <a id="test1".... Commented Aug 26, 2014 at 20:06

3 Answers 3

2

You can use the following:

$('a[href*="test1"]').on('click', function () {
  alert($(this).text());
});

The star designates that the proceeding value must appear somewhere in the attribute's value.

fiddle

Sign up to request clarification or add additional context in comments.

Comments

2

You are calling an ID that doesn't exist:

<li><a role="tab" data-toggle="tab"href="#test1">app1</a></li>

You need to add an ID:

<li><a id="test1" role="tab" data-toggle="tab"href="#test1">app1</a></li>

Comments

1

If you are trying to grab the href="#test". Use the attribute starts with selector. This will grab any element that has an href that begins with '#test':

Also you should change your this reference to $(this) and use text(), not val().

$("a[href^='#test']").on('click', function () {
  // do something…
  alert($(this).text());
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.