how to select option inside select element with javascript - javascript

So I have a select element with four options.
I want to select different options so that different functions can fire , but the onclick method is not working.
let select = document.getElementById('pbvalue');
select.addEventListener('click', dodo);
function dodo(e) {
if (e.target.value == 1) {
alert('hi')
} else {
alert('no')
}
}
<select id="pbvalue" tabindex="4">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
how to select different options, so different functions can fire according to that.

Do this:
let select = document.getElementById('pbvalue');
select.onchange = function () {
// get the selected option
var value = select.options[select.selectedIndex].value
}
// get all options:
for ( int i = 0; i < select.options.length; i++ ) {
console.log( select.options[i].value )
}
This should give you an idea of how to proceed.

use onchange event.
<select id="pbvalue" tabindex="4" onchange="dodo(event)">
<option value="0" disabled>choose</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>
<script>
function dodo(e){
switch(e.target.value){
case "1":
alert(1);//do what ever you want
break;
case "2":
alert(2);
break;
case "3":
alert(3);
break;
default:
alert("default");
break;
}
}
</script>

You can add onChange event on the select element.
<script>
function onSelectChange() {
const element = document.getElementById('pbvalue');
console.log('Selected Index: ', element.selectedIndex);
console.log('Selected Value: ', element.value);
}
</script>
<select id="pbvalue" tabindex="4" onchange="onSelectChange()">
<option value="0">""</option>
<option value="1">100</option>
<option value="2">200</option>
<option value="3">300</option>
</select>

Related

Multiple values of <option>

I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>

Using jQuery to check and see if a select box has/or contains selected options

