OnSelect equivalent for <option>? - javascript

I have a <select> tag and I want it to change the value of a hidden input when an option is selected.
What I thought was to use this:
<input type=hidden value=Ineedtochangethis name=asdf>
<select><option onselect="stuff()">Option 1 is selected</option>...</select>
And then this
function stuff() {
document.getElementsByName("asdf").value=opt1slct;
}
Of course, it doesn't work. What can I do to get a similar effect?

please check following code:
<select onChange="jsFunction()" id="selectOpt">
<option value="1" >1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
if(myselect.options[myselect.selectedIndex].value == 1){
alert('hide');
}else{
alert('show');
}
}

By using the selectedIndex property (and potentially the options one as well) of your select element.
<input id="yourHiddenField" type="hidden"/>
<select onchange="stuff(this);">
<option>Option 1 is selected</option>
</select>
And the JavaScript:
function stuff(yourSelectElement){
document.getElementById('yourHiddenField').value = yourSelectElement.options[yourSelectElement.selectedIndex].innerHTML;
}
And if you want to store just one number in your hidden field, use the value attribute on your option tags like so:
<option value="1">Option 1 is selected</option>
Then the JS changes like this:
document.getElementById('yourHiddenField').value = yourSelectElement.options[yourSelectElement.selectedIndex].value;

Related

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

Javascript change input value when select option is selected

