I need to check textbox value against dropdown list, and if that value does not exist, add to the list.
I have this script:
<select id="drop" onchange="ChooseContact(this)">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
function execute(data) {
var txtbox = document.getElementById ("txtServiceReportInspectedBy").value;
if ( document.createElement('option').value != txtbox ) {
var categories = document.getElementById("drop");
var newOption = document.createElement('option');
newOption.innerText = txtbox ;
newOption.setAttribute('value', txtbox );
categories.appendChild(newOption);
}
document.getElementById("drop").value = txtbox ;
}
But the new item is still created in the dropdown list, eventhough such item already there. Thanks.
You are not searching for the text among the options. Here is how you could do that:
add.addEventListener('click', execute);
function execute(data) {
var txtbox = txtServiceReportInspectedBy.value,
optionTexts = Array.from(document.querySelectorAll('#drop>option'),
option => option.value);
if ( !optionTexts.includes(txtbox) ) {
var newOption = document.createElement('option');
newOption.value = newOption.textContent = txtbox ;
drop.appendChild(newOption);
}
drop.value = txtbox;
}
<input id="txtServiceReportInspectedBy"><button id="add">Add</button><br>
<select id="drop">
<option value="Volvo Red">Volvo Red</option>
<option value="Mers Blue">Mers Blue</option>
<option value="Ferr red">Ferr red</option>
</select>
On your "if" sentence you are creating a new element "option" so always is going to be different your "value", so always is going to create a new element inside your "select" tag
You need to iterate for the elements of your "select" tag to find if its value exist or not
Related
I know how to get the "value" of a selected option tag on change of the select dropdown. But how do I get the associated "text" i.e. inner HTML into the JS variable "country_name" ?
<select name="country" class="country">
<option value="please-select" disabled="disabled" selected="selected">select country</option>
<option value="DE">Germany</option>
<option value="ES">Spain</option>
<option value="FR">France</option>
<option value="IT">Italy</option>
</select>
<script src="js/jquery-3.4.1.min.js"></script>
<script>
$('select.country').on('change',function(){
var country_code = $(this).val();
var country_name = 'Selected Country Name';
alert(country_code+" - "+country_name);
});
</script>
Desired alert output for for instance the second option:
ES - Spain
You just need to build a selector relative to the dropdown, reaching into its option children and filtering to just the selected one, via jQuery's :selected pseudo-selector:
var country_name = $(this).children(':selected').text();
to get the selected text of the selected option of a select field I would do the following
$("select.country").change(function(){
var selectedCountry = $(this).children("option:selected");
var country_code = selectedCountry.val();
var country_name = selectedCountry.text();
alert(country_code+" - "+country_name);
});
Just add this in you javascript
$('select.country').on('change',function(){
var country_code = $(this).val();
var country_name = ( $(this).find(":selected").text() )
alert(country_code+" - "+country_name);
});
I have pair of text boxes. I need to find duplicate pair values in my select dropdown.
JSFIDDLE example
txt12 txt12
txt2 txt1
txt3 txt3
txt4 txt5
txt12 txt12
In my example, txt12 select pair is duplicated. I could possibly find each duplicate values by considering each select dropdowns.
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value); break;
}
else
values.push(select.value);
}
How is it possible to find duplicate pair of select dropdown values
You can use something like
function chkVal() {
var selects = document.getElementsByTagName('select');
var values = [];
for(i=0;i<selects.length;i++) {
var select = selects[i];
if(values.indexOf(select.value)>-1) {
alert('duplicate - '+select.value);
}
else
values.push(select.value);
}
}
You have to just remove the break in the if block as it is moving out of the for loop in the first loop when it find text12.
Refer to the fiddle : "http://jsfiddle.net/sL6ofchd/9/"
With jQuery, try something like this:
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length );
});
$('.check-value').on('click', function() {
var duplicates = $('select+br').prev().filter(function() {
return $(this).val() == $(this).prev().val();
});
console.log( duplicates.length + ' duplicates' );
duplicates.each(function(i) {
console.log( i, this, $(this).prev()[0] );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<select>
<option value="txt2">txt2</option>
</select> <select>
<option value="txt1">txt1</option>
</select><br><br>
<select>
<option value="txt3">txt3</option>
</select> <select>
<option value="txt3">txt3</option>
</select><br><br>
<select>
<option value="txt12">txt12</option>
</select> <select>
<option value="txt12">txt12</option>
</select><br><br>
<input type="button" value="save" class="check-value">
How can I set/retrieve the last selected value of a select drop-down with JavaScript? I'm trying to create an onchange function on a select drop-down that that sets the selected option, and then on each page-load, that valued is loaded.
Here is the HTML
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test2">test3</option>
<option value="test2">test4</option>
</select>
I'm having a little trouble with the JavaSCript though.
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem(select, lastSelected);
selectOption = getLast;
select.onchange = function () {
var lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem(select, lastSelected);
}
and here's a fiddle http://jsfiddle.net/5yJNL/1/
The values in your HTML were wrong
<select class="testSelect">
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
</select>
Javascript
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected) {
select.value = lastSelected;
}
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select', lastSelected);
}
http://jsfiddle.net/2MPPz/1/
You have at least two problems in your code.
The first one is an scope problem: The lastSelected variable is
local defined in your function. You must define as global variable.
The second one is that the first parameter of setItem & getItem
methods should be a String
So your corrected code looks like:
var lastSelected;
var select = document.querySelector(".testSelect");
var selectOption = select.options[select.selectedIndex];
var getLast = localStorage.getItem('select', lastSelected);
selectOption = getLast;
select.onchange = function () {
lastSelected = select.options[select.selectedIndex].value;
localStorage.setItem('select', lastSelected);
};
I have 2 dropdown list, where in the first dropdown list i have some data and if I select the data it has to be stored into the second dropdown list. Here is the code :-
This is the first dropdown list,
<select name="weekId" id="weekId" onchange="getSelected(value)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
This is the second list,
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
If I select Weekly in the first dropdown, the value has to get stored in the second dropdown. How do I go about implementing this?
Thanks in advance!!
var weekId = document.getElementById('weekId')
, selectedWeek = document.getElementById('selectedWeek')
, option;
weekId.onchange = function() {
option = document.createElement('option');
option.value = this.value;
option.text = this.options[this.selectedIndex].text;
selectedWeek.appendChild(option);
weekId.removeChild(this.options[this.selectedIndex]);
};
see working fiddle here: http://jsfiddle.net/bKrFK/1/
the last line in the event-handler will remove the selected option from the weekId select-box (remove that line if not needed)
You can do this using Javascript:
function listbox_moveacross(sourceID, destID) {
var src = document.getElementById(sourceID);
var dest = document.getElementById(destID);
for(var count=0; count < src.options.length; count++) {
if(src.options[count].selected == true) {
var option = src.options[count];
var newOption = document.createElement("option");
newOption.value = option.value;
newOption.text = option.text;
newOption.selected = true;
try {
dest.add(newOption, null); //Standard
src.remove(count, null);
}catch(error) {
dest.add(newOption); // IE only
src.remove(count);
}
count--;
}
}
}
Pass this function with ids of your selectbox.
For Demo: Listbox move left-right options JavaScript
Try this..
<html>
<body>
<select name="weekId" id="weekId" onchange="document.getElementById('selectedWeek').value=this.value">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
</body>
</html>
Note : Second drop down has all value available in first select box.
First of all, when you call the javascript function in onChange event, replace getSelected(value) to getSelected(this.value).
Now after that,
Your javascript function getSelected(value) should look like this
function getSelected(value)
{
document.getElementById("selectedWeek").innerHTML = '<option value="'+value+'">'+value+'</option>';
}
You could use the following, without any jQuery dependencies.
I've added some comments to explain what is going on.
<script>
function handleSelection(weekDropDown) {
// Get selected value
var selection = weekDropDown.options[weekDropDown.selectedIndex].value;
var selectedWeekDropDown = document.getElementById("selectedWeek");
var opt;
if(selectedWeekDropDown.options[0]) {
// Replace
opt = selectedWeekDropDown.options[0];
} else {
// Add an option
opt = document.createElement("option");
}
if(!selectedWeekDropDown.options[0]) {
selectedWeekDropDown.options.add(opt);
}
// Set the option text and value
opt.text = selection;
opt.value = selection;
}
</script>
<select name="weekId" id="weekId" onchange="handleSelection(this)">
<option value="Select">Select</option>
<option value="Weekly">Weekly</option>
<option value="Monthly">Monthly</option>
<option value="Both">Both</option>
</select>
<select id="selectedWeek" name="selectedWeek" size="5" multiple="multiple">
In my HTML, I have a <select> with three <option> elements. I want to use jQuery to check each option's value against a Javascript var. If one matches, I want to set the selected attribute of that option. How would I do that?
Vanilla JavaScript
Using plain old JavaScript:
var val = "Fish";
var sel = document.getElementById('sel');
document.getElementById('btn').onclick = function() {
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++) {
if (opt.value == val) {
sel.selectedIndex = j;
break;
}
}
}
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery
But if you really want to use jQuery:
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
var val = 'Fish';
$('#btn').on('click', function() {
$('#sel').val(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<button id="btn">Select Fish</button>
jQuery - Using Value Attributes
In case your options have value attributes which differ from their text content and you want to select via text content:
<select id="sel">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var val = 'Fish';
$('#sel option:contains(' + val + ')').prop({selected: true});
</script>
Demo
But if you do have the above set up and want to select by value using jQuery, you can do as before:
var val = 3;
$('#sel').val(val);
Modern DOM
For the browsers that support document.querySelector and the HTMLOptionElement::selected property, this is a more succinct way of accomplishing this task:
var val = 3;
document.querySelector('#sel [value="' + val + '"]').selected = true;
Demo
Knockout.js
<select data-bind="value: val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
<script>
var viewModel = {
val: ko.observable()
};
ko.applyBindings(viewModel);
viewModel.val(3);
</script>
Demo
Polymer
<template id="template" is="dom-bind">
<select value="{{ val }}">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</template>
<script>
template.val = 3;
</script>
Demo
Angular 2
Note: this has not been updated for the final stable release.
<app id="app">
<select [value]="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</app>
<script>
var App = ng.Component({selector: 'app'})
.View({template: app.innerHTML})
.Class({constructor: function() {}});
ng.bootstrap(App).then(function(app) {
app._hostComponent.instance.val = 3;
});
</script>
Demo
Vue 2
<div id="app">
<select v-model="val">
<option value="1">Cat</option>
<option value="2">Dog</option>
<option value="3">Fish</option>
</select>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
val: null,
},
mounted: function() {
this.val = 3;
}
});
</script>
Demo
None of the examples using jquery in here are actually correct as they will leave the select displaying the first entry even though value has been changed.
The right way to select Alaska and have the select show the right item as selected using:
<select id="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
</select>
With jquery would be:
$('#state').val('AK').change();
You can change the value of the select element, which changes the selected option to the one with that value, using JavaScript:
document.getElementById('sel').value = 'bike';
DEMO
Markup
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
jQuery
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Demo
I want to change the select element's selected option's both value & textContent (what we see) to 'Mango'.
Simplest code that worked is below:
var newValue1 = 'Mango'
var selectElement = document.getElementById('myselectid');
selectElement.options[selectElement.selectedIndex].value = newValue1;
selectElement.options[selectElement.selectedIndex].textContent = newValue1;
Hope that helps someone. Best of luck.
Up vote if this helped you.
I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:
Example
<select id="org_list">
<option value="23">IBM</option>
<option value="33">DELL</option>
<option value="25">SONY</option>
<option value="29">HP</option>
</select>
So you must know the value of the option to select.
function selectOrganization(id){
org_list=document.getElementById('org_list');
org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}
How to Use?
selectOrganization(25); //this will select SONY from option List
Your comments are welcome. :) AzmatHunzai.
Test this Demo
Selecting Option based on its value
var vals = [2,'c'];
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.val() == vals[n]){
$t.prop('selected', true);
return;
}
});
Selecting Option based on its text
var vals = ['Two','CCC']; // what we're looking for is different
$('option').each(function(){
var $t = $(this);
for (var n=vals.length; n--; )
if ($t.text() == vals[n]){ // method used is different
$t.prop('selected', true);
return;
}
});
Supporting HTML
<select>
<option value=""></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select>
<option value=""></option>
<option value="a">AAA</option>
<option value="b">BBB</option>
<option value="c">CCC</option>
</select>
Excellent answers - here's the D3 version for anyone looking:
<select id="sel">
<option>Cat</option>
<option>Dog</option>
<option>Fish</option>
</select>
<script>
d3.select('#sel').property('value', 'Fish');
</script>
After a lot of searching I tried #kzh on select list where I only know option inner text not value attribute,
this code based on select answer I used it to change select option according to current page urlon this format
http://www.example.com/index.php?u=Steve
<select id="sel">
<option>Joe</option>
<option>Steve</option>
<option>Jack</option>
</select>
<script>
var val = window.location.href.split('u=')[1]; // to filter ?u= query
var sel = document.getElementById('sel');
var opts = sel.options;
for(var opt, j = 0; opt = opts[j]; j++) {
// search are based on text inside option Attr
if(opt.text == val) {
sel.selectedIndex = j;
break;
}
}
</script>
This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .
You just write the code
var theVal = 1;
$('#variable_id').val(theVal).trigger('change');
I used this after updating a register and changed the state of request via ajax, then I do a query with the new state in the same script and put it in the select tag element new state to update the view.
var objSel = document.getElementById("selectObj");
objSel.selectedIndex = elementSelected;
I hope this is useful.
selectElement is a html <select> element.
Increment the value:
selectElement.selectedIndex++
Decrement the value:
selectElement.selectedIndex--
var accHos = document.getElementById("accHos");
function showName(obj) {
accHos.selectedIndex = obj.selectedIndex;
}
div {
color: coral;
}
select {
margin-left: 20px;
margin-bottom: 8px;
min-width: 120px;
}
<div>Select Account Number:</div>
<select id="accNos" name="" onchange="showName(this);">
<option value="">Select Account</option>
<option value="">1052021</option>
<option value="">2052021</option>
<option value="">3052021</option>
<option value="">4052021</option>
<option value="">5052021</option>
</select>
<div>Account Holder Name:</div>
<select id="accHos" name="" disabled>
<option value="">--Name--</option>
<option value="">Suhan</option>
<option value="">Cesur</option>
<option value="">Hopper</option>
<option value="">Rachel</option>
<option value="">Arya</option>
</select>
<!-- Just for my referece -->
Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():
NodeList.prototype.forEach = Array.prototype.forEach
Just:
var requiredValue = 'i-50332a31',
selectBox = document.querySelector('select')
selectBox.childNodes.forEach(function(element, index){
if ( element.value === requiredValue ) {
selectBox.selectedIndex = index
}
})