Using jQuery, upon a change/select event, how can I check and see if multiple select boxes contain any selected items? All I am looking for is how to capture and obtain a total count of this?
Based on a validation if not equal to 0, this would set a buttons default disabled attribute to false.
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
</form>
$('#myform select).bind("change select",function() {
});
Assuming your <button> is within the form element, the following should work for you:
// binding the anonymous function of the on() method
// as the event-handler for the 'change' event:
$('#myform').on('change', function() {
// caching the $(this) (the <form>, in this case):
var form = $(this);
// finding the <button> element(s) within the <form>
// (note that a more specific selector would be
// preferable), and updating the 'disabled' property,
// finding all <option> elements that are selected,
// filtering that collection:
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
// retaining only those whose values have a length
// (in order to not-count the default 'empty'
// <option> elements:
return this.value.length;
// and then checking if that collection is
// equal to 0, to obtain a Boolean true
// disabling the <button>, or a false to
// enable the <button>:
}).length === 0);
// triggering the change event on page-load
// to appropriately enable/disable the <button>:
}).change();
$('#myform').on('change', function() {
var form = $(this);
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
return this.value.length;
}).length === 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<button>Submission button</button>
</form>
References:
change().
filter().
find().
on().
prop().
You can use the jQuery :checked selector to capture all elements that are checked. For the count, you can do:
$( "input:checked" ).length;
You can then do your condition to view if there are zero or more elements checked:
var selected = $( "input:checked" ).length;
if(selected > 0)
//do something
$('#myform select').on('change', function() {
var count = 0;
$('#myform').find('select').find('option').each(function(){
if ($(this).is(':selected')){
count++;
}
});
if (count < 0){
$('#mybutton').prop('disabled', false);
} else {
$('#mybutton').prop('disabled', true);
});
Grab all the selects on the page and just loop through them while adding a change event to each one.
Then in that change event, call a method that counts up how many selects have items selected.
https://jsfiddle.net/x833qr20/3/
// put an on change event on all the selects, can be done in onload
var ddl = $('select');
for (i = 0; i < ddl.length; i++) {
ddl[i].onchange = function() {
CountAllSelectedDDL();
}
}
// function that fires when one select gets changed
function CountAllSelectedDDL() {
var ddl = $('select');
var count = 0;
for (i = 0; i < ddl.length; i++) {
if (ddl[i].selectedIndex > 0) {
count++;
}
}
var button = document.getElementById('button');
if (count > 0) {
// set the buttons default disabled attribute to false
button.disabled = false;
} else {
button.disabled = true;
}
}
Hope this helps.
Here's a working example via jQuery
https://jsfiddle.net/wedh87bm/
$('#myform select').bind("change select",function() {
var completed = true;
$('#myform select').each(function(){
if($(this).val() == "")
{
completed = false;
}
});
if(completed)
{
$('#validate').prop("disabled",false);
} else
{
$('#validate').prop("disabled",true);
}
});

drop down onchange selected list not working?

Drop down not working when I select same option second time.
This is my code:
<html>
<body>
<p>Select a new car from the list.</p>
<select id="mySelect" onchange="myFunction()">
<option value="Audi">Audi
<option value="BMW">BMW
<option value="Mercedes">Mercedes
<option value="Volvo">Volvo
</select>
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
alert(x);
}
</script>
</body>
</html>
First time select any care eg:Audi, then it alerts Audi, after alert again select Audi then there is no alert coming. Could anybody help me whats wrong in this?
Since you select the same option TWICE so there is no change in selected object of Dropdown.
Try like below
Updated Answer
var dd = document.getElementById('mySelect');
var storeLstSlct = document.getElementById('checkIndx');
var slctdValue = '';
if(dd.selectedIndex == 0)
{
return false;
}else if(storeLstSlct.value == dd.options[dd.selectedIndex].value)
{
storeLstSlct.value = 'garbage';
return false;
}else
{
slctdValue = dd.options[dd.selectedIndex].value;
alert(slctdValue);
storeLstSlct.value = slctdValue;
}
Fiddle is HERE
The event is onchange when you try to select the item already selected change event wont fire.
Are you looking for this??
Add the following code
$('option').click(function(){
alert($(this).text());
});
Unfortunately, the above method will not work in "Chrome", try in "Internet Explorer" or "Mozialla" (atleast IE is being used for this reason :p )
you forgot to close option tags and to do this you need to attach onclick event handler to all of the options in the dropdown, see below:
var x = document.getElementById("mySelect");
//attach onclick event handlers to options
for (var i = 0; i < x.options.length; i++)
{
if (x.options[i].addEventListener)
{
/*all other browsers*/
x.options[i].addEventListener("click", function() {mysFunction(this)}, false);
}
else if (x.options[i].attachEvent) /*ie < 9*/
{
x.options[i].attachEvent("click", function() {mysFunction(this)});
}
}
//execute my alert box on item select
function mysFunction(elem) {
alert(elem.value);
}
<select id="mySelect">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
Update with Demo : http://jsbin.com/hujavalayu/1/edit
I hope this will satisfy your requirement, Please check the link
Trigger the event when selected the same value in dropdown?
<p>Select a new car from the list.</p>
<select id="ddList" onClick="onSelect()">
<option value="0">Select Me</option>
<option value="List1">List1</option>
<option value="List2">List2</option>
<option value="List3">List3</option>
</select>
<script>
var prevIndex = "";
function onSelect() {
var currIndex = document.getElementById("ddList").selectedIndex;
if (currIndex > 0) {
if (prevIndex != currIndex) {
alert("Selected Value = " + document.getElementById("ddList").value);
prevIndex = currIndex;
} else {
prevIndex = "";
}
}
}
</script>
you should use onclick="this.value=null" and define your onchange as well,
so every time you select any option it will clear the selected item and you can select same option again ;).
Here is the sample Code:
$serial_no = 0;
<select id="<?php echo $serial_no++; ?>" onclick="this.value=null" onchange="update_value(this.value,this.id)" class="form-control" required>
<option><?php echo $row['card']; ?></option>
<option>---------</option>
<option>Pending</option>
<option>Deliver</option>
</select>
update_value(item){
alert(item);
}

how can select from drop down menu and call javascript function

