Guruprasad J Rao
Guruprasad J Rao

Reputation: 29693

how to update bootstrap select's data-original-index with original select option's value

I have a select button where I load various list option from database.

I convert this select button to bootstrap's select-picker. Now when it renders it hides original select option and creates it's own view.

My select option will render id as value and it will be as rendered as below.

<option value="38">option 1</option>

<option value="37">option 2</option>

<option value="36">option 3</option>

But then when I see bootstrap's UI it will have a option called data-original-index like this

<li data-original-index="1">option 1</li>

<li data-original-index="2">option 2</li>

<li data-original-index="3">option 3</li>

which is nowhere related to my original options and the above render creates a problem for me when I fetch the selected option's value.

Is there any way to render value of data-original-index with my original's option's value??? Any suggestions are welcome!

Upvotes: 1

Views: 6441

Answers (1)

Mouser
Mouser

Reputation: 13304

You can attach an onchange event to the original select. Bootstrap is tied into that select. So if you select an option from the bootstrap select it will allow you to retrieve the selected value.

$(this).find("option:selected").attr("value"); This line seeks the selected option and returns the attribute value.

See this example:

$(function() {

  $('.selectpicker').on('change', function(){
    var selected = $(this).find("option:selected").attr("value");
    alert(selected);
  });
  
});
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/css/bootstrap-select.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.6.3/js/bootstrap-select.js"></script>

<select class="selectpicker">
   <option value="38">option 1</option>
   <option value="37">option 2</option>
   <option value="36">option 3</option>
</select>

Upvotes: 2

Related Questions