enable or disable option from select - javascript

I am trying to make an option either selectable OR non-selectable based on whether or not they chose another option. For example, if there is options 1-6 and they have NOT chosen option 1 in their first select box, then in that SAME select box and any other in the form, then option 6 could NOT be chosen.
I looked around, but everything is about clicking a button to achieve this.
This is the code I have (I have also tried onclick)
<script type="text/javascript">
function makeDisable(){
var x=document.getElementById("mySelect2");
x.disabled=true
}
function makeEnable(){
var x=document.getElementById("mySelect2");
x.disabled=false
}</script>
<form>
<select class="mySelect" id="mySelect">
<option onchange="makeEnable()" value="Enable list">Apple</option>
<option onchange="makeDisable()" value="Disable list">Banana</option>
<option id="mySelect2" disabled="true">Orange</option>
</select>
</form>

Option elements don't have event "onchange", but Select elements do.
I've quickly wrote a code snippet below. You may add more select items. When you choose an option in one of those select elements, you shouldn't choose options at same index in other select elements.
function toggleDisability(selectElement) {
//Getting all select elements
var arraySelects = document.getElementsByClassName('mySelect');
//Getting selected index
var selectedOption = selectElement.selectedIndex;
//Disabling options at same index in other select elements
for (var i = 0; i < arraySelects.length; i++) {
if (arraySelects[i] == selectElement)
continue; //Passing the selected Select Element
arraySelects[i].options[selectedOption].disabled = true;
}
}
<form>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect1">
<option>Apple</option>
<option>Banana</option>
<option>Orange</option>
</select>
<select onchange="toggleDisability(this);" class="mySelect" id="mySelect2">
<option>Hamburger</option>
<option>Pizza</option>
<option>Cola</option>
</select>
</form>

Related

How do you properly "reset" a <select> element that supports multiple options in regular JS?

I want to be able to reset <select> tags by themselves instead of making them reset with the entire form. This is what I have so far:
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
And the JS:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
selectedOptions[i].selected = false;
}
}
When I first tried this, it seemed to work. However, only when one option is selected. I've noticed that when there is more than one option currently selected, it seems to break.
Starting with three options, and clicking the Reset button results in this, for some reason:
Every option gets deselected apart from one. Why does this happen?
Clicking the Reset button again deselects the one still selected option though.
You can set the selectedIndex attribute to -1 to indicate that no element is selected.
function resetS() {
const multipleSelect = document.getElementById('s');
multipleSelect.selectedIndex = -1;
}
<form autocomplete="off">
<select id="s" name="select" multiple>
<option disabled>Select a value!</option>
<option value="one">1</option>
<option value="two">2</option>
<option value="three">3</option>
</select>
<button onclick="resetS()" type="button">Reset</button>
</form>
The list of selected <option> elements is a "live" list. When you change the selected flag on one of the elements, the list changes; that is, the <option> you changed disappears from the list, so the length gets 1 shorter. An indexed for loop will therefore skip elements.
The way to deal with that (well, one way) is to use a while loop as follows:
function resetS() {
const selectedOptions = document.getElementById('s').selectedOptions;
while (selectedOptions.length) {
selectedOptions[0].selected = false;
}
}
edit — or you could use the method suggested in Tom's answer, which is simpler.

How to reset default value in an select based on previous select tag?

I have two select options :
<select id="Living things">
<option>Choose Any</option>
<option>Animals</option>
<option>Plants</option>
</select>
<select id="Compare">
<option>Any</option>
<option>less</option>
<option>greater</option>
</select>
Consider the first options from both the drop downs are default. Now imagine I selected 'Animals' from first and 'less' from second. Now if I change the first to 'Plants' then the second list should be reset.i.e,
<option>Any</option>
<option>less</option>
<option>greater</option>
Please help in this.Thank You.
<select id="livingThings" onchange="reset();">
<option>Choose Any</option>
<option>Animals</option>
<option>Plants</option>
</select>
<select id="compare">
<option>Any</option>
<option>less</option>
<option>greater</option>
</select>
<script src="test.js"></script>
livingThings = document.getElementById('livingThings');
compare =document.getElementById('compare');
function reset(){
if (livingThings.selectedIndex != 0){
compare.selectedIndex = 0;
}
}
You can add an event listener for the first select element whenver it changes then reset the value of the second select element to its default, note that IDs can not have white spaces, I have added a dash to it
document.querySelector("#Living-things").onchange = function() {
let select = document.querySelector("#Compare");
select.value = select.children[0].value;
}
<select id="Living-things">
<option>Choose Any</option>
<option>Animals</option>
<option>Plants</option>
</select>
<select id="Compare">
<option>Any</option>
<option>less</option>
<option>greater</option>
</select>

Generate text on a webpage which depends on dropdown box options

