how to get both values call in function javascript - 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>

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>

how I can get the content the select from the value [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 get multiple values from an HTML <select> element

How to take the values of value1 and value2 in two variables using javascript?
<select class="form-control" id="country" name="country">
<option value="**value1**" "**value2**" >Select Item</option>
</select>
You could make your own attribute. I know you probably do not want to get the element with an ID, but I don't know the context. You can just call getAttribute on the option and use any name you gave to the "custom" attribute.
window.addEventListener('load', ()=>
{
const option = document.getElementById('option');
function init()
{
//Use this to get the values
console.log(option.getAttribute('other-value'));
}
init();
});
<select class="form-control" id="country" name="country">
<option id="option" value="value1" other-value="value2">Select Item</option>
</select>
I don't know what you really want to do with your piece of code,
but here is a proper way to use the option elements, and a way to split multiple values with a fixed separator:
var example = document.getElementById('example');
example.addEventListener('change', function() {
// Console displays the “value”, and not the text, of the selected option
console.log("option value:", example.value);
});
// Here is what I'll do with your "multiple" values
var country = document.getElementById('country');
var options = country.querySelector('option');
var values = options.value.split("/");
values.forEach(function(val) {
country.innerHTML += "<option value=" + val + ">" + val + "</option>";
});
<p>My simple example</p>
<select id="example" name="country">
<option value="--">Select Country</option>
<option value="GB">Great Britain</option>
<option value="FR">France</option>
</select>
<br>
<br>
<p>Example with option getting splitted</p>
<select class="form-control" id="country" name="country">
<!-- Let's say your multiple values are separated by a "/" -->
<option value="**value1**/**value2**">Select Item</option>
</select>
Hope it helps.
$('select').on('change', function() {
console.log( $('#country').val() );
console.log($(this).find(':selected').data('second'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="form-control" id="country" name="country">
<option value="value1" data-second ="value2" >Select Item 1</option>
<option value="value3" data-second ="value4" >Select Item 2</option>
</select>

How to get data attribute of option tag in JavaScript

Want to get data attribute value from selected dropdown option.
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
var rc = ? //value of data-rc
var clnc = ? //value of data-clnc
No jQuery please only JavaScript :)
You can read them out via dataset property.
var option = document.getElementsByTagName("option")[0];
console.log(option.dataset.rc)
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
Or, if you want to get the values of the selected option:
var selection = document.getElementById("mySelect");
selection.onchange = function(event){
var rc = event.target.options[event.target.selectedIndex].dataset.rc;
var clnc = event.target.options[event.target.selectedIndex].dataset.clnc;
console.log("rc: " + rc);
console.log("clnc: " + clnc);
};
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
<option value="21" data-rc="23" data-clnc="30">Treatment1</option>
<option value="21" data-rc="31" data-clnc="50">Treatment2</option>
<option value="21" data-rc="14" data-clnc="75">Treatment3</option>
</select>
suppose we have a select field
<select id="ddlViewBy">
<option value="1" data-rc="25" data-clnc="10" selected="selected">test1</option>
<option value="2" >test2</option>
<option value="3">test3</option>
</select>
Now we will get the select list and its selected option
var e = document.getElementById("ddlViewBy");
var option= e.options[e.selectedIndex];
Now we have the selected option we can get its attribtues
var attrs = option.attributes;
attrs is the attributes array you can get attribtues by index you want.
Or you can get attribtues by
var datarc = option.getAttribute("data-rc");
Check this working pen
working pen
$('#options').on('change', function(){
alert($(this).find("option:selected").attr('data-rc'))
alert($(this).find("option:selected").attr('data-clnc'))
});
var mySelect = document.querySelector('#mySelect')
console.log('mySelect value ' + mySelect.value)
console.log('mySelect data-rc ' + mySelect.selectedOptions[0].getAttribute("data-rc"))
console.log('mySelect data-clnc ' + mySelect.selectedOptions[0].getAttribute("data-clnc"))
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
$(selector).find("option:selected").data("rc") for rc and clnc for clnc where selector is your "select" tag id/class
You can do that with jquery selector
var rc = $('select option:selected').data('rc');

Change select box value depending other selected option box

i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>

Categories

Resources