Use old and new value on Javascript after onChange of Select element - javascript

I try to pass on a function the old and the new value of a select element with the following way:
<select class="browser-default" id="countries" onfocus="this.oldvalue = this.value;" onchange="getCurrency(this);this.oldvalue = this.value;">
<option value="" disabled selected>Choose your country</option>
<option value="1">....</option>
<option value="2">....</option>
</select>
var getCurrency = function(country) {
currency_value = country.value;
country_name = country.options[country.selectedIndex].innerHTML;
old_value = country.oldvalue;
if ( oldvalue === "") {
oldvalue = 10;
}
}
However, it doesn't work. It doesn't pass the old value to the function. I saw something similar to another question in Stackoverflow and try to reproduce it.

Try the following.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="browser-default" id="countries" onfocus="this.oldvalue = this.value;" onchange="getCurrency(this);this.oldvalue = this.value;">
<option value="" disabled selected>Choose your country</option>
<option value="1">India</option>
<option value="2">Australia</option>
<option value="3">USA</option>
</select>
<script>
var oldValue = $("#countries").val();
var newValue;
$("#countries").change(function(){
newValue=$(this).val();
alert(oldValue + " : " + newValue);
oldValue=newValue;
});
</script>

Related

How to get data from the drop down menu using javascript? [duplicate]

