Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show first character of selected option in Select

I have a select box like this:

<select id="selectbox1">
  <option value="s">Second</option>
  <option value="m">Minute</option>
  <option value="h">Hour</option>
  <option value="d">Day</option>
  <option value="w">Week</option>
  <option value="t">monTh</option>
  <option value="y">Year</option>
</select>

I want when I select for example 1st option second Just S appear on select box and so on. and when its open for another select again show Second.

like image 538
Maysam Avatar asked Jan 08 '14 08:01

Maysam


People also ask

How do I get the first select option?

Select the <select> element using JQuery selector. This selector is more specific and selecting the first element using option:nth-child(1). This will get access to the first element (Index starts with 1).

How do I get selected text option in select?

To get the text of the selected option, we first need to find the selected option using the find() method and then use the text() method to get the option text. where selectBox is the value of the id attribute of the <select> HTML tag.

How do you display a selected value in a drop down list?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.


1 Answers

Try this:

Add one hidden option and on selection of option take the text of value and insert into hidden option and make it selected forcefully everytime.

$('#selectbox1').on('change', function(){                                           
    var option = $(this).find('option:selected');
    $('.hide').text(option.val()).val(option.val());    
    $('.hide').data('value', option.text());
    $('.hide').attr('selected', true);        
});

To get the selected option value and text, you can this:

$(this).find('option:selected').val();
$(this).find('option:selected').data('value');

DEMO Link

like image 124
brg Avatar answered Oct 13 '22 01:10

brg