Remove first element, when multiple clicks on selectbox - javascript

when user chooses an option in selectbox a new box is triggered.
But supposed user changes his opinion and choose a new option, the former selectbox does not vanish.
How can I make the “wrong” selectbox – first choice – vanish.
I have a working example at codepen to illustrate the issue.
When user makes a decision with “Choose Option” he calls the hotelchecker function, so that a second selectbox appears “Option based on previous choice”. When he than reconsider his choice and choose again from “Choose option” - how can I prevent, that I have multiple second selectboxes?
Here is my HTML:
<div id="selectbox">
<select class="selectstyled" id="change">
<option value="0">Choose Option</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
</div>
Here my JS:
[let changeUse = document.getElementById("change");
changeUse.addEventListener("change", hotelchecker);
function hotelchecker() {
if (changeUse.value == 1) {
document.getElementById("selectbox").insertAdjacentHTML("afterend", `
<div id = "selectbox">
<select class = "selectstyled"
id = "changeHotel">
<option value="0">Option based on previuos choice</option>
<option value="1">Further choice 1</option>
<option value="2">Further choice 2</option>
<option value="3">Further choice 3</option>
</select>
</div>
`)
}
if (changeUse.value == 2) {
document.getElementById("selectbox").insertAdjacentHTML("afterend", `
<div id = "selectbox">
<select class = "selectstyled"
id = "changeHotel">
<option value="0">Option based on previuos choice</option>
<option value="1">Further choice 1</option>
<option value="2">Further choice 2</option>
<option value="3">Further choice 3</option>
</select>
</div>
`)
}
};][1]
I thought about running a querySelectorAll "changeHotel" and if it is >0 to remove existing element but I always get "undefined".

You need to add selectbox with unique id.
then on change event clear your selectedbox element.
try below solution.
let changeUse = document.getElementById("change");
changeUse.addEventListener("change", hotelchecker);
function hotelchecker() {
var element = document.getElementById('selectbox1');
if (typeof(element) != 'undefined' && element != null)
{
element.parentNode.removeChild(element);
}
var element2 = document.getElementById('selectbox2');
if (typeof(element2) != 'undefined' && element2 != null)
{
element2.parentNode.removeChild(element2);
}
if (changeUse.value == 1) {
document.getElementById("selectbox").insertAdjacentHTML("afterend", `
<div id = "selectbox1">
<select class = "selectstyled"
id = "changeHotel">
<option value="0">Option based on previuos choice</option>
<option value="1">Further choice 1</option>
<option value="2">Further choice 2</option>
<option value="3">Further choice 3</option>
</select>
</div>
`)
}
if (changeUse.value == 2) {
document.getElementById("selectbox").insertAdjacentHTML("afterend", `
<div id = "selectbox2">
<select class = "selectstyled"
id = "changeHotel">
<option value="0">¿En qué Hotel?</option>
<option value="4">Hotel 1 auf Granni</option>
<option value="5">Hotel 2 auf Granni</option>
<option value="6">Hotel 3 auf Granni</option>
</select>
</div>
`)
}
};
<div id="selectbox">
<select class="selectstyled" id="change">
<option value="0">Choose Option</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
</div>

Too much hardcoding, I would suggest to do it in beautiful way, create element for second option
<div id="selectbox">
<select class="selectstyled" id="change">
<option value="0">Choose Option</option>
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
<select class="selectstyled" id = "secondSelection"></select>
</div>
and script is
let changeUse = document.getElementById("change");
changeUse.addEventListener("change", hotelchecker);
const optionsSets = {
0: [],
1: [
{ value: '0', text: 'Option based on previuos choice'},
{ value: '1', text: 'Further choice 1'},
{ value: '2', text: 'Further choice 2'},
],
2: [
{ value: '0', text: '¿En qué Hotel?'},
{ value: '4', text: 'Hotel 1 auf Granni'},
{ value: '5', text: 'Hotel 2 auf Granni'},
],
}
function hotelchecker() {
const secondSelection = document.getElementById("secondSelection")
secondSelection.innerHTML =
optionsSets[changeUse.value].map(({ value, text }) =>
`<option value="${value}">${text}</option>`
).join('')
secondSelection.style.display = +changeUse.value ? 'block' : 'none'
}
hotelchecker()

Related

How to allow the selection ONLY one option for certain values in a multiple selection dropdown list?

