How to show different selected value than options label - javascript

I have simple html select:
<select id="mySelect" style="width:10em">
<option value="val1">Some long text for val 1</option>
<option value="val2">Some long text for val 2</option>
<option value="val3">Some long text for val 3</option>
</select>
opened combo box:
I dont see what I've selected, I don't want to set width, I want to show different text.
I want to keep those long texts in floating panel, but when option is selected, I want to see some short version to see option in small space.Is there any solution to show different text in closed than in opened mode?

I solved this problem using jQuery by adding hidden option that decouples selected value and text. Just override that this hidden option will be selected always and update its value to whatever you want. In this case I used value as text, but it can be stored in some custom a
var val = $("#mySelect").val();
var lbl = $("#mySelect option:selected").text();
$("#mySelect").prepend("<option value='" + val + "' data-value='selected' selected hidden>" + val + "</option>");
$("#mySelect").on('change', function() {
var val = $("#mySelect").val();
var lbl = $("#mySelect option:selected").text();
$("#mySelect option[data-value='selected']").attr('value', val);
$("#mySelect option[data-value='selected']").text(val);
$("#mySelect").val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h2>
jQuery hidden option
</h2>
<select id="mySelect" style="width:10em">
<option value="val1">Some long text for val 1</option>
<option value="val2">Some long text for val 2</option>
<option value="val3">Some long text for val 3</option>
</select>
Other approach is use bootstrap-select like in example:
<select class="selectpicker">
<option title="Combo 1">Hot Dog, Fries and a Soda</option>
<option title="Combo 2">Burger, Shake and a Smile</option>
<option title="Combo 3">Sugar, Spice and all things nice</option>
</select>

Related

How to Hide the Certain Text Value of Selected Option using jQuery

I have a select box that contains certain elements (see below):
<select id="test" name="test">
<option value="12345">12345 - Test</option>
<option value="67890">67890 - Test 2</option>
<option value="53453">53453 - Test 3</option>
</select>
Here is what I'm trying to accomplish When the user selects a certain element, I want certain elements of the text to hide. For example, if I select 12345, I want the - Test to hide.
How can I do it in jQuery?
Thank you,
Kevin
A brute force-y way to do it would be to keep track of the internal text and values of the currently-selected option, then replace the text with the desired text when the option changes. This part's easy in your case, since the desired output text is the same as the option's value.
I opted to add a blank option at the beginning, since by default the text will not have changed, but you can get around this by adding a trigger to go off when the page is finished loading.
var selectedTextOrig = "";
var selectedValue = 0;
$("#test").change(function() {
// Reset the inner html text for the previously-selected option
$("#test option").each(function() {
if ($(this).val() == selectedValue) {
$(this).text(selectedTextOrig);
return false; // break out of $.each()
}
});
// Store the viewable text and value of the currently selected
selectedValue = $("#test option:selected").val();
selectedTextOrig = $("#test option:selected").text();
// Replace the current inner html
$("#test option:selected").text(selectedValue);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="test" name="test">
<option disabled="disabled" selected></option>
<option value="12345">12345 - Test</option>
<option value="67890">67890 - Test 2</option>
<option value="53453">53453 - Test 3</option>
</select>
I have found a solution:
Here is how I achieved it:
$('select[name="test"]').find('option').remove().end();
$('select[name="test"]').append(new Option(selectId, selectId));
$('select[name="test"]').trigger('change');

Show Value Instead of text in select option

I have country codes dropdown list, in select option text there countryname and ISD Code together, but I want only show ISD Code after Selection.
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
I have searched for some other forums but I am not able to get how to do this. like if we select Anguilla, then it should show +1 there and if it is selected Angola, it should show +244
A solution with only a <select> element.
How it works:
Initializes a hidden <option> that will be used for showing the selected option's value.
When an option is selected:
affects to the hidden option's value attribute and text content the value attribute of the just selected option if this value is not empty. Then shows that hidden option.
empties value and text content of that option, then hides it, if the chosen value is empty (Country code option here).
document.addEventListener('DOMContentLoaded', () => {
const select = document.querySelector('select');
select.addEventListener('change', () => {
const value = select.value,
showValueOption = select.querySelector('.show-value');
if (value === '') {
showValueOption.style.display = 'none';
showValueOption.value = '';
return;
}
showValueOption.style.display = '';
showValueOption.innerText = value;
showValueOption.value = value;
select.selectedIndex = 0;
});
});
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option class="show-value" value="" style="display:none;"></option>
<option value="" selected>Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
You can handle change event of select tag like this.
I updated code for display selected value as selected text.
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
})
$("#country_isd_code").change(function(){
$("#codeselect").val($(this).val());
//$("#country_isd_code option:selected").text($(this).val());
$("#selecteditem").val($(this).val())
$("#selecteditem").text($(this).val())
$("#selecteditem").prop('selected', true);
$("#selecteditem").show();
})
#selecteditem{
display:none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control-input" name="country_isd_code" id="country_isd_code">
<option id="selecteditem" value=""></option>
<option value="">Country Code</option>
<option value="+244">Angola (+244)</option>
<option value="+1">Anguilla (+1)</option>
</select>
<input type="text" id="codeselect" />

Generate text on a webpage which depends on dropdown box options

I have created a dropdown box with 3 options on my website.
I want to change some text on the webpage, depending on the drop-down item selected. For example:
If dropdown option 1 is chosen, I would like some text on the page that says "You have chosen option 1".
I don't know any JavaScript and so I haven't tried anything apart from trying to search for a similar solution.
<select name="os0" style="background: #315d80; color: #fff; border-color: white; border: 0px;">
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
<option value="op3">Option 3</option>
</select>
Full sultion with jQuery (I started typing it before you added the HTML to your question so the options are italian car brands).
https://jsfiddle.net/mL2c2xb6/
HTML:
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
Javascript:
$('select').change(function(){ // Listen to changes to <select> element
const options = $("option"); // Get all the <option> elements.
let selectedOption = ""; // Var to store selected option value.
options.each(function(index){ // Iterate through option elements.
let option = options[index];
if($(option).prop("selected")) { // Find the seletced one.
selectedOption = $(option).val(); // Get the value and store it
};
});
$("#choiceDisplay")
.empty()
.append(selectedOption); // Display the result.
});
var e = document.querySelector('[name="os0"]');
var strUser = "";
e.addEventListener("change", function(){
strUser = e.options[e.selectedIndex].innerHTML;
alert("You have chosen " + strUser);
});

remove selected value from select box using jquery but It's need to display current selected value in select box?

I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>

Select the first option by value when there are duplicate values

I have a select list that contains duplicate values. I don't have the power to change this.
<select id="dropdown">
<option value="1">Item 1</option>
<option value="1">Item 1 again under a different name</option>
<option value="2">Item 2</option>
</select>
In a different place, I have a link element that, when clicked, calls $("#dropdown").val(1). This "Item 1 again under a different name" to be selected and displayed. I want "Item 1" to be selected instead. How can I accomplish this?
To do that you can select the option element by the value attribute and use the :first selector. Try this:
var value = 1;
$('#dropdown option[value="' + value + '"]:first').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
<option>Please select...</option>
<option value="1">Item 1</option>
<option value="1">Item 1 again under a different name</option>
<option value="2">Item 2</option>
</select>
Try This :
$("#dropdown option[value=1]:first").prop({selected:true});
I guess there will be only one duplicate value in dropdown. First you need to find that value than select first option of same value.
var arrDuplicate = [];
var duplicateVal = 0;
$("#dropdown option").each(function () {
if (arrDuplicate.indexOf($(this).val()) > -1)
duplicateVal = $(this).val();
arrDuplicate.push($(this).val());
});
$("#dropdown option[value=" + duplicateVal + "]:first").attr("selected", "selected");

Categories