Accessing several form options - javascript

How do I access several option values in a form, under two different select ids, with JavaScript?
Here's the code: (JSFiddle: http://jsfiddle.net/sebastianonline/9yL4rv6j/)
(HTML5)
Select your favorite fruit:
<select id="mySelect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pineapple">Pineapple</option>
<option value="banana">Banana</option>
</select>
Click the button to return the value of the selected fruit.
Pick a product
Amount
<label><strong>Amount:</strong></label>
<select id="amount">
<option selected>1</option>
<option>2</option>
<option>3</option>
</select>
<!-- text value here -->
<p id="include"></p>
<p id="include2"></p>
(JavaScript)
function mySelect()
{
var x = document.getElementById("mySelect").selectedIndex;
var p = document.getElementsByTagName("option")[x].value;
document.getElementById("include").innerHTML = p;
}
function myAmount()
{
var a = document.getElementById("amount").selectedIndex;
var b = document.getElementsByTagName("option")[a].value;
document.getElementById("include2").innerHTML = b;
}
Function mySelect() is able to pick the right option value and insert it in the first paragraph, however, the second function (myAmount()) is picking the same options as the first function, even though its id points to select id="amount". I need the second function to pick the options in select id="amount" and print it in p id="include2".

You are using document.getElementsByTagName("option"), which returns all option elements in the document, not all options for the current select. Which of course means your indexing is out.
But you can get the selected option's value in a given select element using the .value property of the select element itself:
function mySelect() {
var x = document.getElementById("mySelect").value;
document.getElementById("include").innerHTML = x;
}
function myAmount() {
document.getElementById("include2").innerHTML =
document.getElementById("amount").value;
}

Related

move option from one select to another select with JS

From two html selects, I would like to move when I click the button to move an option to another select with javascript vanila, and when it has been moved, it is removed from the select from where it was at the beginning. It should also work the other way around.
function move1() {
var x = document.getElementById("select1");
}
function move2() {}
<select id="select1">
<option value="0">1</option>
<option value="0">2</option>
<option value="0">3</option>
</select>
<button type="button" onclick="move1()">>></button>
<button type="button" onclick="move2()"><<</button>
<select id="select2"></select>
You can do it like this:
Fetch both selects with getElementById() and store them in select_1 and select_2 variables.
Check if selected option exists by compering selectedIndex property of the select with -1. It will be equal to -1 only if the user didn't select anything.
If selectedIndex is equal to -1, then do nothing because there is nothing to transfer to second select.
If selectedIndex is different from -1, it means that user selected something and option with that index should be transfered.
Create new option for second select with document.createElement('option') and copy the selected option values to the new option.
Remove the selected option of current select with select.options.remove(select.selectedIndex)
function move1() {
const select_1 = document.getElementById("select1");
const select_2 = document.getElementById("select2");
if(select_1.selectedIndex !== -1) {
const selected_option = select_1.options[select_1.selectedIndex];
let new_option = document.createElement('option');
new_option.value = selected_option.value
new_option.innerHTML = selected_option.innerHTML;
select_2.appendChild(new_option);
select_1.options.remove(select_1.selectedIndex)
}
}
function move2(){
const select_1 = document.getElementById("select1");
const select_2 = document.getElementById("select2");
if(select_2.selectedIndex !== -1) {
const selected_option = select_2.options[select_2.selectedIndex];
let new_option = document.createElement('option');
new_option.value = selected_option.value
new_option.innerHTML = selected_option.innerHTML;
select_1.appendChild(new_option);
select_2.options.remove(select_2.selectedIndex)
}
}
<select id="select1">
<option value="0">1</option>
<option value="0">2</option>
<option value="0">3</option>
</select>
<button type="button" onclick="move1()">>></button>
<button type="button" onclick="move2()"><<</button>
<select id="select2"></select>
Here's a version that can manage more than 2 sets of <select> and <button> pairs. If there are more than 2 pairs, all recieving <select> will add the selcted <option>. In the HTML a data-* attribute is added to each <option>:
<option data-idx="0" value='1'>1</option>
<option data-idx='1' value="2">2</option>
<option data-idx='2' value="3">3</option>
The value of data-idx is the <option>s original index position. In the event handler switchOPt(e) the data-idx value will be used to determine what index it should be placed in:
to.add(copy, +copy.dataset.idx);
All details are commented in the example.
/*
Collect all buttons into a HTMLCollection then convert it
into an Array. Same with all select
*/
const btnArray = [...document.querySelectorAll('button')];
const selArray = [...document.querySelectorAll('select')];
/*
Iterate through the array of buttons. Register each button
to the click event. The event handler is switchOpt(e)
*/
btnArray.forEach(btn => btn.addEventListener('click', switchOpt));
// Event handler always passes the Event Object
function switchOpt(e) {
/*
Determine the select that will send it's option by
matching it's #id vs this.name (the [name] of the button
the user clicked
*/
const from = document.getElementById(this.name);
// if the select doesn't have any options end function
if (from.childElementCount < 1) return;
/*
Determine the select that adds an option by .filter()
under the condition that it is NOT >from<
*/
let to = selArray.filter(sel => sel.id != from.id);
// Rereference >to< to be the select with the array
to = to[0];
// Determine which option has been selected
const opt = from.options[from.selectedIndex];
// Make a copy of the selected option
const copy = opt.cloneNode(true);
/*
Add >copy< to >to< the second parameter is the index
of the element that >copy< will be placed before it so
it'll always be in order
*/
to.add(copy, +copy.dataset.idx);
// Remove the option from >from<
opt.remove();
}
<!-- Assign each option a data attribute wuth the value
of it's index -->
<select id="A">
<option data-idx='0' value="1">1</option>
<option data-idx='1' value="2">2</option>
<option data-idx='2' value="3">3</option>
</select>
<button name='A' type="button">>></button>
<button name='B' type="button"><<</button>
<select id="B"></select>

