0

Let's say I want option C preselected when I load the page with a hash value of C appended to the URL (ex. http://www.example.com/#C).

I know how to get the value from the hash, but I'm having trouble on selecting the option.

I tried the following using jQuery:

$('.dropdown ul > li > a:contains("C")').click();
$('.dropdown ul > li > a:contains("C")').trigger('click');

but the value selected on the dropdown menu doesn't change

<div class="dropdown open" style="float:none;margin-top:5px;" id="select-group-0">
  <input type="hidden" value="A" name="your-category" id="undefined" class="wpcf7-form-control wpcf7-select wpcf7-validates-as-required">
  <a id="contactform_type" class="dropdown-toggle dropdown-toggle-filter fp_input contactform_dropdown" data-toggle="dropdown" href="#">A</a>
  <ul class="dropdown-menu dropdown-menu-filter">
     <li><a tabindex="-1" data-value="A">A</a></li>
     <li><a tabindex="-1" data-value="B">B</a></li>
     <li><a tabindex="-1" data-value="C">C</a></li>
  </ul>
</div>
1
  • 1
    it likely that your click trigger is firing before bootstrap is applied. check when it's called and delay if necesary. Also, you dont need .trigger('click') simply calling .click() with no params is the same. Commented Mar 3, 2014 at 23:18

1 Answer 1

1

I'm not sure wether you're trying to change the selected value of the dropdown to "C", or just highlight "C" in the dropdown list... Assuming you're trying to "change the selected value of the dropdown to C", you can use something like this..

/* update dropdown text when item clicked */
$(".dropdown-menu li a").click(function(){
  var selText = $(this).text();
  $(this).parents('.dropdown').find('.dropdown-toggle').html(selText);
});

/* preselect value */
var selectedValue = "C";
$('.dropdown ul > li > a:contains("'+selectedValue+'")').parent('li').addClass("active");
$('.dropdown ul > li > a:contains("'+selectedValue+'")').trigger('click');

Demo: http://www.bootply.com/118698

If you're only try to highlight "C" in the dropdown list, you'd just remove the call to trigger('click').

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

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.