How to get multiple values from an HTML <select> element - javascript

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>

Related

How can I get the latest HTML tags of a changeable elements, like Select, Checkbox, Input in JS/Jquery?

I need to get the HTML tags of the changeable element so that I can pass them to create a PDF. But, whenever I use element.innerHTML or element.html(), I get the HTML tags generated after page load but not after I made the changes.
In HTML:
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
In JS:document.getElementById("testSelect").innerHTML
It returns:
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
And now if I manually change the value to 2, then
In JS:
document.getElementById("testSelect").value
"2"
as you can see the value is changed. But, the HTML tags won't change as
In JS:
document.getElementById("testSelect").innerHTML
"
<option id="no">-- not selected --</option>
<option id="one" selected="">1</option>
<option id="two">2</option>
"
Still, I get the old tags. Instead, I want something like this.
"
<option id="no">-- not selected --</option>
<option id="one">1</option>
<option id="two" selected="">2</option>
"
I made this script for you hope it helps you!
var selectBox=document.querySelector("#testSelect");
selectBox.addEventListener("change", function(){
const selectBoxOptions=selectBox.querySelectorAll("option");
selectBoxOptions.forEach((option)=>{
option.removeAttribute("selected");
});
detectOptionObjectByValue(this, this.value).setAttribute("selected", "selected");
});
function detectOptionObjectByValue(selectBox, value){
const options=selectBox.querySelectorAll("option");
let pos=0, obj=false;
options.forEach(function(option){
option.value==value?obj=options[pos]:0;
pos++;
});
return obj;
}
<select id="testSelect">
<option id="no">-- not selected --</option>
<option id="one" selected>1</option>
<option id="two">2</option>
</select>
You can make a function which will iterate through all options and set all the selected attributes to false
$('select option[value=' + i + ']').attr("selected",false);
Then based on the value selected set the attribute to true
$('select option[value=' + this.value + ']').attr("selected",true);
const dropdownElement = document.getElementById('testSelect')
dropdownElement.onchange = function () {
clearSelected()
$('select option[value=' + this.value + ']').attr("selected",true);
console.log("value selected: " + this.value);
console.log("html: " + dropdownElement.innerHTML)
};
// set all the options to unselected
function clearSelected(){
var elements = dropdownElement.options;
for(var i = 0; i < elements.length; i++){
$('select option[value=' + i + ']').attr("selected",false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="testSelect">
<option id="no" value="0">-- not selected --</option>
<option id="one" value="1" selected>1</option>
<option id="two" value="2">2</option>
</select>
On jQuery site you have similar question explained:
https://learn.jquery.com/using-jquery-core/faq/how-do-i-get-the-text-value-of-a-selected-option/
$(function(){
$('#select').change(function(){
$('#output-value').text($(this).val());//get value
$('#output-element').text($(this).find('option:selected').text());//get text of selected element
$(this).find('option').each(function(){
$(this).attr('selected', $(this).is('option:selected')); //adds and removes selected attribute
});
$('#output-html').text($(this).html());
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="select" >
<option>--</option>
<option value="1" >1 val</option>
<option value="2" >2 val</option>
<option value="3" >3 val</option>
</select>
<br/>
Value
<div id="output-value" ></div>
Element
<div id="output-element" ></div>
HTML
<div id="output-html"></div>

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

How to select option with a name?

I have the following <select>:
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>
When I pass a variable through get, which will be equal to one of the name, I want that particular <option> to selected.
You should use filter method in order to find out option which have your given text.
var name="Nitheesh";
var option=$("select option").filter(function(i,option){
return $(option).text()==name;
}).attr('selected','selected');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="Nitheesh">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>
If you want to obtain an option by particular name attribute, use this:
$("option[name = '" + name + "']").attr('selected','selected');
Use the Attribute Equal Selector like this:
var someName = /*...*/;
var $option = $("[name = '" + someName + "']");
Here is a reference of other CSS Selectors.
Using jQuery can use an attribute selector
var newVal = 4306;
$('#to option[name="' + newVal +'"]').prop('selected',true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>
Here is a sample
$(document).ready(function(){
//given get val
var val = "4307";
$("#to option[name="+val+"]").attr("selected",true);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="to" name="contact">
<option value=""></option>
<option name="4307" value="">Nitheesh</option>
<option name="4306" value="">Ramanatan</option>
</select>

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.

Can't get jquery to set value of select input when value of first select changes

I'm trying to update the value of a select input when I change the value of another select input. I cannot get anything to happen on the page and want to make sure I don't have a syntax error or some other dumb thing in this code.
<div class="group">
<div class="inputs types">
<strong style="font-size:13px;">Category:</strong>
<select name="id" id="ctlJob">
<option value="1">Automotive</option>
<option value="2">Business 2 Business</option>
<option value="3">Computers</option>
<option value="4">Education</option>
<option value="5">Entertainment & The Arts</option>
<option value="6">Food & Dining</option>
<option value="7">Government & Community</option>
<option value="8">Health & Beauty</option>
<option value="9">Home & Garden</option>
<option value="10">Legal & Financial Services</option>
<option value="11">Professional Services</option>
<option value="12">Real Estate</option>
<option value="13">Recreation & Sports</option>
<option value="14">Retail Shopping</option>
<option value="15">Travel & Lodging</option>
</select>
<select name="type" id="ctlPerson"></select>
</div>
</div>
<script>
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
$('#ctlPerson').html('<option value="123">ascd</option>');
});
});
</script>
Try using append instead:
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
var ctl = $('#ctlPerson').append('<option value="123">'+val+'</option>')[0].options;
ctl.selectedIndex = ctl.length-1;
});
});
http://jsfiddle.net/J69q8/
I think you also need to set the 'selected' property. Add
$('#ctlPerson option[value="123"]').attr('selected', 'selected');
to the end of the script. You are currently adding the option to the select list, but are not changing the select list to show it.
<div id="test">
<select name="sel" id="sel">
<option name="1" id="1" value="1">Automotive</option>
<option name="2" id="1 value="2">Business 2 Business</option>
<option name="3" id="1 value="3">Computers</option>
</select>
<select name="sel2" id="sel2"></select>
</div>
<script>
$("#sel").change(function() {
var val = $(this).val();
$('#sel2').html('<option value="1">NEW</option>');
)};
</script>
this works fine for what you need to do.
it's something like what you have

Categories

Resources