How to create new input text using a select with values in form using Javascript?

function updateItems() {
const data = {
ItemNames: []
};
var ItemCount = document.getElementById("selectQty").value;
for (var i = 1; i <= ItemCount; i++){
data.ItemLists.push({
id: `ItemName${i}`,
value: document.getElementById(`ItemName${i}`).value
});
}
}
Above is my code, I am trying to create new input text called id="ItemName" to create based on the value in the select combobox called id="selectQty". I created this loop but it doesn't create new input text based on the selected number in the combo box. I am beginner at Javascript and doing exercises. I tried looking for other solution but I can't seem to find any. Any help will be appreciated.
This function will be called on using the select:
<select id="selectQty" onchange="updateItems()">
<option value="0" disabled selected value>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="2">3</option>
<option value="2">4</option>
<option value="2">5</option>
<option value="2">6</option>
<option value="2">7</option>
</select>
This is my input text
<input type="text" id="ItemName" placeholder="Item Name">
You need to use createElement method to create new dynamically added inputs.
To get the value of actual input we need to create we can use _this.value which will be coming from our onclick function.
You might notice this + sign which mean we are converting the string number to actual integer format for looping purposes.
Also, i have also addedlabel to each of your input when they are created you can name the label to what suits you the best.
In addition, to make it look nicer we can add line break <br> to make sure our labels and input are generated in each line.
Lastly, you need to use innerHTML to make sure that you set the results to empty each time you select a different option from the select.
You can also refer to each comment as well i have added in each line of JS code below.
Live Demo:
function updateItems(_this) {
var ItemCount = +_this.value //get the value
var results = document.querySelector('#results') //append results
results.innerHTML = '' //clear the results on each update
for (var i = 1; i <= ItemCount; i++) {
var input = document.createElement('input') //create input
var label = document.createElement("label"); //create label
label.innerText = 'Input ' + i
input.type = "text";
input.placeholder = "Type text here"; //add a placeholder
input.className = "my-inputs"; // set the CSS class
results.appendChild(label); //append label
results.appendChild(document.createElement("br"));
results.appendChild(input); //append input
results.appendChild(document.createElement("br"));
}
}
<select id="membership-members" onchange="updateItems(this)">
<option value="0" disabled selected>Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<br>
<br>
<div id="results"></div>

Two dynamic select boxes with data attribute in both and dependant on them