I am very new to javascript. So i have a select option and an input field. What i want to achieve is to have the value of the input field change when i select a particular option. This is what i have tried:
First Name: <input type="text" value="colors">
<select name="">
<option>Choose Database Type</option>
<option onclick="myFunction(g)>green</option>
<option onclick="myFunction(r)>red</option>
<option onclick="myFunction(o)>orange</option>
<option onclick="myFunction(b)>black</option>
</select>
<script>
function myFunction(g) {
document.getElementById("myText").value = "green";
}
function myFunction(r) {
document.getElementById("myText").value = "red";
}
function myFunction(o) {
document.getElementById("myText").value = "orange";
}
function myFunction(b) {
document.getElementById("myText").value = "black";
}
</script>
A few things:
You should use the onchange function, rather than onclick on each individual option.
Use a value attribute on each option to store the data, and use an instance of this to assign the change (or event.target)
You have no ID on your text field
You're missing the end quote for your onclick function
<select name="" onchange="myFunction(event)">
<option disabled selected>Choose Database Type</option>
<option value="Green">green</option>
<option value="Red">red</option>
<option value="Orange">orange</option>
<option value="Black">black</option>
</select>
And the function:
function myFunction(e) {
document.getElementById("myText").value = e.target.value
}
And add the ID
<input id="myText" type="text" value="colors">
Fiddle: https://jsfiddle.net/gasjv4hs/
More proper way is to put your JS code in a different .js file and use Jquery as when you go further with your programming this is the proper way.
Your HTML
<input type="text" id="color" name="color">
<select name="" id="changeData">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
Your JS
$(document).ready(function () {
$('#changeData').change(function(){
var color = $(this).val();
$('#color').val(color);
})
});
Also make sure that you have added Jquery Library to your Project. You can either download Jquery and add in your project folder OR also you can use CDN. in this example CDN is used.
I came up with a similar problem. In my case i was trying to change the minimum value of an input based on the value of an option in a select list. I tried to apply the above solutions but nothing worked. So i came with this, which can be applied to problems similar to this
HTML
<input id="colors" type="text" value="">
<select id="select-colors" name="" onchange="myFunction()">
<option disabled selected>Choose Colour</option>
<option value="green">green</option>
<option value="red">red</option>
<option value="orange">orange</option>
<option value="black">black</option>
</select>
JS
function myFunction() {
var x = document.getElementById("select-colors").value;
document.getElementById("colors").value = x;
}
This works by getting the value of the select with id "select-colors" on every change, assigning it into a variable "x" and inserting it into the input value with id "colors". This can be implemented in anyway based on your problem
You create functions with same name multiple times.
Only last one will work.
the variables you pass g,r,o,b are undefined.
Don't add onclick to option add onchange to select.
Make use of HTML5 data-* attribute
function myFunction(element) {
document.getElementById("myText").value = element;
}
First Name: <input type="text" id="myText" value="colors">
<select name="" onchange="myFunction(this.value);">
<option>Choose Database Type</option>
<option data-value="green">green</option>
<option data-value="red">red</option>
<option data-value="orange">orange</option>
<option data-value="black">black</option>
</select>
You can resolve it this way.
` First Name:
<select name="" onchange="myFunction()" id="selectID">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script>
function myFunction() {
var selectItem = document.getElementByID('selectID').value;
document.getElementByID('yourId').value = sekectItem;
}
</script>
Here's a way to achieve that:
var select = document.getElementById('colorName');
function myFunction(event) {
var color = 'No color selected';
if (select.selectedIndex > 0) {
color = select.item(select.selectedIndex).textContent;
}
document.getElementById('myText').value = color;
}
select.addEventListener('click', myFunction);
myFunction();
First Name: <input type="text" id="myText">
<select id="colorName">
<option>Choose Database Type</option>
<option>green</option>
<option>red</option>
<option>orange</option>
<option>black</option>
</select>
Your code should be like following.
<input type="text" name="color" id="color">
<select name="" id="change_color">
<option>Choose Database Type</option>
<option >green</option>
<option >red</option>
<option >orange</option>
<option >black</option>
</select>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function () {
$('#change_color').change(function(){
var color = ($(this).val());
$('#color').val(color);
})
});
</script>
Here is JS Code that worked for me
var selectYear = document.getElementById('select-year');
selectYear.addEventListener('change', function() {
var selectedYear = document.getElementById('selected-year');
selectedYear.innerHTML = selectYear.value;
});
Select Input ID: select-year
Text ID: selected-year
Code generated from Codex AI :)

Get a select box by name and set another select box by same name?

I am building a fairly complex form-- I need to copy some data between one and another and I am using jQuery to do this. The only road block I am running into is setting the state.
I have two drop downs, one us using the full state name as the value and the other is using the state abbreviation as the value. The names are the same-
so on form 1 it looks like
<option value="Illinois">Illinois</option>
and form 2 it looks like
<option value="IL">Illinois</option>
Each form has its own unique css selector. How can I set the selected value of form 2 to match what is in form 1 using jQuery?
I do not have any control over the forms, just need to manipulate the input. Have tried using a name selector in jQuery, but I'm not having any luck.
Thank you.
You can do something like this
<select id="fullName">
<option value="Maryland" data-abbr="MD">Maryland</option>
<option value="Illinois" data-abbr="IL">Illinois</option>
<option value="Delaware" data-abbr="DE">Delaware</option>
</select>
<select id="abbr">
<option value="MD">Maryland</option>
<option value="IL">Illinois</option>
<option value="DE">Delaware</option>
</select>
And your jQuery
$('body').on('change', '#fullName', function(){
var abbr = $(this).find('option:selected').data('abbr');
$('#abbr').val(abbr);
});
Try this
<form id="form1" name="form1">
<select name="states" onchange="changeselect(this)">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
<option value="option5">option5</option>
</select>
</form>
<form id="form2" name="form2">
<select name="states">
<option value="opt1">option1</option>
<option value="opt2">option2</option>
<option value="opt3">option3</option>
<option value="opt4">option4</option>
<option value="opt5">option5</option>
</select>
</form>
function changeselect(elem)
{
var value1 = $(elem).val();
$('#form2 select option').removeAttr('selected');
$('#form2').find('select option').each(function(){
var value2 = $(this).html();
if(value1 == value2)
{
var selected = $(this).attr('value');
$('#form2 select').val(selected);
}
});
}
If you create 2 arrays which exactly correspond with one another:
var StateNames = ['Alabama','Alaska','Arizona','Arkansas','California','Colorado','Connecticut','Delaware','Florida','Georgia','Hawaii','Idaho','Illinois','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','New York','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Texas','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];
var StateAbbreviations = ['AL','AK','AZ','AR','CA','CO','CT','DE','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY'];
You can:
get the value from the first option list;
find that value's index in the first array; (hint: use indexOf)
use the same index to find out what the corresponding abbreviation is in the second array;
use the returned abbreviation to locate the correct option in the second option list

Remove option in select

<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
$(".one").change(function(){
})
I would like make - for example if i select in first position option 1 then i others selects this option should be removed.
So if i in first select i select 1 then in select second and third i have only option 2 and 3. If in second select i select 2 then in last select i have only option 3.
How can i make it? I would like use jQuery.
LIVE: http://jsfiddle.net/9N9Tz/1/
If you need to sort something, consider using something like jQuery UI sortable as a bunch of drop down menus make a really poor UX for that.
But to answer your question:
var $selects = $('.one');
$selects.on("keyup click change", function(e) {
$selects.not(this).trigger('updateselection');
}).on("updateselection", function(e, data) {
var $this = $(this);
$this.children().show();
$selects.not(this).each(function() {
var value = $(this).val();
if (value) {
$this.children('[value="' + value + '"]').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<br />
<select class="one">
<option></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Hiding an option works in current firefox. I'm not sure about legacy browser. Hiding, but not removing, the element makes sure that you can change your selection without having crippled your input elements.
Here you go http://jsfiddle.net/Calou/9N9Tz/6/.
When the value of the <select>s changes, just take this value and search for the <option>s with this value in the others <select>s and remove them.
$(".one").change(function(){
var val = this.value
if (val !== '') {
$(this).siblings().find('option[value=' + val + ']').remove()
}
})
// As soon as all selects have one class, you'll have to distinguish them:
$(".one").each(function() {
// Now this corresponds to one select (in the loop over all)
$(this).change(function() {
// Fix what've done before
$('option').show();
// Find every other select, find an option in it
// that has the same value that is selected in current select
// (sorry for the description)
$('.one').not(this).find('option[value=' + $(this).find('option:selected').val() +']').hide();
});
})​;​
jsFiddle
It will be easy if you use different class for second and third select element
$(".one").change(function(){
var val = parseInt($(this).val());
$('.two,.three').find('option:contains('+val+')').remove();
});
EDIT:
Updated code to apply for multiple selects. [Thanks to all commentators and Alex for bringing it to notice ]
$(".one").change(function(){
var val = parseInt($(this).val());
$(this).siblings().find('option:contains('+val+')').remove();
});

Calling Change on SELECT Dynamically

I have a dropdownlist which is declared like this:
<select class="ddl" onchange="reloadValues(this)">
options...
</select>
There is another dropdownlist which is identical
<select class="ddl" onchange="reloadValues(this)">
options...
</select>
When I change the first dropdownlist the reloadValues function is fired. How can I also fire the reloadValues of the second dropdownlist.
If you use jquery, you can do it like so
$(document).ready(function() {
$(".ddl").change(function(ev) {
var that = this;
reloadValues(that);
$(".ddl").each(function(item, index) {
if(this !== that)
reloadValues(this);
});
});
});
Without jquery
function reloadValues(that)
{
var ddl=document.getElementsByTagName('select')
for(i=0;i<ddl.length;i++)
{
if(ddl[i].className=='ddl')
{
if(that==ddl[i])
{
alert("This element triggered the event and contains "+ddl[i].length+" items!");
}
else
{
// Do something
alert("This element didn't trigger the event and contains "+ddl[i].length+" items!");
}
}
}
}​
Here is a fiddle.
Unfortunately you cannot compare the actual functions as the onevent function is unique per element.
It would look something like
function onchange()
{
reloadValues(this)
}
It would be super elegant if we could loop through all selects and compare the reloadValues function inside the unique per element onchange function to see if it's the same function or not.
But a separate function would be assigned to each element, so they cannot be directly compared. You could compare the string values by element1.onchange+'' == element2.onchange+'' but you may get unexpected results in some browsers, as they will format the string value differently sometimes.
Here is an example that works by checking the string value of the attribute. E.g. it performs the same routine on all elements that have the value reloadValues(this) set to their onchange attribute.
In this example, changing the index of one select changes any select on the page to the same index so long as it has the reloadValues(this) text exactly in its onchange attribute. In this example, it doesn't matter what the id or class attributes are of the selects.
However, tagging or changing the text value of the onchange attribute will affect it.
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script language="javascript" type="text/javascript">
function reloadValues( XXX ) {
var allSelects = document.body.getElementsByTagName("select");
for( var i = 0; i < allSelects.length; i++) {
if(allSelects[i].attributes["onchange"].value == "reloadValues(this)") {
allSelects[i].selectedIndex = XXX.options.selectedIndex;
}
}
}
</script>
<body>
<select class="ddl" onchange="reloadValues(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="fsfsfs" onchange="reloadValues(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="ddl" onchange="reloadValues(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select class="ddl" onchange="reloadValues(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</body>
</html>

Categories

Resources