I have created a dropdown box with 3 options on my website.
I want to change some text on the webpage, depending on the drop-down item selected. For example:
If dropdown option 1 is chosen, I would like some text on the page that says "You have chosen option 1".
I don't know any JavaScript and so I haven't tried anything apart from trying to search for a similar solution.
<select name="os0" style="background: #315d80; color: #fff; border-color: white; border: 0px;">
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
<option value="op3">Option 3</option>
</select>
Full sultion with jQuery (I started typing it before you added the HTML to your question so the options are italian car brands).
https://jsfiddle.net/mL2c2xb6/
HTML:
<select id="carSelect">
<option></option>
<option value="Audi">Audi</option>
<option value="Ferrari">Ferrari</option>
<option value="Fiat">Fiat</option>
</select>
<p id="choiceDisplay">
Selection Display
</p>
Javascript:
$('select').change(function(){ // Listen to changes to <select> element
const options = $("option"); // Get all the <option> elements.
let selectedOption = ""; // Var to store selected option value.
options.each(function(index){ // Iterate through option elements.
let option = options[index];
if($(option).prop("selected")) { // Find the seletced one.
selectedOption = $(option).val(); // Get the value and store it
};
});
$("#choiceDisplay")
.empty()
.append(selectedOption); // Display the result.
});
var e = document.querySelector('[name="os0"]');
var strUser = "";
e.addEventListener("change", function(){
strUser = e.options[e.selectedIndex].innerHTML;
alert("You have chosen " + strUser);
});

Button to add selected="selected" from outside form

I am using laravel, and trying to integrate some jquery, which I am not very good at.
I have a multiple select box with potentially lots of options, based on database values.
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
The user can select tools directly from the select box, but this can be a huge list and therefore I am also displaying a search field below the select box to
search the database of tools so the user can see more info about the tool, and then decide if he wants to include it.
Currently the user has to first search, then find the entry in the select box and select it.
I want a faster solution with a button next to the info about the tool, that automatically adds selected="selected" to the correct option in the select box above.
I tried
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$("div.toolselect select").val(id);
}
But that erased all the other other selected fields.
Any ideas would be appreciated.
Try using jQuery's prop function:
<input type="button" value="Mer" onclick="addselect('{{$tool->id}}')"/>
<script type="text/javascript">
addselect = function (id){
$('.toolselect select option[value="'+ id +'"]').prop('selected');
}
</script>
For a multi-select, the value is an array of all the selected items. You're just setting the value to a single item, which is treated as an array of one element, so all the other selections get discarded.
So you should get the old value, add the new ID to it, and then set that as the new value.
function addselect(id) {
$('.toolselect select').val(function(i, oldval) {
oldval = oldval || []; // oldval = null when nothing is selected
oldval.push(id);
return oldval;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="toolselect">
<select multiple>
<option value="1">Tool 1</option>
<option value="2">Tool 2</option>
<option value="3">Tool 3</option>
</select>
</div>
<input type="button" value="Select 1" onclick="addselect('1')"/>
<input type="button" value="Select 2" onclick="addselect('2')"/>
<input type="button" value="Select 3" onclick="addselect('3')"/>
Instead of using this :
addselect = function (id){
$("div.toolselect select").val(id);
}
Try this :
addselect = function(id) {
var temp = [];
var arr = $('select').val();
for(i=0;i<arr.length;i++){
temp.push(arr[i]);
}
temp.push(id);
$("div.toolselect select").val(temp);
}
This way your previous selection is preserved, and the new selection is appended to the previous selection.
Hope this helps.

How to link two dynamically populated select boxes?

I have two dynamically populated selectboxes with data coming from same json object within the page. What I want to achieve is to link the two boxes so that whenever there is a change in one select box the same option in other select box gets automatically disabled.
So suppose Xiomi and the corresponding second value Xiomi Redme is selected in first selectboxes then the same option Xiomi Redme should not be available for selection in the other select box
<div>
<select id="brand-select" name="Brand">
<option value=''>Select Brand</option>
<option value='300'>Xiomi</option>
<option value='147'>HTC</option>
</select>
</div>
<div>
<select id='mobile_model_select' name='Mobile_Brand_Models' style='width:208px;'></select>
</div>
<div>
<select id="brand-select_product2" name="Brand">
<option value=''>Select Brand</option>
<option value='300'>Xiomi</option>
<option value='147'>HTC</option>
</select>
</div>
<div>
<select id='mobile_model_select_product2' name='Mobile_Brand_Models_For_Product2' style='width:208px;'></select>
</div>
Here is my jquery code
$(document).ready(function(){
var modelData = {
"300":{
"MI3_16GB":"XIAOMI Mi3 (16GB)",
"REDMI_NOTE":"XIAOMI REDMI NOTE",
"REDMI":"XIAOMI Redmi ",
"REDMI_1S":"XIAOMI REDMI 1S"
},
"147":{
"ONE_M8":"HTC One (M8)",
"DESIRE_610":"HTC Desire 610",
"ONE_E8":"HTC ONE E8"
}
};
$('#brand_select').change(function(){
correspondingId = $(this).find(":selected").val();
var correspondingIdObject = modelData[correspondingId];
$('#mobile_model_select option').remove();
$.each(correspondingIdObject, function(key, value){
$('#mobile_model_select').append($("<option>").text(value).attr('value',key));
});
$('#brand_select_product2').change(function(){ //
correspondingSelectedIdObject = $(this).find(":selected").val();
$('#mobile_model_select_product2 option').remove();
$.each(correspondingSelectedIdObject, function(key, value){
$('#mobile_model_select_product2').append($("<option>").text(value).attr('value',key));
});
});
My problem is how to link the two onchange functions so that whenever the value is changed in one the same option in the other select box is disabled.
for (var i=0; i<selects.length; i++) {
$(selects[i]).find('option').removeAttr('disabled');
for (var j=0; j<vals.length; j++) {
$(selects[i]).find('option[value='+vals[j]+']').attr('disabled', 'disabled');
}
}
have a look at this fiddle .. hope this helps u ...
JSFiddle
credits : #Skwal

Categories