How to get the display value of Select using javascript - javascript

<Select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</Select>
I am using document.getElementById("Example").value; to get the value.
I want to display the text instead of the value. eg. value=1 --> One. How can I get the One text?

In plain JavaScript you can do this:
const show = () => {
const sel = document.getElementById("Example"); // or this if only called onchange
let value = sel.options[sel.selectedIndex].value; // or just sel.value
let text = sel.options[sel.selectedIndex].text;
console.log(value, text);
}
window.addEventListener("load", () => { // on load
document.getElementById("Example").addEventListener("change",show); // show on change
show(); // show onload
});
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
jQuery:
$(function() { // on load
var $sel = $("#Example");
$sel.on("change",function() {
var value = $(this).val();
var text = $("option:selected", this).text();
console.log(value,text)
}).trigger("change"); // initial call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

Here the selected text and value is getting using jquery when page load
$(document).ready(function () {
var ddlText = $("#ddlChar option:selected").text();
var ddlValue = $("#ddlChar option:selected").val();
});
refer this
http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html
http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html

This works well
jQuery('#Example').change(function(){
var value = jQuery('#Example').val(); //it gets you the value of selected option
console.log(value); // you can see your sected values in console, Eg 1,2,3
});

Related

Html element get specific attribute value

I would like to get the "data-price" attribute from the option element onChange. getting the value does work, but i can not get the data-price attribute. I have the following code, which doesnt work.
function getComboA(selectObject) {
var printit = selectObject.getAttribute("data-price");
console.log(printit);
}
/*with this it gets the value tho, but i need the data-price attribute
function getComboA(selectObject) {
var printit = selectObject.value;
console.log(printit);
}
*/
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option data-price=100 value="Value1">Text1</option>
<option data-price=200 value="Value2">Text2</option>
<option data-price=2003 value="Value3">Text3</option>
</select>
By JavaScript :
var selection = document.getElementById("comboA");
selection.onchange = function(event){
var printit = event.target.options[event.target.selectedIndex].dataset.price;
console.log(printit);
};
Or JQuery :
$('#comboA').change(function(){
var printit =$(this).find(':selected').attr('data-price')
console.log(printit);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="comboA" >
<option value="">Select combo</option>
<option data-price=100 value="Value1">Text1</option>
<option data-price=200 value="Value2">Text2</option>
<option data-price=2003 value="Value3">Text3</option>
</select>
This should make it work:
const comboA = document.querySelector('#comboA');
comboA.addEventListener('change', function(event) {
console.log(event.target.options[event.target.selectedIndex].dataset.price);
});
With this you can also omit the function call in html.
You can use the selectedIndex of the selectObject to get the index which you can use to get the selected option and then you can get the data-price attribute of that option.
Code:
function getComboA(selectObject) {
var selectedIndex = selectObject.selectedIndex;
var selectedPrice = selectObject[selectedIndex].getAttribute("data-price");
console.log(selectedPrice);
}

Jquery filter is not working as expected

<div id="div1">
<input id="input1">
<select multiple="multiple" id="select1">
<option value="sandeep">sandeep</option>
<option value="ram">ram</option>
<option value="raj">raj</option>
<option value="pak">pak</option>
<option value="abc">abc</option>
<option value="dog">dog</option>
<option value="cat">cat</option>
<option value="journey">journey</option>
<option value="mahesh">mahesh</option>
</select>
</div>
<script type="text/javascript">
var selectClone1;
selectClone1 = $('#select1 option').clone();
$('#input1').on('keyup', function(){
$('#select1 option').remove();
var value = $(this).val();
selectClone1.filter(function(index, element){
console.log('index : '+index);
console.log('element : '+element);
return value == '' || element.value.indexOf(value) >= 0;
}).appendTo('#select1');
});
$('#select1').on('click', function(){
var option = $('option:selected', this).clone();
$('option:selected', this).remove();
selectClone1 = $.grep(selectClone1, function(el){return el.value == option[0].value}, true);
</script>
I am working on the search functionality along with removal of options when user clicked on option. The above code is working properly for search but when i clicked an option to delete from select box after search for a value, parameters of filter function(index, element) getting exchanged. Due to it error is coming. Can you help me guys where i am missing the point.
Better to use Array's splice method for removing element from main array and no need to clone.
$('#select1').on('click', function(){
var option = $('option:selected', this);
$('option:selected', this).remove();
selectClone1.splice($.inArray( option[0], selectClone1 ), 1);
});

JQuery Set Option in Opt Group

I'm trying to figure out how to set an option inside of a optgroup using JQuery and I can't seem to figure it out.
I have a hidden field on the page that contains the following value 4-2014. On ready I would like to read the hidden value and set the selected option.
html:
<select name="dropdownlist" id="dropdownlist">
<option value="All">All</option>
<optgroup label="2013" id="2013">
<option value="7">July</option>
<option value="4">April</option>
</optgroup>
<optgroup label="2014" id="2014">
<option value="4">April</option>
<option value="3">March</option>
</optgroup>
Jquery:
$(document).ready(function() {
//set the dropdown selected item.
var varDropdownvalue = $("input[id$=Dropdownvalue]").val();
var monthyear = varDropdownvalue.split('-');
$('#dropdownlist #'+monthyear[1]+' option[value='+monthyear[0]+']').prop("selected", true);
$('#dropdownlist').change(function () {
//get the optgroup label and value of selected option.
var label = $(this.options[this.selectedIndex]).closest('optgroup').prop('label');
var value = $(this).find("option:selected").val();
alert(value+'-'+label);
});
});
Here is a fiddle: jsfiddle
Try
$('#dropdownlist').val(monthyear[0]).change();
http://jsfiddle.net/LPAFD/1/
Field:
<input type="hidden" id="hidden_select" value="4-2014" />
JS:
var hidden = $("#hidden_select").val().split("-");
var month = hidden[0];
var year = hidden[1];
var list = $("#dropdownlist");
var theOption = list.find('optgroup#'+year+' option[value="'+month+'"]').val();
list.val(theOption).change();

Fetching data value defined in the select tag when an option is selected

I have the following markup and I need to fetch value of data-base inside the function below.
<select id="myid" onclick="myselected(this)" data-base="/admin/index">
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS
function myselected(obj) {
var idx = obj.selectedIndex;
var ival = obj.options[idx].value;
var baseval = .... ? how do I access data-base value?
}
Try element.getAttribute():
var baseval = obj.getAttribute('data-base')

How to synchronize two SELECT elements

I was wondering how to synchronize the values and text of two elements. For instance,
<select id="box1" onchange="sync();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
and then sync(); would look something like....
function sync()
{
box2.selected = box1.selected;
}
Any idea how I would do this?
Thanks,
Matthew
One possible approach:
function sync(el1, el2) {
// if there is no el1 argument we quit here:
if (!el1) {
return false;
}
else {
// caching the value of el1:
var val = el1.value;
// caching a reference to the element with
// with which we should be synchronising values:
var syncWith = document.getElementById(el2);
// caching the <option> elements of that <select>:
var options = syncWith.getElementsByTagName('option');
// iterating over those <option> elements:
for (var i = 0, len = options.length; i < len; i++) {
// if the value of the current <option> is equal
// to the value of the changed <select> element's
// selected value:
if (options[i].value == val) {
// we set the current <option> as
// as selected:
options[i].selected = true;
}
}
}
}
// caching the <select> element whose change event should
// be reacted-to:
var selectToSync = document.getElementById('box1');
// binding the onchange event using an anonymous function:
selectToSync.onchange = function(){
// calling the function:
sync(this,'box2');
};
function sync(el1, el2) {
if (!el1) {
return false;
} else {
var val = el1.value;
var syncWith = document.getElementById(el2);
var options = syncWith.getElementsByTagName('option');
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].value == val) {
options[i].selected = true;
}
}
}
}
var selectToSync = document.getElementById('box1');
selectToSync.onchange = function() {
sync(this, 'box2');
};
<select id="box1">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Or, revised and updated somewhat:
function sync() {
// caching the changed element:
let el = this;
// retrieving the id of the element we should synchronise with
// from the changed-element's data-syncwith custom attribute,
// using document.getElementById() to retrieve that that element.
document.getElementById( el.dataset.syncwith )
// retrieving the <options of that element
// and finding the <option> at the same index
// as changed-element's selectedIndex (the index
// of the selected <option> amongst the options
// collection) and setting that <option> element's
// selected property to true:
.options[ el.selectedIndex ].selected = true;
}
// retrieving the element whose changes should be
// synchronised with another element:
var selectToSync = document.getElementById('box1');
// binding the snyc() function as the change event-handler:
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
document.getElementById(el.dataset.syncwith).options[el.selectedIndex].selected = true;
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Note that this approach does assume – and requires – that the <option> elements are in the same order.
To update the original approach, where the order is irrelevant, using ES6 approaches (and the same data-syncwith custom attribute approach):
function sync() {
// caching the changed element (since
// we're using it twice):
let el = this;
// retrieving the id of the element to synchronise 'to' from
// the 'data-syncwith' custom attribute of the changed element,
// and retrieving its <option> elements. Converting that
// Array-like collection into an Array using Array.from():
Array.from(document.getElementById(el.dataset.syncwith).options)
// Iterating over the array of options using
// Array.prototype.forEach(), and using an Arrow function to
// pass the current <otpion> (as 'opt') setting that current
// <option> element's selected property according to Boolean
// returned by assessing whether the current option's value
// is (exactly) equal to the value of the changed element:
.forEach(opt => opt.selected = opt.value === el.value);
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
Array.from(document.getElementById(el.dataset.syncwith).options).forEach(opt => opt.selected = opt.value === el.value);
}
let selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="3">Three</option>
<option value="2">Two</option>
</select>
JS Fiddle demo.
If you look at the HTML in the Snippet you'll see that I switched the positions of <option> elements in the second <select> element to demonstrate that the <option> position doesn't matter in this latter approach.
References:
Array.from().
Array.prototype.forEach().
Arrow functions.
document.getElementById().
EventTarget.addEventListener().
for loop.
HTMLElement.dataset.
HTMLSelectElement.
let statement.
var.
In the Actual browsers you dont have to do to much...
<select id="box1" onchange="box2.value=this.value;">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Jsfiddle DEMO
Without jQuery:
for (var i=0; i<document.getElementById('box1').options.length; i++)
if (document.getElementById('box1').options[i].selected)
for (var j=0; j<document.getElementById('box2').options.length; j++)
if (document.getElementById('box1').options[i].value == document.getElementById('box2').options[j].value)
document.getElementById('box2').options[j].selected = true;
With jQuery:
Note: on method requires jQuery > 1.7
jQuery(function($) {
$('#first').on('change', function() {
var sel = $('option:selected', this).val();
$('#second option').filter(function(index, el) {
return el.value == sel;
}).prop('selected', true);
});
});
<select name="first" id="first" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<select name="second" id="second" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Categories