Reputation: 5827
I am building an app with Bootstrap. In this app, I have a control that converts a value between imperial and metric values. To accomplish this, I currently have the following:
<div class="input-group">
<input type="text" class="form-control">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Action <span class="caret"></span>
</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li><a href="#" data-type="lb">Pounds</a></li>
<li><a href="#" data-type="kg">Kilograms</a></li>
</ul>
</div>
<input id="theValue" type="hidden" data-start-type="kg" />
</div>
When the control theValue
element is populated from the server, it will either be "lb" or "kg". I want to make it so that the selected menu option is based on the value of theValue
when the page initially loads. In other words, I do not want to see the text "Action". Instead, I need to select either Pounds or Kilograms when the view loads.
How do I do this from jQuery?
Upvotes: 3
Views: 9089
Reputation: 13178
Using jQuery, you would select the theValue
element, access its data-start-type
attribute, find the a
element with the same data-type
attribute, and then use its text
value to set the text of the button. You'll want a unique way to identify the button for selection in jQuery, so give it an id
; I used "actionButton".
$(document).ready(function(){
var data_start_type = $('#theValue').attr('data-start-type');
var $data_type_elem = $('[data-type='+data_start_type+']');
$('#actionButton').text($data_type_elem.text());
});
Here's a jsFiddle: http://jsfiddle.net/7g9k2dwx/
Upvotes: 2