change available html select options - javascript

I am looking for a javascript solution to change the available html select options. I have a javascript function being triggered at the right point, but I can't figure out how to change the available options. For example, if option A is selected in htmlselect1, I want the options in htmlselect2 to be updated. Thanks.
What I have seems to almost be working, but it has empty selections in the select options as well. This is the javascript function.
function setDurationChoices(){
var selectedType= hikeTypeID.value;
if(selectedType=== "G"){
document.inputForm.duration.options = new Option("3", "5", true);
}
else if(selectedType=== "H"){
document.inputForm.duration.options = new Option("2", "3", "4", true);
}
else if(selectedType=== "B"){
document.inputForm.duration.options = new Option("5", "7", true);
}
}
Here is where it is triggered:
<select id="hikeTypeID" name="hikeType" onchange="setDurationChoices()">
<option value="G">G</option>
<option value="H">H/option>
<option value="B">B</option>
</select>
Here is the select that I want to dynamically change:
<select name="duration">
<option value="3">3</option>
<option value="5">5</option>
</select>

The optional parameters for Option are the following
new Option([text[, value[, defaultSelected[, selected]]]])
text (required) - value shown on page
value - the value
defaultSelected - [true/false] - this is equivilavnt of adding the
selected attribute to the element on the html tag. So if you reset a
form, the value would remain selected.
selected - [true/false] - selects the value when option is set to true
This creates just a single option element like
<option value="G">G</option>
To add a option to say hikeTypeId, the code can be like
document.getElementById('hikeTypeId').options.add(new Option("g","g",false,false));
to flush all previous and add new, it can be done using [add(element[,index])] and remove(index)
while(document.getElementById('hikeTypeId').options.length)
document.getElementById('hikeTypeId').options.remove(0);
document.getElementById('hikeTypeId').options.add(new Option("g","g",false,false), 0);
document.getElementById('hikeTypeId').options.add(new Option("h","h",false,false), 1);
document.getElementById('hikeTypeId').options.add(new Option("i","i",false,true), 2);
You can as well use document.createElement('option') and set the attributes accordingly, if this is confusing.
var option = document.createElement('option');
option.text = text;
option.value = value;
option.selected = true;

Related

I need to set a select to selected using data-val

I have a select I need to set to selected but the select is using a name and the options are using "data-val" and I can't change either:
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 2</option>
</select>
How can I set Option 2 to selected using JavaScript?
A couple ways that you could go about this;
You could be very explicit and set the value of the <select /> itself through;
document.querySelector('[name="properties[Liner]"]').value = "Option 2";
Or you could be a little bit more dynamic with the following;
document.querySelector('[name="properties[Liner]"]').value = document.querySelector('[data-val="2"]').value;
For the targeting of the name, you'll want to use [name="{some name}"]
For the targeting of a data-attribute, you'll want to use [data-val="{some value}"]
In this scenario, you could just specify "name" for querySelector and you'll get what you want because there's only one element with a name on the page (at least in your mini-scenario).
Code explanation in comments
(function(){
const selectEle = document.querySelector('[name="properties[Liner]"]'); // query the select the element
const setSelected = 2; // set the default value
const options = selectEle.querySelectorAll('option'); // query all the option element
options.forEach((option)=>{
const value = option.getAttribute('data-val'); // get the attribute data-val
if(value == setSelected){ // if matches
option.setAttribute('selected', true); // set selected
}
});
})();
<select name="properties[Liner]">
<option data-val="1">Option 1</option>
<option data-val="2">Option 2</option>
<option data-val="3">Option 3</option>
</select>

display a part of value in select option