How to get dynamic select boxes dependant on the value of data attributes in both?
Got this code
HTML
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>
JS
var sel1 = document.querySelector('#hours');
var sel2 = document.querySelector('#paxno');
var options2 = sel2.querySelectorAll('option');
function giveSelection() {
sel2.innerHTML = '';
for(var i = 0; i < options2.length; i++) {
if(options2[i].dataset.option === $("#hours").find(":selected").data("option")) {
sel2.appendChild(options2[i]);
}
}
}
I have been trying to do this from the example given on this question on Stackoverflow, and it is working when data-attribute is non numeric but data stored in both will be numeric.
Any thoughts what I am doing wrong here? is this the best approach to 2 dynamic select boxes with both having data attributes?
Since you're using jQuery, you might as well use it all the way.
To make it consistent, always use the jQuery data() method. data() will always try to intelligently convert the value of the data field to another type if it can determine that it is a number, or an object, or an array, or etc. So your original was comparing a dataset.option to a data(), using === which removes type coersion. So nothing would ever be equal.
var sel1 = $('#hours');
var sel2 = $('#paxno');
var options2 = sel2.find('option');
function giveSelection() {
var target = sel1.find(':selected').data('option');
sel2.empty().append(
options2.filter(function(){
return $(this).data('option') === target;
})
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="hours" onchange="giveSelection()">
<option value="somethingA" data-option="1">optionA</option>
<option value="somethingB" data-option="2">optionB</option>
</select>
<select id="paxno">
<option data-option="1">optionC</option>
<option data-option="1">optionD</option>
<option data-option="2">optionE</option>
<option data-option="1">optionF</option>
</select>

How do you add data to an option tag?

I'd like to add a data value to an option tag in a select element. For example data-price but my problem is that I have multiple select tags. So how do I get JavaScript to grab the data value of that option that the user selects?
How I want it to work:
Select element #1 contains:
<select onchange="updatePrice()">
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
Select element #2 contains:
<select onchange="updatePrice()">
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
Then I'm honestly not sure what to do in the JS... But I want it to grab what the user selected, get the data-price then calculate the total (just by adding select1 + select2).
EDIT: My answer is different than this question because my question is more specific and requires different methods. Even though this is specific it could help a developer in the future by the answers it gets. Therefore it is not a duplicate but a more specific question than the other. Though that question has a simpler answer that could be plugged in if the developer knows how to.
Here is some code matching your discription. A few notes: Use the value attribute to get direct access to the option value from the select element. The unary operator (+) converts the two values from strings to a operatable numbers. The third div is just to show the output total value.
function updatePrice(){
var s1 = document.getElementById("option1");
var s2 = document.getElementById("option2");
var total = +s1.value + +s2.value;
document.getElementById("price").innerHTML = "Total: $" + total
// to get the text within the selected option
var h1 = s1.options[s1.selectedIndex].text;
return total;
}
<select id="option1" onchange="updatePrice()">
<option value="1">Apple $1</option>
<option value="2">Potato $2</option>
<option value="3">Bag of Grapes $3</option>
</select>
<select id="option2" onchange="updatePrice()">
<option value="5">Really good cake</option>
<option value="15">Super Good Cake</option>
</select>
<div id="price"></div>
Let me know if you need any further explanation. Cheers.
This is a bit tricky. You need to give an identifier so our code won't get confused.
<select id="goods1" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="1">Apple $1</option>
<option data-price="2">Potato $2</option>
<option data-price="3">Bag of Grapes $3</option>
</select>
<select id="goods2" onchange="updatePrice(this)">
<option data-price="0">Select one</option>
<option data-price="5">Really good cake</option>
<option data-price="15">Super Good Cake</option>
</select>
First, add a global variable to storing current price. Second, store the identifier and the price value. Finally, manipulate the current price.
<script>
let price = 0;
let stored = {};
const updatePrice = elm => {
const id = elm.id;
const selectedPrice = parseInt(
Array.from(
elm.children
).filter(x => x.selected)[0].dataset.price
);
price = 0;
stored[id] = selectedPrice;
Object.keys(stored).forEach(key => price += stored[key]);
console.log(`Price: ${price}`);
};
</script>
Add some unique class to all selectbox whos valued need to be involved in total calculation like mul_ck
//when even a single selectbox change it will trigger re-calculation
$('.mul_ck').change(function(){
var total = 0;
//grab all _mul_ck_ and loop over them
$('.mul_ck').each(function(){
var selectValue = $(this).find(":selected").attr('data-price');
total += parseFloat(selectValue);
});
alert(total);
});

Multiselect element identifying after multiple clicks [duplicate]

This question already has answers here:
How to get all selected values of a multiple select box?
(28 answers)
Closed 6 years ago.
I've select element box with multiple options.
A
B
C
D
It also has "multiple" attribute, allowing user to choose multiple options at once (ctrl + click).
Currently I'm using
var example= document.getElementById('selectedboxid');
which returns selected element id (what is what I need!).
Problem I am facing is - if user wants to choose multiple elements, getElementById will return same id (the one, who was clicked first!). I need to return newly clicked element id on every click (choosing more than one element at once). How can this be accomplished?
Code looks like:
var example = document.getElementById('select_example');
select_example.addEventListener('change', function() {
var elementID = select_example.value; // Element ID stays the same...
...
}
});
This should work for getting the last one clicked and also grabbing the full list.
var sel = document.getElementById('sel');
// GEt all selected
sel.addEventListener('change',function() {
console.log(this.selectedOptions);
});
// Get the one clicked
sel.addEventListener('click', function(evt) {
console.log(evt.target);
});
select {
width: 200px;
height: 200px;
}
<select id="sel" multiple>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Yout can do it like this:
var selectedOptions = document.querySelectorAll('#select_example option:checked')
This will return NodeList of all selected option elements
var selectedValues = Array.prototype.map.call(selectedOptions, function(el){return el.value})
This will map array of selected option elements to array of selected values.
Use selectedOptions property. Example:
<select id="myselect" multiple="multiple">
<option value="0">0-0-0-0-0-0</option>
<option value="1">1-1-1-1-1-1</option>
<option value="2">2-2-2-2-2-2</option>
<option value="3">3-3-3-3-3-3</option>
<option value="4">4-4-4-4-4-4</option>
</select>
var select = document.getElementById('myselect');
function processChange(event) {
var selectElement = event.target;
console.log(selectElement.selectedOptions);
}
select.addEventListener('change', processChange);
Working example: https://jsfiddle.net/a8nbj7rw/

Categories