er_benji
er_benji

Reputation: 305

Select programmatically an element from a dropdown button

I need to select programmatically (javascript) an element from a dropdown button:

          <div class="form-group">
            <label class="col-lg-3 control-label">Button</label>
            <div class="col-lg-9">
              <div class="btn-group m-r">
                <button data-toggle="dropdown" class="btn btn-md btn-default dropdown-toggle">
                  <span class="dropdown-label" data-placeholder="Please select">Option 1</span> 
                  <span class="caret"></span>
                </button>
                <ul class="dropdown-menu dropdown-select">
                  <li id="properties_form_1" class="active"><a href="#"><input type="radio" name="d-s-c-1">Option 1</a></li>
                  <li id="properties_form_2"><a href="#"><input type="radio" name="d-s-c-1">xxx</a></li>
                  <li id="properties_form_3"><a href="#"><input type="radio" name="d-s-c-1">xxxx</a></li>
                  <li id="properties_form_4"><a href="#"><input type="radio" name="d-s-c-1">xxx</a></li>
                  <li id="properties_form_5"><a href="#"><input type="radio" name="d-s-c-1">xxxxx-Pair</a></li>
                </ul>
              </div>
            </div>
          </div>

[UPDATE] I have tried the following:

    order_form_div.find("[id^='properties_form_']").each(function(){
    console.log("id: " + $(this).attr('id'));
    $(this).removeClass('active');  
});
order_form_div.find("#" + item.productType).addClass('active');

And it puts the correct item active but the text in "Option 1" is not updated. So, instead of changing this text manually, I suppose that there are any elegant way to do it.

Upvotes: 1

Views: 1244

Answers (2)

Will Lanni
Will Lanni

Reputation: 921

Once you've switched the selected property to the option you wish to be selected, run

 $('.dropdown-menu').selectpicker('refresh');

This should update the button. (might need to run it on btn-group, not sure from your structure)

Upvotes: 2

phylax
phylax

Reputation: 2086

a shot in the dark:

// deactivate all
$('.dropdown-menu li').removeClass('active');

// the id of the element to select
var selected = 'properties_form_2';

// set active class
$('#' + selected).addClass('active');
// check radio-button
$('#' + selected + '.active input').prop('checked', true);

Upvotes: 0

Related Questions