I want to make a dropdown menu with the following options. I want be able to select a select multiple value for option A, B, and C, but disable multiple selection if option D is selected. How can I do that? Thanks.
<label>Choose an option:</label>
<select required multiple>
<option>Please select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">C</option>
</select>
Remove the other selected options if "D" is selected, otherwise allow multiple select (do nothing).
document.addEventListener("mouseup", checkMultiple);
function checkMultiple(evt) {
const selectr = evt.target.closest(`select`);
if (selectr && selectr.querySelector(`[value='D']:checked`)) {
[...selectr.options].forEach(v => v.selected = v.value === `D`);
}
}
/*
Note: the above is a shortened version of
the function in the original answer:
function checkMultiple(evt) {
if (!/option/i.test(evt.target.nodeName)) {
return true;
}
const selector = evt.target.parentNode;
const options = [...selector.querySelectorAll("option")];
if (options.find(v => v.value === "D").selected) {
options
.filter(v => v.value !== "D")
.forEach(v => v.selected = false);
}
}
*/
<label>Choose an option:</label>
<select required multiple>
<option>Please select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
</select>
let arr = [];
document.querySelector('#product_attr_ids').onchange = function(e) {
if (this.querySelectorAll('option:checked').length <= 1) {
arr = Array.apply(null, this.querySelectorAll('option:checked'));
} else {
Array.apply(null, this.querySelectorAll('option')).forEach(function(e) {
e.selected = arr.indexOf(e) > -1;
});
}
}
<p>The html of selections with multiple set to true.</p>
<p>Pressing command + click will not allow you to choose more than one option</p>
<p>Javascript. You can chnage the <strong>('option:checked').length <= 1) </strong> to whatever number you want, peraps you want your users to choose only 2 or 3 options.</p>
<label>Choose an option:</label>
<br />
<select id="product_attr_ids" required multiple>
<!-- Prevent user from select first blank option -->
<option disabled>Please select</option>
<option value="A">Attribute 1</option>
<option value="B">Attribute 2</option>
<option value="C">Attribute 3</option>
<option value="D">Attribute 4</option>
</select>

Hide select options based on previous selections