I have a drop down which has many options. I want that when I select any
option then it calls a function through JavaScript.
the code which I used is here
<select name="aa" onchange="report(this.value)"> <--- this is function in .js
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
I want when I select daily then function(daily) is invoked
and vice versa.
function report(daily)<-- js function {
loadXMLDoc('script/d_report.php','responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
function report(monthly) {
document.getElementById('responseTag').style.visibility='visible';
loadXMLDoc('script/m_report.php','responseTag');
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
<select name="aa" onchange="report(this.value)">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
function report(period) {
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
}
Unobtrusive version:
<select id="aa" name="aa">
<option value="">Please select</option>
<option value="daily">daily</option>
<option value="monthly">monthly</option>
</select>
using
window.addEventListener("load",function() {
document.getElementById("aa").addEventListener("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
document.getElementById('responseTag').style.visibility='visible';
document.getElementById('list_report').style.visibility='hidden';
document.getElementById('formTag').style.visibility='hidden';
});
});
jQuery version - same select with ID
$(function() {
$("#aa").on("change",function() {
const period = this.value;
if (period=="") return; // please select - possibly you want something else here
var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
loadXMLDoc(report,'responseTag');
$('#responseTag').show();
$('#list_report').hide();
$('#formTag').hide();
});
});
Greetings
if i get you right you need a JavaScript function that doing it
function report(v) {
//To Do
switch(v) {
case "daily":
//Do something
break;
case "monthly":
//Do somthing
break;
}
}
Regards
<script type="text/javascript">
function report(func)
{
func();
}
function daily()
{
alert('daily');
}
function monthly()
{
alert('monthly');
}
</script>

Playing with selects and javascript

My code is:
<select name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>
<select name='other'>
<option>Rats</option>
<option>Cats</option>
<option>Oranges</option>
<option>Audi</option>
</select>
How can I filter my second <select>, so it would only show items which I want eg. if I choose Animals, my select would be:
<select name='other'>
<option>Rats</option>
<option>Cats</option>
</select>
and if I choose "Food", my <select> would look like:
<select name='other'>
<option>Oranges</option>
</select>
Well, I hope you get the idea. Thanks.
You'd need to create some kind of association between the selects, I'd recommend using the data-* attribute:
<select id="main_select" name='main'>
<option>Animals</option>
<option>Food</option>
<option>Cars</option>
</select>
<select id="other_select" name='other'>
<option data-category="Animals">Rats</option>
<option data-category="Animals">Cats</option>
<option data-category="Food">Oranges</option>
<option data-category="Cars">Audi</option>
</select>
Once that's in place for all of the <option> elements, the JavaScript code would look something like this:
EDITED, this works:
$(function() {
var cloned = $('#other_select option').clone();
$('#main_select').change(function() {
var selectedCategory = $(':selected', this).text();
var filtered = $(cloned).filter("[data-category='" + selectedCategory + "']");
$("#other_select option").replaceWith(filtered);
});
$('#main_select').change(); //fire the event initially.
});
jsFiddle example
You could add a change event handler to the main select box that then branches on which option was selected and then dynamically adds options to the other select. The following assumes a select with id main and id other:
HTML:
<select name="main" id="main">
<option value="1">Cars</option>
<option value="2">Food</option>
<option value="3">Animals</option>
</select>
<!-- Default the other select to 'cars' -->
<select name="other" id="other">
<option value="Audi">Audi</option>
</select>
JavaScript:
$("#main").bind("change", function() {
var categories = $("#other").get(0);
categories.options.length = 0;
switch (this.value) {
case "1":
categories.options[0] = new Option("Audi", "Audi");
break;
case "2":
categories.options[0] = new Option("Oranges", "Oranges");
break;
case "3":
categories.options[0] = new Option("Rats", "Rats");
categories.options[1] = new Option("Cats", "Cats");
break;
}
});
Check out an example here: http://jsfiddle.net/andrewwhitaker/nRGC9/
The naive solution would be:
$('select [name=main]').change(function(){
var other = $('select [name=other] option');
switch($(this).val()){
case 'Animals':
other.each(function () { if (!isAnimal($(this).val()))
$(this).hide();
else
$(this).show();
});
//where isAnimal is a function that accepts a string parameter and checks whether its an animal or not
break;
case 'food':
//continue in the same manner......
}});

Categories