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>
I have the following HTML <select> element:
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Using a JavaScript function with the leaveCode number as a parameter, how do I select the appropriate option in the list?
You can use this function:
function selectElement(id, valueToSelect) {
let element = document.getElementById(id);
element.value = valueToSelect;
}
selectElement('leaveCode', '11');
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
Optionally if you want to trigger onchange event also, you can use :
element.dispatchEvent(new Event('change'))
If you are using jQuery you can also do this:
$('#leaveCode').val('14');
This will select the <option> with the value of 14.
With plain Javascript, this can also be achieved with two Document methods:
With document.querySelector, you can select an element based on a CSS selector:
document.querySelector('#leaveCode').value = '14'
Using the more established approach with document.getElementById(), that will, as the name of the function implies, let you select an element based on its id:
document.getElementById('leaveCode').value = '14'
You can run the below code snipped to see these methods and the jQuery function in action:
const jQueryFunction = () => {
$('#leaveCode').val('14');
}
const querySelectorFunction = () => {
document.querySelector('#leaveCode').value = '14'
}
const getElementByIdFunction = () => {
document.getElementById('leaveCode').value='14'
}
input {
display:block;
margin: 10px;
padding: 10px
}
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
<input type="button" value="$('#leaveCode').val('14');" onclick="jQueryFunction()" />
<input type="button" value="document.querySelector('#leaveCode').value = '14'" onclick="querySelectorFunction()" />
<input type="button" value="document.getElementById('leaveCode').value = '14'" onclick="getElementByIdFunction()" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
function setSelectValue (id, val) {
document.getElementById(id).value = val;
}
setSelectValue('leaveCode', 14);
Not answering the question, but you can also select by index, where i is the index of the item you wish to select:
var formObj = document.getElementById('myForm');
formObj.leaveCode[i].selected = true;
You can also loop through the items to select by display value with a loop:
for (var i = 0, len < formObj.leaveCode.length; i < len; i++)
if (formObj.leaveCode[i].value == 'xxx') formObj.leaveCode[i].selected = true;
I compared the different methods:
Comparison of the different ways on how to set a value of a select with JS or jQuery
code:
$(function() {
var oldT = new Date().getTime();
var element = document.getElementById('myId');
element.value = 4;
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId option").filter(function() {
return $(this).attr('value') == 4;
}).attr('selected', true);
console.error(new Date().getTime() - oldT);
oldT = new Date().getTime();
$("#myId").val("4");
console.error(new Date().getTime() - oldT);
});
Output on a select with ~4000 elements:
1 ms
58 ms
612 ms
With Firefox 10. Note: The only reason I did this test, was because jQuery performed super poorly on our list with ~2000 entries (they had longer texts between the options).
We had roughly 2 s delay after a val()
Note as well: I am setting value depending on the real value, not the text value.
document.getElementById('leaveCode').value = '10';
That should set the selection to "Annual Leave"
I tried the above JavaScript/jQuery-based solutions, such as:
$("#leaveCode").val("14");
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
in an AngularJS app, where there was a required <select> element.
None of them works, because the AngularJS form validation is not fired. Although the right option was selected (and is displayed in the form), the input remained invalid (ng-pristine and ng-invalid classes still present).
To force the AngularJS validation, call jQuery change() after selecting an option:
$("#leaveCode").val("14").change();
and
var leaveCode = document.querySelector('#leaveCode');
leaveCode[i].selected = true;
$(leaveCode).change();
Short
This is size improvement of William answer
leaveCode.value = '14';
leaveCode.value = '14';
<select id="leaveCode" name="leaveCode">
<option value="10">Annual Leave</option>
<option value="11">Medical Leave</option>
<option value="14">Long Service</option>
<option value="17">Leave Without Pay</option>
</select>
The easiest way if you need to:
1) Click a button which defines select option
2) Go to another page, where select option is
3) Have that option value selected on another page
1) your button links (say, on home page)
<a onclick="location.href='contact.php?option=1';" style="cursor:pointer;">Sales</a>
<a onclick="location.href='contact.php?option=2';" style="cursor:pointer;">IT</a>
(where contact.php is your page with select options. Note the page url has ?option=1 or 2)
2) put this code on your second page (my case contact.php)
<?
if (isset($_GET['option']) && $_GET['option'] != "") {
$pg = $_GET['option'];
} ?>
3) make the option value selected, depending on the button clicked
<select>
<option value="Sales" <? if ($pg == '1') { echo "selected"; } ?> >Sales</option>
<option value="IT" <? if ($pg == '2') { echo "selected"; } ?> >IT</option>
</select>
.. and so on.
So this is an easy way of passing the value to another page (with select option list) through GET in url. No forms, no IDs.. just 3 steps and it works perfect.
function foo(value)
{
var e = document.getElementById('leaveCode');
if(e) e.value = value;
}
Suppose your form is named form1:
function selectValue(val)
{
var lc = document.form1.leaveCode;
for (i=0; i<lc.length; i++)
{
if (lc.options[i].value == val)
{
lc.selectedIndex = i;
return;
}
}
}
Should be something along these lines:
function setValue(inVal){
var dl = document.getElementById('leaveCode');
var el =0;
for (var i=0; i<dl.options.length; i++){
if (dl.options[i].value == inVal){
el=i;
break;
}
}
dl.selectedIndex = el;
}
Why not add a variable for the element's Id and make it a reusable function?
function SelectElement(selectElementId, valueToSelect)
{
var element = document.getElementById(selectElementId);
element.value = valueToSelect;
}
Most of the code mentioned here didn't worked for me!
At last, this worked
window.addEventListener is important, otherwise, your JS code will run before values are fetched in the Options
window.addEventListener("load", function () {
// Selecting Element with ID - leaveCode //
var formObj = document.getElementById('leaveCode');
// Setting option as selected
let len;
for (let i = 0, len = formObj.length; i < len; i++){
if (formObj[i].value == '<value to show in Select>')
formObj.options[i].selected = true;
}
});
Hope, this helps!
You most likely want this:
$("._statusDDL").val('2');
OR
$('select').prop('selectedIndex', 3);
If using PHP you could try something like this:
$value = '11';
$first = '';
$second = '';
$third = '';
$fourth = '';
switch($value) {
case '10' :
$first = 'selected';
break;
case '11' :
$second = 'selected';
break;
case '14' :
$third = 'selected';
break;
case '17' :
$fourth = 'selected';
break;
}
echo'
<select id="leaveCode" name="leaveCode">
<option value="10" '. $first .'>Annual Leave</option>
<option value="11" '. $second .'>Medical Leave</option>
<option value="14" '. $third .'>Long Service</option>
<option value="17" '. $fourth .'>Leave Without Pay</option>
</select>';
I'm afraid I'm unable to test this at the moment, but in the past, I believe I had to give each option tag an ID, and then I did something like:
document.getElementById("optionID").select();
If that doesn't work, maybe it'll get you closer to a solution :P
I am working on a calculator tax.
I wanted to receive the selected values of that was redirected to the url value, so that I could for example send someone a link to the values that I have chosen, so it does not have to set them again only to be had when you start link.
http://kalkulator.atrocki.pl/calculator/index.html
<div class="styled-select">
<h1>Vat</h1>
<select id="vat">
<option value='0'>0%</option>
<option value='0.08'>8%</option>
<option value='0.23'>23%</option>
<option value="other">Add another VAT value..</option>
</select>
<input type="text" class="vatInput" id="vatInputId" placeholder="Vat w %">
</div>
<div class="styled-select">
<h1>tax 2</h1>
<select id="tax">
<option value="0">0%</option>
<option value='0.18'>18%</option>
<option value='0.19'>19%</option>
<option value='0.32'>32%</option>
<option value="other">Add another TAX value..</option>
</select>
JavaScript has no built in function for handling query string parameters.
It's very easy to do this with whatever back-end language you are using in your server.
If you absolutely must do this with Javascript, check this question:
How to get the value from the GET parameters?
You can parse the query string into a nice object, then look for the key value pair you want.
function parseQuery() {
var query = {};
var indexOfQ = window.location.href.indexOf("?");
if (indexOfQ < 0)
return null;
var a = window.location.href.substr(indexOfQ + 1).split('&');
for (var i = 0; i < a.length; i++) {
var b = a[i].split('=');
query[decodeURIComponent(b[0])] = decodeURIComponent(b[1] || '');
}
return query;
}
function loadQueryString() {
var query = parseQuery();
if (!query) return;
if (typeof query['val'] !== 'undefined') {
var newSelection = $("<option>", { value: query['val'], text: (Math.floor(parseFloat(query['val']) * 100)) + '%'});
$('select').prepend(newSelection);
}
}
loadQueryString();
Let's say i've got 5 selects in an html form but you can only choose options from 3 of them. I need to accomplish the following: 1. calculate a total price, 2. dynamically pass set variables (that will eventually get passed to json for PHP) equal to the name attr of the selected options.
The problem i'm having is that i'm using value ="1" on every option. Then defining the price which is updated each time they select another option by statically assigning the variable with an if else. In what i'm doing each select has many options to choose from.
Where i'm stuck:
Either i'm going to use the name attribute and pass over 5 variables (using option:selected) or there is a way to accomplish this so my database only needs 3 columns to store to the database instead of 5.
I was hoping to accomplish this in the script on the page, rather than in the PHP. Can you do this dynamically and only send over 3 variables for JSON to pass off to the php or is this just going to be easier and faster to send over 5? Yes i'm very new to javascript and jquery :)
<form id = "testform" name = "testform" method="POST" action="test.php">
<select class = "choose" id="choice1">
<option value="0" selected=""></option>
<option value="1"> Choice 1.a</option>
</select>
<select class = "choose" id="choice2">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<select class = "choose" id="choice3">
<option value="0" selected=""></option>
<option value="1"> Choice 1.c</option>
</select>
<select class = "choose" id="choice4">
<option value="0" selected=""></option>
<option value="1"> Choice 1.d</option>
</select>
<select class = "choose" id="choice5">
<option value="0" selected=""></option>
<option value="1"> Choice 1.b</option>
</select>
<label><h4>Total:$</h4> <input style="" type="number" class="num" name="amount" value="0.00" readonly="readonly" /></label>
<script type="text/javascript">
$('select').change(function(){
var form = this.form;
var sum = 0;
var price;
$('select :selected').each(function() {
sum += Number($(this).val());
});
if (sum > 3) {
alert("You can only choose 3 classes");
$('select.choose').each(function() {
$('.choose').val(0);
});
}
if (sum == 1){
price = 80;
}
else if (sum == 2) {
price = 130;
}
else if (sum == 3) {
price = 180;
}
$(".num").val(price);
form.elements['total'] = price;
});
Check how many selects have a value of something other than 0, make sure it's not more than 3, then get the name of those selects
$('select').on('change', function(){
var selected = $('select').filter(function() {
return parseInt(this.value, 10) !== 0;
}),
sum = selected.length,
price = [80, 130, 180][sum - 1],
names = selected.map(function() {
return this.id; // selects don't seem to have names ?
}).get();
if (sum > 3) {
alert("You can only choose 3 classes");
} else {
$('.num').val(price);
}
console.log(names, sum)
});
FIDDLE
<select multiple name="item" style="width: 225px;" action="post" id="mySelect" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="10">One
<option value="20">Two
<option value="30">Three
<option value="40">Four
<option value="50">Five
<option value="60">Six
</select>
<p>Total: <b><span id="selectedValue"></span></b></p>
I'm trying to get the total price displayed if multiple items are selected but it doesn't seem to be working for me. It's probably something simple but I can't get it. Any help greatly appreciated.
value property stores the last selected option's value, since you have a multiple select element, you can iterate through the selectedOptions collection of the HTMLSelectElement object:
document.getElementById('mySelect').addEventListener('change', function() {
var total = 0,
selected = this.selectedOptions,
l = selected.length;
for (var i = 0; i < l; i++) {
total += parseInt(selected[i].value, 10);
}
// ...
});
http://jsfiddle.net/qoft7mre/
onChange="document.getElementById('selectedValue').innerHTML = parseInt(document.getElementById('selectedValue').innerHTML || 0) + parseInt(this.value);"
This is not what you really want but you can sum like this.