I have a select drop-down with country and code. In drop-down option, for user experience and understanding i am displaying name of the country along with country code.
As a normal functionality when a user selects any value from the drop-down that value gets displayed inside the input like this
however i want that only the country code should get displayed like this
Part of my code
<select name="countrycode" class="form-control pf-country" id="countrycode">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The entire code is available here
Can anyone please suggest how to do it.
As per my understanding, You can try this one. As this example providing exact output as you mentioned in your questions.
https://silviomoreto.github.io/bootstrap-select/examples/#selected-text
Basically we're trying to change innerText of selected-option. It can be achieved easily by adding onchange event listener to the select tag.
But there's a little problem, on changing innerText we lose previous value of innerText, solution by #KKK solves problem but leaves this little thing.
Following code handles problem in complete ways. We're adding data-innerText atribute with previous value of innerText and also id="previous" to identify it. Please check this demo.
function simpleTweak(select){
var previouslySelectedTag = document.getElementById('previous');
if(previouslySelectedTag!=undefined){
previouslySelectedTag.innerText = previouslySelectedTag.getAttribute('data-innerText');
previouslySelectedTag.setAttribute('id','');
}
var innerText = select.options[select.selectedIndex].innerText;
select.options[select.selectedIndex].setAttribute('data-innerText',innerText);
select.options[select.selectedIndex].setAttribute('id','previous');
var value="(+"+select.options[select.selectedIndex].value+")";
select.options[select.selectedIndex].innerText = value;
}
As I understood, you need to change the display text after selecting the option, is it? If so, you can do it like this.
You can set the selected index's text in onchange event. But it will reset the text in the option when you click the dropdown again. You may need to change it back if you prefer.
function displayCountryCode() {
var countrycode = document.getElementById("countrycode");
countrycode.options[countrycode.selectedIndex].text = '+' + countrycode.value;
}
<select name="countrycode" class="form-control pf-country" id="countrycode" onchange="displayCountryCode()">
<option data-countryCode="IN" value="91">Code</option>
<option data-countryCode="IN" value="91">India (+91)</option>
<option data-countryCode="US" value="1">USA (+1)</option>
<optgroup label="Other countries">
<option data-countryCode="DZ" value="213">Algeria (+213)</option>
<option data-countryCode="AD" value="376">Andorra (+376)</option>
</optgroup>
</select>
The following JavaScript code will change the text of the selected option when you select it and change it back when you select a different one.
It does this by saving the values of the country name and country number as HTML5 data attributes (option.dataset.countryName & option.dataset.countryNumber)
Doing it this way, you don't have to change the format of the HTML from what you provided in your post.
I used vanilla JavaScript, so it'll work with or without jQuery.
window.addEventListener('load', () => {
let select = document.getElementsByName('countrycode')[0]
let options = document.getElementsByTagName('option')
for (let i = 1; i < options.length; i++) {
let option = options[i]
let matches = option.innerText.match(/(.*?) (\(\+\d+\))/)
option.dataset.countryName = matches[1]
option.dataset.countryNumber = matches[2]
// Set the value in the collection again now that the object has been changed
options[i] = option
}
select.addEventListener('change', () => {
for (let i = 1; i < options.length; i++) {
let option = options[i];
option.innerText = option.dataset.countryName + ' '
option.innerText += option.dataset.countryNumber
}
let option = document.querySelector('option:checked')
if (option !== options[0]) {
option.innerText = option.dataset.countryNumber
}
})
})
There's also a demo at CodePen

make a select dependent with js

I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach

Javascript Div onchange Grab Values from Two Select Boxes

I'm trying to make it so when a select box within a div changes, it will grab values from both that select box and one other one that I've yet to add, but I don't know how to go about it.
I currently have this code
<select id='selMag' onchange='getSelMag(this)'>
<option value='0.0>Select Minimum Magnitude</option>
<option value='1.0'>1.0</option>
<option value='2.0'>2.0</option>
<option value='3.0'>3.0</option>
<option value='4.0'>4.0</option>
<option value='5.0'>5.0</option>
<option value='6.0'>6.0</option>
<option value='7.0'>7.0</option>
<option value='8.0'>8.0</option>
<option value='9.0'>9.0</option>
<option value='10.0'>10.0</option>
</select>
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
}
This, as it is right now, works fine from grabbing it from the , but I would like to add another one and put them inside a container div, and make it so when either one changes it will grab the values from both of them, add both strings together, and convert them into a number. I plan to make it so the select box above will not have the decimal values and just be 1, 2, etc. and have the second box be .1, .2, etc. so when they are added together, it will show 1.1, 1.2, etc.
Presumably, the select is in a form. To be successful, form controls must have a name, so:
<select id='selMag' name='selMag' onchange='getSelMag(this)'>
Adding a name nearly always obviates the requirement for an ID. If the other select also has a name:
<select name='selMag2'>
and it belongs to the same form as the first, you can reference it from the getSelMag function via the form:
function getSelMag(sel) {
// Always declare variables
var value = Number(sel.value);
// Access them from the appropriate scope
console.log(value);
// Reference the other select using named properties of the form
var otherSelect = sel.form.selMag2;
// Do stuff with it
var otherValue = otherSelect.value;
}
Note that all form controls have a form property that references their parent form, and that the controls belonging to a form can be accessed via the form's elements collection.
Those with names (and in some browsers those with IDs) can be accessed as named properties of the form and of the elements collection, and also by index in the collection.
It seems that you want to concatenate the values with a period between, so the function might look like:
function getSelMag(sel) {
var value0 = sel.form.selMag.value;
var value1 = sel.form.selMag2.value;
console.log(value0 + '.' + value1);
}
and the HTML:
<form>
<select name="selMag" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
<select name="selMag2" onchange="getSelMag(this);">
<option value="0" selected>0
<option value="1">1
<option value="2">2
</select>
</form>
Use the answer from this link to get the value of other select box in getSelMag() function
Get selected value in dropdown list using JavaScript?
as follows:
function getSelMag(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag2");
var option2 = e.options[e.selectedIndex].text;
//do whatever u want
}
You can make another function say x() that will be called for other select box you make and access the value of first select box from that
<select id='selMag2' onchange='x(this)'>
as
function getSelMag2(sel) {
value = Number(sel.value);
console.log(window.value);
var e = document.getElementById("selMag");
var option1 = e.options[e.selectedIndex].text;
//do whatever u want
}
Hope this helps

jQuery - Set the selected option of a select box using value or text with options nested in optgroups

So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.

Categories

Resources