Is it possible to hide options in a select/dropdown with jQuery based on the user's selection from a previous dropdown e.g:
If user is 8 (Age Select/Dropdown), and chooses subject English (Subject Select/Dropdown) then hide Location 2 from (Locations dropdown)?
<select name="age">
<option value="8">8</div>
<option value="9">9</div>
<option value="10">10</div>
<option value="11">11</div>
</select>
<select name="subject">
<option value="eng">English</div>
<option value="maths">Maths</div>
<option value="science">Science</div>
</select>
<select name="subject">
<option value="loc-1">Location One</div>
<option value="loc-2">Location Two</div>
<option value="loc-3">Location Three</div>
</select>
Thank you!
you just need to add change function to your drop-down and according to your requirement you need to add your logic. see below example.
$(document).ready(function(){
$("#age").change(function(){
hideOption();
})
$("#subject").change(function(){
hideOption();
})
})
function hideOption(){
var age=$("#age").val();
var subject=$("#subject").val();
if(age==8 && subject=="Maths"){
$("#location [value='Location Two']").hide();
}
else{
$("#location [value='Location Two']").show();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" id='age'>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
</select>
<select name="subject" id='subject'>
<option value="English">English</option>
<option value="Maths">Maths</option>
<option value="Science">Science</option>
</select>
<select name="Location" id='location'>
<option value="Location One">Location One</option>
<option value="Location Two">Location Two</option>
<option value="Location Three">Location Three</option>
</select>
You can do something like below
$(document).on('change', '.age', function(e){
var val = $(this).val();
var subject = $('.subject').find(":selected").val();
if(val == 8 && subject == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
$(document).on('change', '.subject', function(e){
var age = $('.age').find(":selected").val();
var val = $(this).val();
if(age == 8 && val == 'English' ){
$('.location option[value="Two"]').hide();
} else {
$('.location option[value="Two"]').show();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="age" class="age">
<option >select</8>
<option value="8">8</8>
<option value="9">9</8>
<option value="10">10</8>
<option value="11">11</8>
</select>
<select name="subject" class="subject">
<option value="English">English</8>
<option value="Maths">Maths</8>
<option value="Science">Science</8>
</select>
<select name="location" class="location">
<option value="One">Location One</8>
<option value="Two">Location Two</8>
<option value="Three">Location Three</8>
</select>
With jQuery you can use .hide() and .show() to toggle element visibility. First however, you can check if the value of a select (for example age) was changed. Based on the logic you want to have, you can for example check what the value of the change was and do something if it matches a condition.
For example:
$( "#age-select" ).change(function() {
var value = $(this).val();
if(value == 8) {
$("#location-two").hide();
} else {
$("#location-two").show();
}
});
However, notice that I added an id for the "Location Two" option ("location-two") and for the age select element. Also, to make this work properly, you have to fix the values so that they're not all 8 and fix the closing tags of the elements (not ).

Change paragraph after selecting value in dropbox in js

I have a form with dropbox with a few options.
I want to change a paragraph according to the selected value in the dropbox, i.e. the selected value will replace the paragraph.
For ex. I have:
<select name="howmanyno1" size=1>
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p>number</p>`
I need the text "number" be replaced after selecting a value from the dropbox, with the value selected (2,3,4 or 5).
How should I do this?
Thanks.
<select onchange="myFunction()" name="howmanyno1" id="mySelect">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
<p id="demo">number</p>`
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>
<select name="howmanyno1" id="selectDiv" size=1 onchange="changePara()">
<option value=2 selected>2</option>
<option value=3>3</option>
<option value=4>4</option>
<option value=5>5</option>
</select>
//somewhere below
<p id="changed">number</p>
js code
function changePara(){
var val = document.getElementById("selectDiv").value;
if(val == 2){
document.getElementById("changed").innerHTML = "something";
}
else if(val == 3){
document.getElementById("changed").innerHTML = "something else";
}
// and so on
}
A jQuery based solution
Add an id to your <p> element
<p id="para">number</p>
Use jQuery to select the <select> box
let select = $('select[name="howmanyno1"]')
Create a function for updating the text in <p>
let updateText = function(e) {
$('#para').text("Selected item: " + select.val())
}
And then make the select box listen to the change event
select.on('change', updateText)
I hope this solution will be usefull
var textBlocks = new Array(
'Select from the list to change this box',
'Text block two',
'Text block three');
function changeText(elemid) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById("display").innerHTML=textBlocks[ind];
}
</head><body>
<select id="dropDown" onChange="changeText('dropDown');">
<option value="0">1</option>
<option value="1">2</option>
<option value="2">3</option>
</select><br>
<div id="display">Select from the list to change this box</div>
</body></html>

How to count the number of Form selects that have had values changes in Jquery/Javascript

I have several selects in my form. If one select has had its options changed then it should increase the counter. 5 selects then counter should be 5. Essentially I want to check if all my selects have been selected so I can submit the form. I don't want to use "required".
<div id="firstPanelID"
<div class="form-group input-group">
<label class="fixingLabelAlignmentInner">Transfer Code of Center from which Infant Transferred : </label>
<div class="fixingInputAlignmentInner">
<select id="transferCodePIW" name=transferCodePIW class="form-control" style="height:32px;width:80%;">
<option disabled selected value>SELECT</option>
<option value="13240">13240 - Mowbray Maternity Hospital</option>
<option value="14994">14994 - New Somerset Hospital</option>
<option value="16011">16011 - Tygerberg Hospital</option>
<option value="8005432">8005432 - Khayelitsha District Hospital</option>
<option value="8005433">8005433 - Michell's Plain District Hospital</option>
<option value="8005435">8005435 - Red Cross Children's Hospital</option>
<option value="97777777">97777777 - Birth at Home or in Transit</option>
<option value="">Other</option>
<option value="77777777">N/A</option>
<option value="99999999">Unknown</option>
</select>
</div>
</div>
</div>
I have tried it with the following. The selects may be visible/invisible due to other radio buttons hence the visible. The function works for radio buttons but I can't get it to work for selects.
var sgroups = [];
$('#firstPanelID select:visible:selected').each(function(index, el){
var i;
for(i = 0; i < sgroups.length; i++)
if(sgroups[i] == $(el).attr('name'))
return true;
sgroups.push($(el).attr('name'));
}
);
alert(($('#firstPanelID select:visible:selected').length))
I think the code is self-explanatory.
var counter = 0;
$('select').change(function () {
var o = $(this);
if (!o.hasClass('counted')) {
counter++;
o.addClass('counted');
}
$('#counter').text(counter);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
</select>
<select>
<option value="2aa">2aa</option>
<option value="2bb">2bb</option>
<option value="2cc">2cc</option>
</select>
<select>
<option value="3aa">3aa</option>
<option value="3bb">3bb</option>
<option value="3cc">3cc</option>
</select>
<div id="counter">
0
</div>
If you want to check if all selects have been checked, assuming each select will have an empty value, you can do this:
function isThereAnyEmptySelection () {
let r = false;
$('select').each(function () {
if ($(this).val() === '') { // or === null, or === undefined, or === '0' etc., depending on context
r = true;
}
});
return r;
}
You can use .one() to attach a single change event to each <select> element, when count is equal to $("selector").length call .off() to remove change event, then perform action, for example, submit <form> element.
let count = 0;
$("select").one("change", function() {
++count;
console.log(count);
if (count === $("select").length) {
$("select").off("change");
// submit form here
console.log(count + " is " + $("select").length)
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select>
<option value="1">1</option>
<option value="2">2</option>
</select>

Multiple select elements - Handle with jQuery when select an option from all of them

I have two select elements with some options. What I want to do is to handle this with jquery so as I can get the values of them only when options have values.
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
If I want to handle with one select element only I use .on('change', function() with select element and it works, but with multiple select element how can I do it.
You should check if selectedIndex is not 0 for all your select elements.
$(document).on('change', 'select', function () {
var allChanged = true;
// check if there is any other select element which was not changed
$('select').each(function () {
if (this.selectedIndex == 0) {
allChanged = false;
}
});
// if all select elements have been changed
if (allChanged) {
alert('BOTH CHANGED');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-heading">
<select id="loading-by-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
<select id="loading-by-sub-tag">
<option value="" disabled selected> -- Select Subject --</option>
<option value="value1">Selection 1</option>
<option value="value2">Selection 2</option>
</select>
</div>
Just a side note, use .filter() :
$('select').change(function() {
var m = $(this).siblings('select').addBack();
var n = m.filter(function(){
return $(this).val() == null && $(this)
});
if ( !n.length ) alert('both selected')
});
DEMO

Categories

Resources