how I can get the content the select from the value [duplicate] - javascript

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

Related

Swap a select text with javascript?

I have a example code here:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
I want to swap se1 and se2 . Here is my code i tried:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
It's work but it require Jquery 1.2.3 but i want to use Jquery 2.1.3. If i change script url to "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" but it isn't work
Thanks for help!
You shouldn't be swapping the values or the text of the two selected items in the lists. You just need to swap which item is selected in each list. Once that is done, that option will have whatever value the list has set up for it.
The version of JQuery you use here doesn't matter since what you are doing requires JQuery operations that have been in JQuery since the beginning.
var sel1 = $("#se1");
var sel2 = $("#se2");
function swap() {
let selection1 = sel1[0].selectedIndex; // Store the first list's selection
sel1[0].selectedIndex = sel2[0].selectedIndex;
sel2[0].selectedIndex = selection1;
// Test
console.log(sel1.val(), sel2.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>

dynamic create element in javascript and change values

I try to make dynamic inputs, I give labels attribute contenteditable="ture" because if I want to edit content other time, I give for attribute in label and name attribute in input this textContent(label)
function addInput() {
let options = `
<select class="select1">
<option value="">--</option>
<option value="number">number</option>
<option value="text">text</option>
<option value="date">date</option>
<option value="datetime-local">datetime-local</option>
<option value="file">file</option>
<option value="tel">tel</option>
<option value="time">time</option>
<option value="url">url</option>
<option value="month">month</option>
<option value="range">range</option>
<option value="color">color</option>
</select>
<input class="input1" type="text">
<button class="button1">create</button>
`;
document.querySelector('.choose').innerHTML = options;
let button1 = document.querySelector('.button1');
button1.addEventListener('click', function(e) {
e.preventDefault
let select1 = document.querySelector('.select1').value;
let input1 = document.querySelector('.input1').value;
let chooses = [
[select1, input1]
];
chooses.forEach((choose) => {
if (choose !== " ") {
let code = `<div class="relative delete dragthing Nlabel" onclick="addvalue()" ><label for="${choose[1]}" contenteditable="true" class="Vlabel" >${choose[1]}</label><span class="removeElement" onclick="removeElement()"><i class="fa-solid fa-circle-xmark"></i></span><input class="Ninput" name="${choose[1]}" type=${choose[0]} ></div>`;
document.querySelector('.Nform').innerHTML += code;
}
});
});
}
<button onclick="addInput()" class="createElement">create input</button>
<div class="choose"></div>
<div class="Nform" id="dragparent"></div>
my problem in this function frist when I create new input and try to change content, for attribute in label and name attribute in input will change to this content but if create input again and try to change content, for attribute in label and name attribute in input will not change to this content so why my function run one time?
function addvalue() {
let values = document.querySelectorAll('.Vlabel');
console.log(values);
values.forEach(value => {
window.addEventListener('click', () => {
let value2 = document.querySelector('.Vlabel').innerText;
document.querySelector('.Vlabel').setAttribute('for', value2);
document.querySelector('.Ninput').setAttribute('name', value2);
});
});
}
addvalue() should take an argument telling it which DIV it should process. Then it can call methods on that element to find the enclosed Vlabel and Ninput elements.
function addInput() {
let options = `
<select class="select1">
<option value="">--</option>
<option value="number">number</option>
<option value="text">text</option>
<option value="date">date</option>
<option value="datetime-local">datetime-local</option>
<option value="file">file</option>
<option value="tel">tel</option>
<option value="time">time</option>
<option value="url">url</option>
<option value="month">month</option>
<option value="range">range</option>
<option value="color">color</option>
</select>
<input class="input1" type="text">
<button class="button1">create</button>
`;
document.querySelector('.choose').innerHTML = options;
let button1 = document.querySelector('.button1');
button1.addEventListener('click', function(e) {
e.preventDefault
let select1 = document.querySelector('.select1').value;
let input1 = document.querySelector('.input1').value;
let chooses = [
[select1, input1]
];
chooses.forEach((choose) => {
if (choose !== " ") {
let code = `<div class="relative delete dragthing Nlabel" onclick="addvalue(this)" ><label for="${choose[1]}" contenteditable="true" class="Vlabel" >${choose[1]}</label><span class="removeElement" onclick="removeElement()"><i class="fa-solid fa-circle-xmark"></i></span><input class="Ninput" name="${choose[1]}" type=${choose[0]} ></div>`;
document.querySelector('.Nform').innerHTML += code;
}
});
});
}
function addvalue(div) {
console.log("addvalue");
let value2 = div.querySelector('.Vlabel').innerText;
div.querySelector('.Vlabel').setAttribute('for', value2);
div.querySelector('.Ninput').setAttribute('name', value2);
}
<button onclick="addInput()" class="createElement">create input</button>
<div class="choose"></div>
<div class="Nform" id="dragparent"></div>

How to track the select option is deselect and and grab the deselect option value in jquery

Below is the example of the code for the scenario.
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>
Suppose if deselect the honda, how would i know that this particular option is deselected and how i will grab that option value in jquery.
Thanks in advance
You can keep some variables and filter out those accordingly.
and in JS, you can handle these variables in the events
Here is the snippet, Hopefully you were looking for the same.
var prevValues = [];
var currentValues = [];
$(document).ready(function() {
currentValues = $('.car').val();
})
$('.car').on('change', function() {
prevValues = [...currentValues];
currentValues = $('.car').val();
let newlyAdded = currentValues.filter(x=> !prevValues.includes(x))[0];
let newlyRemoved = prevValues.filter(x=> !currentValues.includes(x))[0];
if(newlyAdded) {
console.log('Added item', newlyAdded);
}
if( newlyRemoved) {
console.log('Removed Item', newlyRemoved);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="car" multiple name="cars">
<option value="volvo">Volvo</option>
<option value="honda" selected>honda</option>
<option value="opel" selected>Opel</option>
<option value="audi">Audi</option>
</select>

Change paragraph after selecting value in dropbox in js

I have a form with dropbox with a few options.
I want to change a paragraph according to the selected value in the dropbox, i.e. the selected value will replace the paragraph.
For ex. I have:
<select name="howmanyno1" size=1>
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p>number</p>`
I need the text "number" be replaced after selecting a value from the dropbox, with the value selected (2,3,4 or 5).
How should I do this?
Thanks.
<select onchange="myFunction()" name="howmanyno1" id="mySelect">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<p id="demo">number</p>`
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
<select name="howmanyno1" id="selectDiv" size=1 onchange="changePara()">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p id="changed">number</p>
js code
function changePara(){
var val = document.getElementById("selectDiv").value;
if(val == 2){
document.getElementById("changed").innerHTML = "something";
}
else if(val == 3){
document.getElementById("changed").innerHTML = "something else";
}
// and so on
}
A jQuery based solution
Add an id to your <p> element
<p id="para">number</p>
Use jQuery to select the <select> box
let select = $('select[name="howmanyno1"]')
Create a function for updating the text in <p>
let updateText = function(e) {
$('#para').text("Selected item: " + select.val())
}
And then make the select box listen to the change event
select.on('change', updateText)
I hope this solution will be usefull
var textBlocks = new Array(
'Select from the list to change this box',
'Text block two',
'Text block three');
function changeText(elemid) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById("display").innerHTML=textBlocks[ind];
}
</head><body>
<select id="dropDown" onChange="changeText('dropDown');">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select><br>
<div id="display">Select from the list to change this box</div>
</body></html>

how to get both values call in function javascript

please check my code i tried to get both values from different drop down menus.
<select name="select1" onchange="updatevariable(data1,select2)">
<option value="2" >2</option>
<option value="15" >15</option>
</select>
<select name="select2" onchange="updatevariable(select1,data2)">
<option value="1" >1</option>
<option value="23" >23</option>
</select>
<script type="text/javascript">
var value = "test";
var value1 = "test";
function updatevariable(data1,data2) {
value = data1;
value1 = data2;
alert(value,value1);
}
</script>
thanks
Try this:
Explanation:
What you have is called inline script, it should be avoided. You could replace all your code with this under instead. In your html what you want to do doesn't work that way. updatevariable(data1,select2) does not get the variable or the select element. So try my solution instead.
var value = "test";
var value1 = "test";
var sel = document.getElementsByTagName('select');
function updatevariable() {
value = sel[0].value;
value1 = sel[1].value;
alert(value +' - '+ value1);
}
for (var i = 0; i < sel.length; i++) {
sel[i].addEventListener('change', updatevariable);
};
Example
You could also use jQuery or Mootools if you have much code to write. Otherwise just plain JS is good also...
You're referencing JS variables that don't exist: data1, data2, select, select2
You don't need to pass any variables into the function. Try this instead:
Updated HTML with id specified on each select
<select id="select1" name="select1" onchange="updatevariable(this)">
<option value="2" >2</option>
<option value="15" >15</option>
</select>
<select id="select2" name="select2" onchange="updatevariable(this)">
<option value="1" >1</option>
<option value="23" >23</option>
</select>
And your JS function:
window.updatevariable = function(el) {
value = document.getElementById('select1').value;
value1 = document.getElementById('select2').value;
alert(value +' | ' + value1);
}
Live Example
Try this one:
<select name="select1" id="select1" onchange="updatevariable(1,select1)">
<option value="2" >2</option>
<option value="15" >15</option>
</select>
<select name="select2" id="select2" onchange="updatevariable(2,select2)">
<option value="1" >1</option>
<option value="23" >23</option>
</select>
<script type="text/javascript">
var values = new Array();
function updatevariable(index,id) {
var value = document.getElementById(id).value;
values[index] = value;
}
</script>

Categories

Resources