I have a dropdown list like this:
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:
<select id="box1" onChange="myNewFunction(this.selectedIndex);" >
But rather than 7122 I want cat.
Try options
function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}
<select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
There are two solutions, as far as I know.
both that just need using vanilla javascript
1 selectedOptions
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
2 options
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.options[select.selectedIndex].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
HTML:
<select id="box1" onChange="myNewFunction(this);">
JavaScript:
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
// ...
}
DEMO: http://jsfiddle.net/6dkun/1/
Use -
$.trim($("select").children("option:selected").text()) //cat
Here is the fiddle - http://jsfiddle.net/eEGr3/
To get it on React with Typescript:
const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
const { options, selectedIndex } = event.target;
const text = options[selectedIndex].text;
// Do something...
};
Using jquery.
In your event
let selText = $("#box1 option:selected").text();
console.log(selText);
Using vanilla JavaScript
onChange = { e => e.currentTarget.options[e.selectedIndex].text }
will give you exact value if values are inside a loop.
function runCode() {
var value = document.querySelector('#Country').value;
window.alert(document.querySelector(`#Country option[value=${value}]`).innerText);
}
<select name="Country" id="Country">
<option value="IN">India</option>
<option value="GBR">United Kingdom </option>
<option value="USA">United States </option>
<option value="URY">Uruguay </option>
<option value="UZB">Uzbekistan </option>
</select>
<button onclick="runCode()">Run</button>
You'll need to get the innerHTML of the option, and not its value.
Use this.innerHTML instead of this.selectedIndex.
Edit: You'll need to get the option element first and then use innerHTML.
Use this.text instead of this.selectedIndex.
<select class="cS" onChange="fSel2(this.value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select><br>
<select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const s=document.querySelector(".cS");
// options[this.selectedIndex].value
let fSel = (sIdx) => console.log(sIdx,
s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);
let fSel2= (sIdx) => { // this.value
console.log(sIdx, s.options[sIdx].text,
s.options[sIdx].textContent, s.options[sIdx].label);
}
// options[this.selectedIndex].text
// options[this.selectedIndex].textContent
// options[this.selectedIndex].label
// options[this.selectedIndex].innerHTML
let fSel3= (sIdx) => {
console.log(sIdx);
}
</script> // fSel
But :
<script type="text/javascript"> "use strict";
const x=document.querySelector(".cS"),
o=x.options, i=x.selectedIndex;
console.log(o[i].value,
o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
</script> // .cS"
And also this :
<select id="iSel" size="3">
<option value="one">Un</option>
<option value="two">Deux</option>
<option value="three">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const i=document.getElementById("iSel");
for(let k=0;k<i.length;k++) {
if(k == i.selectedIndex) console.log("Selected ".repeat(3));
console.log(`${Object.entries(i.options)[k][1].value}`+
` => ` +
`${Object.entries(i.options)[k][1].innerHTML}`);
console.log(Object.values(i.options)[k].value ,
" => ",
Object.values(i.options)[k].innerHTML);
console.log("=".repeat(25));
}
</script>
You can get an array-like object that contains the selected item(s) with the method getSelected() method. like this:
querySelector('#box1').getSelected()
so you can extract the text with the .textContent attribute. like this:
querySelector('#box1').getSelected()[0].textContent
If you have a multiple selection box you can loop through array-like object
I hope it helps you😎👍
var selectionlist=document.getElementById("agents");
td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML;
ECMAScript 6+
const select = document.querySelector("#box1");
const { text } = [...select.options].find((option) => option.selected);
Try the below:
myNewFunction = function(id, index) {
var selection = document.getElementById(id);
alert(selection.options[index].innerHTML);
};
See here jsfiddle sample

how do i innerhtml a select list element in javascript? [duplicate]

I have a dropdown list like this:
<select id="box1">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
How can I get the actual option text rather than the value using JavaScript? I can get the value with something like:
<select id="box1" onChange="myNewFunction(this.selectedIndex);" >
But rather than 7122 I want cat.
Try options
function myNewFunction(sel) {
alert(sel.options[sel.selectedIndex].text);
}
<select id="box1" onChange="myNewFunction(this);">
<option value="98">dog</option>
<option value="7122">cat</option>
<option value="142">bird</option>
</select>
Plain JavaScript
var sel = document.getElementById("box1");
var text= sel.options[sel.selectedIndex].text;
jQuery:
$("#box1 option:selected").text();
There are two solutions, as far as I know.
both that just need using vanilla javascript
1 selectedOptions
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.selectedOptions[0].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
2 options
live demo
const log = console.log;
const areaSelect = document.querySelector(`[id="area"]`);
areaSelect.addEventListener(`change`, (e) => {
// log(`e.target`, e.target);
const select = e.target;
const value = select.value;
const desc = select.options[select.selectedIndex].text;
log(`option desc`, desc);
});
<div class="select-box clearfix">
<label for="area">Area</label>
<select id="area">
<option value="101">A1</option>
<option value="102">B2</option>
<option value="103">C3</option>
</select>
</div>
All these functions and random things, I think it is best to use this, and do it like this:
this.options[this.selectedIndex].text
HTML:
<select id="box1" onChange="myNewFunction(this);">
JavaScript:
function myNewFunction(element) {
var text = element.options[element.selectedIndex].text;
// ...
}
DEMO: http://jsfiddle.net/6dkun/1/
Use -
$.trim($("select").children("option:selected").text()) //cat
Here is the fiddle - http://jsfiddle.net/eEGr3/
To get it on React with Typescript:
const handleSelectChange: React.ChangeEventHandler<HTMLSelectElement> = (event) => {
const { options, selectedIndex } = event.target;
const text = options[selectedIndex].text;
// Do something...
};
Using jquery.
In your event
let selText = $("#box1 option:selected").text();
console.log(selText);
Using vanilla JavaScript
onChange = { e => e.currentTarget.options[e.selectedIndex].text }
will give you exact value if values are inside a loop.
function runCode() {
var value = document.querySelector('#Country').value;
window.alert(document.querySelector(`#Country option[value=${value}]`).innerText);
}
<select name="Country" id="Country">
<option value="IN">India</option>
<option value="GBR">United Kingdom </option>
<option value="USA">United States </option>
<option value="URY">Uruguay </option>
<option value="UZB">Uzbekistan </option>
</select>
<button onclick="runCode()">Run</button>
You'll need to get the innerHTML of the option, and not its value.
Use this.innerHTML instead of this.selectedIndex.
Edit: You'll need to get the option element first and then use innerHTML.
Use this.text instead of this.selectedIndex.
<select class="cS" onChange="fSel2(this.value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS1" onChange="fSel(options[this.selectedIndex].value);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select><br>
<select id="iS2" onChange="fSel3(options[this.selectedIndex].text);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS3" onChange="fSel3(options[this.selectedIndex].textContent);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].label);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<select id="iS4" onChange="fSel3(options[this.selectedIndex].innerHTML);">
<option value="0">S?lectionner</option>
<option value="1">Un</option>
<option value="2" selected>Deux</option>
<option value="3">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const s=document.querySelector(".cS");
// options[this.selectedIndex].value
let fSel = (sIdx) => console.log(sIdx,
s.options[sIdx].text, s.options[sIdx].textContent, s.options[sIdx].label);
let fSel2= (sIdx) => { // this.value
console.log(sIdx, s.options[sIdx].text,
s.options[sIdx].textContent, s.options[sIdx].label);
}
// options[this.selectedIndex].text
// options[this.selectedIndex].textContent
// options[this.selectedIndex].label
// options[this.selectedIndex].innerHTML
let fSel3= (sIdx) => {
console.log(sIdx);
}
</script> // fSel
But :
<script type="text/javascript"> "use strict";
const x=document.querySelector(".cS"),
o=x.options, i=x.selectedIndex;
console.log(o[i].value,
o[i].text , o[i].textContent , o[i].label , o[i].innerHTML);
</script> // .cS"
And also this :
<select id="iSel" size="3">
<option value="one">Un</option>
<option value="two">Deux</option>
<option value="three">Trois</option>
</select>
<script type="text/javascript"> "use strict";
const i=document.getElementById("iSel");
for(let k=0;k<i.length;k++) {
if(k == i.selectedIndex) console.log("Selected ".repeat(3));
console.log(`${Object.entries(i.options)[k][1].value}`+
` => ` +
`${Object.entries(i.options)[k][1].innerHTML}`);
console.log(Object.values(i.options)[k].value ,
" => ",
Object.values(i.options)[k].innerHTML);
console.log("=".repeat(25));
}
</script>
You can get an array-like object that contains the selected item(s) with the method getSelected() method. like this:
querySelector('#box1').getSelected()
so you can extract the text with the .textContent attribute. like this:
querySelector('#box1').getSelected()[0].textContent
If you have a multiple selection box you can loop through array-like object
I hope it helps you😎👍
var selectionlist=document.getElementById("agents");
td2.innerHTML = selectionlist.children[selectionlist.selectedIndex].innerHTML;
ECMAScript 6+
const select = document.querySelector("#box1");
const { text } = [...select.options].find((option) => option.selected);
Try the below:
myNewFunction = function(id, index) {
var selection = document.getElementById(id);
alert(selection.options[index].innerHTML);
};
See here jsfiddle sample

how to preserve all select elements selected values in jquery

Can you help me to solve this problem.
The problem is this.
I have multiple select lists with same class name but different ids. If user select same option which is already selected in other select list then there should be an alert. and after alert the current select list which is clicked or changed should be restore to the previous value. for example we have 3 select boxes name as A1, A2, A3. Each one have same values for example 1,2,3,4. A1 selected value is 1, A2 selected value is 2 and A3 selected value is 3. Now if your want to change A1 value from 1 to 2 then there should be an alert like "Already selected". After this alert A1 list should be restored back to its original value which is 1. I tried the following code. In this code I can get already existing alert but the value of the last changes select box is changed to new one.
$(document).ready(function(){
var init = true;
if(init == true){
var a = new Array();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
a[current_obj_id] = current_obj_value;
});
init = false;
}
$(".brand-list").change(function(){
a[$(this).attr('id')] = $('#'+ $(this).attr('id') + " option:selected").val();
var current_selected_obj_id = $(this).attr('id');
var current_selected_obj_value = $('#'+ $(this).attr('id') + " option:selected").val();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
if(current_obj_id != current_selected_obj_id){
if(current_selected_obj_value == current_obj_value){
alert("current element global value: "+ a[current_selected_obj_id]);
$('#'+ current_selected_obj_id + " option[value=" + a[current_selected_obj_id] +"]").attr('selected','selected')
alert("already selected");
}
}else{
a[current_obj_id] = current_obj_value;
}
});
});
$( ".brand-list" ).focus(function() {
var current_selected_obj_id = $(this).attr('id');
var current_selected_obj_value = $('#'+ $(this).attr('id') + " option:selected").val();
a[current_selected_obj_id] = current_selected_obj_value;
console.log(a[current_selected_obj_id]);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
</select>
Hopefully you can understand my question, because I'm not get to ask question which community members can understand easily. Thanks
You can save the previous value and check it then
$(document).ready(function(){
var init = true;
if(init == true){
var a = new Array();
$(".brand-list").each(function(i, obj){
var current_obj_id = $(this).attr('id');
var current_obj_value = $('#'+ current_obj_id + " option:selected").val();
a[current_obj_id] = current_obj_value;
});
init = false;
}
function hasConflict(input){
var conflict = false;
$(".brand-list").not(input).each(function(i, obj){
if($(this).val()==input.val()){
conflict = true;
return false; //break the loop
}
});
return conflict;
}
$(".brand-list").change(function(){
var $this = $(this); //recycle object
if(hasConflict($this)){
$this.val($this.data('prev'));
alert("Conflict"); //do whatever
}
});
$( ".brand-list" ).on('click focus',function() {
$(this).data('prev',$(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" selected="selected">3</option>
<option value="4">4</option>
</select>
Rather than annoy user by letting them select something and be told they can't it's better UX to either disable previous selections or remove them completely.
Here's an approach that manages the filtering/removing of other selections
var $selects = $(".brand-list"),
// store a cloned set of all options
$storedOptions = $selects.first().children().clone().removeAttr('selected'),
// whether to always include "SELECT A BRAND"
alwaysShowDefault = true;
$selects.change(function() {
// create array of all the selected values
var allValues = $selects.map(function() {
return $(this).val()
}).get();
// loop through each select to create filtered options
$selects.each(function(i) {
// new set of cloned and filtered options for this select instance
var $opts = $storedOptions.clone().filter(function() {
if(+this.value === -1){
return alwaysShowDefault || +allValues[i] === -1;
}
return allValues[i] === this.value || allValues.indexOf(this.value) === -1;
});
// update filtered options and reset current value
$(this).html($opts).val(allValues[i])
})
// trigger one change on page load to filter what is already selected
}).first().change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select id="inputBrand-1" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1" selected="selected">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-2" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2" selected="selected">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="inputBrand-3" class="brand-list">
<option value="-1">SELECT A BRAND</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3" >3</option>
<option value="4">4</option>
</select>
Actually you'r currently doing is manually setting the selected attribute on each option element. It is not a good approach because it doesn't remove other attributes of options of the same select element. So use following code in your source.
$(e.currentTarget).val(-1);
Replace following code with above one
$('#'+ current_selected_obj_id + " option[value=" + a[current_selected_obj_id] +"]").attr('selected','selected')

How to check if all value in select option are the same with javascript?

if I have html like this.
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
How to check if all value in select option are the same with javascript ?
Use Set object to check if each of the option elements has the same value property. If so - use Array#forEach to apply selected prop on each of them.
let parent = document.getElementById('catalogsearch_specification2'),
values = Array.from(parent.children).map(v => v.value);
[...new Set(values)].length == 1 ? Array.from(parent.children).forEach(v => v.selected = true) : null;
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
You can do:
var isSame = true,
prev = '';
$('#catalogsearch_specification2 > option').each(function() {
if (prev && prev !== this.value) {
isSame = false;
return;
}
prev = this.value;
});
console.log(isSame);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
This snippet will help you understand how to retrieve values from child nodes.
var obj = {};
var i = 0
$("#catalogsearch_specification2 option").each(function() {
//You can write you logic here.
if(!obj.hasOwnProperty(this.value)) {
obj[this.value] = {"value" : this.value, "duplicate" : 1};
} else {
obj[this.value].duplicate = (obj[this.value].duplicate) + 1;
}
});
console.log(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
Here I'm taking all the child option element of id "catalogsearch_specification2".
There are a numerous way you can check. Here is a solution. Take the first option value and count total no of option with that value. And again count the total option value. If the count are same then all option values are same otherwise not.
$(function(){
var firstValue = $('#catalogsearch_specification2').find("option:first-child").val();
if($('#catalogsearch_specification2 option[value="'+firstValue+'"]').length == $('#catalogsearch_specification2 option').length){
console.log("All values are same");
}else{
console.log("All values are not same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-1">ddd</option>
</select>

Change placeholder of input when I select Option

I have been trying out some jQuery coding but doesn't seem to work. In the #vat input, I need the placeholder to change.
<select id="VatExpense">
<option value="" disabled selected></option>
<option value="0"></option>
<option value="1"></option>
<option value="0"></option>
<option value="0"></option>
<option value="1"></option>
</select>
<input type="text" id="vat" placeholder="Rate">
You should be using data- attributes, not value to determine the rates.
Demo fiddle
HTML:
<select id="VatExpense">
<option data-rate="20" value="" disabled selected>Expense Type</option>
<option data-rate="20" value="0">Telephone</option>
<option data-rate="0" value="1">Public Transport & Taxis</option>
<option data-rate="20" value="2">Computer Consumables</option>
<option data-rate="20" value="3">Subsistence</option>
<option data-rate="0" value="4">Overseas Travel</option>
</select>
Then read them in the jQuery and change the placeholder accordingly.
Script:
<script type="text/javascript">
$(function(){
$("#VatExpense").change(function(){
$("#vat").attr("placeholder", $(this).find(":selected").data("rate") + "%");
});
});
</script>
You can try this:
Jquery :
$("#VatExpense").on("change", function() {
var vatExpense = $("#VatExpense option:selected").val();
var vatPlaceholder = "Rate";
if (vatExpense == 0) {
vatPlaceholder = "Standard rate 20%";
} else if (vatExpense == 1) {
vatPlaceholder = "Zero Rate 0%";
}
$("#vat").attr("placeholder", vatPlaceholder);
});
JsFiddle: http://jsfiddle.net/ghorg12110/kzmL0e1j/
You can do it like this :
(function() {
var placeholders = {
'value_':'Rate',
'value_0':'Standard rate 20%',
'value_1':'Zero Rate 0%'
};
$("#VatExpense").on('change', function(e) {
$("#vat").prop('placeholder', placeholders['value_' + $(this).val() ]);
});
})();
Try below like this Demo Here use attr()
$('#VatExpense').change(function(){
var selectedval = $(this).val();
if(selectedval == 0){
$('#vat').attr('placeholder','Standard rate 20%');
}else if(selectedval == 1){
$('#vat').attr('placeholder','Zero Rate 0%');
}
});

Categories