Javascript change input value when select option is selected - javascript

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 :)

Related

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>

Get pre-selected value of an HTML select element

Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})
Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>
There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");
The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');

how can i store two info on a single select and call them in separate textbox HTML/JS

<span id="s_home_country">
<select name="Home Country" id="home_country">
<option value="Select one" selected="selected">Select one</option>
<option value="h1">Home1</option>
<option value="h2">Home2</option>
<option value="h3">Home3</option>
<option value="h4">Home4</option>
</select>
</span>
and I have another data that i want to incorporate, when Home1 is selected, I want this to show 21-dec into another textbox automatically. and so on..
var Home_country = [
"21-Dec",
"01-Jan",
"01-Jan",
"01-Jan",
];
You could use an object and an event listener.
var home_country = {
"h1":"21-Dec",
"h2":"01-Jan",
"h3":"01-Jan",
"h4":"01-Jan",
};
var selectbox = document.getElementById('home_country');
var textbox = document.getElementById('home_country_date');
selectbox.addEventListener('change', function(e){
textbox.value = home_country[this.value]
})
<span id="s_home_country">
<select name="Home Country" id="home_country">
<option value="Select one" selected="selected">Select one</option>
<option value="h1">Home1</option>
<option value="h2">Home2</option>
<option value="h3">Home3</option>
<option value="h4">Home4</option>
</select>
</span>
<input type="text" id="home_country_date">
Please find below snippet just add another attribute data-attr1 and on change of select list find selected option and get its attribute with name data-attr1 and pass attribute's value to textbox
$("#home_country").on("change",function(){
$(".txtvalue").val($(this).find("option:selected").attr("data-attr1"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="s_home_country">
<select name="Home Country" id="home_country">
<option value="Select one" selected="selected">Select one</option>
<option data-attr1="21-Dec" value="h1">Home1</option>
<option data-attr1="01-Dec" value="h2">Home2</option>
<option data-attr1="02-Dec" value="h3">Home3</option>
<option data-attr1="03-Dec" value="h4">Home4</option>
</select>
</span>
<input type="text" class="txtvalue" />
Add an event listener to your select input which outputs the relevant value from your array when an option is selected:
var el = document.getElementById('home_country');
var textbox = document.getElementById('your_textbox_el');
el.addEventListener('change', function(e){
if (e.target.value == 'h1') {
textbox.value = Home_country[0];
} else if (e.target.value == 'some other condition') {
// do something else
}
}
Unless I'm misunderstanding you, you can just put the values of the Home_country array inside the value properties of the options like so:
<span id="s_home_country">
<select name="Home Country" id="home_country">
<option value="Select one" selected="selected">Select one</option>
<option value="21-Dec">Home1</option>
<option value="01-Jan">Home2</option>
<option value="01-Jan">Home3</option>
<option value="01-Jan">Home4</option>
</select>
</span>
Now, when you do get the value of your select element, it will be the value in the array that you gave.

OnSelect equivalent for <option>?

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;

how to activate a textbox if I select an other option in drop down box

suppose I've a 3 options in a drop down box say red , blue, others.
If a user select option as an others then below a text box should be visible to wrtie his own favourite color.
I can populate the drop down box with colors but do not know how to bring textbox visible on selection of others in the
drop-down box. I know that using javascript it is possible to do but I am quite new to javascript. can anybody please help me
out??
This is the select option I am implementing in my html form
<select name="color"> // color
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" /></td> // this textbox should be hidden //until unless others is selected in the drop down box
Below is the core JavaScript you need to write:
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('color');
if(val=='pick a color'||val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" style='display:none;'/>
</body>
</html>
Coded an example at http://jsbin.com/orisuv
HTML
<select name="color" onchange='checkvalue(this.value)'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="color" id="color" style='display:none'/>
Javascript
function checkvalue(val)
{
if(val==="others")
document.getElementById('color').style.display='block';
else
document.getElementById('color').style.display='none';
}
Inline:
<select
onchange="var val = this.options[this.selectedIndex].value;
this.form.color[1].style.display=(val=='others')?'block':'none'">
I used to do this
In the head (give the select an ID):
window.onload=function() {
var sel = document.getElementById('color');
sel.onchange=function() {
var val = this.options[this.selectedIndex].value;
if (val == 'others') {
var newOption = prompt('Your own color','');
if (newOption) {
this.options[this.options.length-1].text = newOption;
this.options[this.options.length-1].value = newOption;
this.options[this.options.length] = new Option('other','other');
}
}
}
}
As Umesh Patil answer have comment say that there is problem.
I try to edit answer and get reject. And get suggest to post new answer.
This code should solve problem they have (Shashi Roy, Gaven, John Higgins).
<html>
<head>
<script type="text/javascript">
function CheckColors(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';
}
</script>
</head>
<body>
<select name="color" onchange='CheckColors(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type="text" name="othercolor" id="othercolor" style='display:none;'/>
</body>
</html>
Simply
<select id = 'color2'
name = 'color'
onchange = "if ($('#color2').val() == 'others') {
$('#color').show();
} else {
$('#color').hide();
}">
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<input type = 'text'
name = 'color'
id = 'color' />
edit: requires JQuery plugin
This will submit the right form response (i.e. Select value most of the time, and Input value when the Select box is set to "others"). Uses jQuery:
$("select[name="color"]").change(function(){
new_value = $(this).val();
if (new_value == "others") {
$('input[name="color"]').show();
} else {
$('input[name="color"]').val(new_value);
$('input[name="color"]').hide();
}
});

Categories

Resources