Removing and adding options from a group of select menus with jQuery - javascript

This is a little more complicated than the title makes it out to be, but here are the essential business rules:
There are three select menus on the
page, each filled with the same
options and values.
There will always be three select
menus.
There will always be the same number
of options/values in each select
menu.
Selecting a question in any of the
menus will remove that question as an option from
the other two menus.
Re-selecting a different question
from any of the menus will bring
back the question that was
previously removed from the other
two menus at the index it was at previously.
I've tried this a few different ways, and the thing that is killing me is number 5. I know that it wouldn't be inserted at the exact index because some questions may have already been removed, which would reorder the index. It basically needs an insertBefore or insertAfter that puts it in the same "slot".
Even if you don't post any code, some thoughts on how you might approach this would be extremely helpful. The select menus and jQuery look something like this, but I've had numerous tries at it in different variations:
jQuery:
$(function() {
$(".questions").change(function() {
var t = this;
var s = $(t).find(":selected");
// Remove, but no "insert previously selected" yet...
$(".questions").each(function(i) {
if (t != this) {
$(this).find("option[value=" + s.val() + "]").remove();
}
});
});
});
HTML:
<select name="select1" class="questions">
<option value="1">Please select an option...</option>
<option value="2">What is your favorite color?</option>
<option value="3">What is your pet's name?</option>
<option value="4">How old are you?</option>
</select>
<select name="select2" class="questions">
<option value="1">Please select an option...</option>
<option value="2">What is your favorite color?</option>
<option value="3">What is your pet's name?</option>
<option value="4">How old are you?</option>
</select>
<select name="select3" class="questions">
<option value="1">Please select an option...</option>
<option value="2">What is your favorite color?</option>
<option value="3">What is your pet's name?</option>
<option value="4">How old are you?</option>
</select>

Don't remove the elements, hide them. With removing, you are causing you a lot more problems than necessary. This works for me:
$(function() {
$('select.questions').change(function() {
var hidden = [];
// Get the values that should be hidden
$('select.questions').each(function() {
var val = $(this).find('option:selected').val();
if(val > 0) {
hidden.push($(this).find('option:selected').val());
}
});
// Show all options...
$('select.questions option').show().removeAttr('disabled');
// ...and hide those that should be invisible
for(var i in hidden) {
// Note the not(':selected'); we don't want to hide the option from where
// it's active. The hidden option should also be disabled to prevent it
// from submitting accidentally (just in case).
$('select.questions option[value='+hidden[i]+']')
.not(':selected')
.hide()
.attr('disabled', 'disabled');
}
});
});
I made a small change to your HTML also, I denoted an option that should always be visible with a value of 0. So the valid options go from 1 to 3.
Here's a working example, tell me if I misunderstood you:
http://www.ulmanen.fi/stuff/selecthide.php

I was working on a solution of this recently and modified this code to remove rather than disable/hide. For my solution it was required (I'm also using UI to style the select elements). Here's how I did it:
// Copy an existing select element
var cloned = $('select[name="select1"]').clone();
// Each time someone changes a select
$('select.questions').live('change',function() {
// Get the current values, then reset the selects to their original state
var hidden[];
$('select.questions').each(function() {
hidden.push($(this).val());
$(this).html(cloned.html());
});
// Look through the selects
for (var i in hidden) {
$('select.questions').each(function() {
// If this is not the current select
if ((parseInt(i)) != $(this).parent().index()) {
// Remove the ones that were selected elsewhere
$(this).find('option[value="'+hidden[i]+'"]').not('option[value="0"]').remove();
} else {
// Otherwise, just select the right one
$(this).find('option[value="'+hidden[i]+'"]').not('option[value="0"]').attr('selected','selected');
}
});
}
});

Related

When registering both onchange and onclick on a select, the click event is triggered twice

Goal: Have a select whose option have nested structure when user clicks on the select, but when user selects an option the option should be displayed "normally" (ie with no leading spaces).
Attempted solution using JS and Jquery: My JS is far from sophisticated so I apologize in advance :)
I attempted to use .on("change") and .on("click") to change the selected option value (by calling .trim() since I achieve the "nested" structure with ). I'm also storing the original value of the selected option because I want to revert the select menu to its original structure in case the user selects another option.
The problem: The function registered for .on("click") is called twice, thus the select value immediately resets itself to its original value.
I suspect there is a much, much easier solution using CSS. I will be happy to accept an answer that will suggest such solution.
JSFiddle: https://jsfiddle.net/dv6kky43/9/
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
<textarea id="output"/>
var orig;
var output = $("#output");
output.val("");
function onDeviceSelection(event){
output.val(output.val() + "\nonDeviceSelection");
var select = event.target;
orig = select.selectedOptions[0].text;
select.selectedOptions[0].text = select.selectedOptions[0].text.trim()
}
function resetDeviceSelectionText(event) {
output.val(output.val() + "\nresetDeviceSelectionText");
var select = event.target;
if (orig !== undefined){
select.selectedOptions[0].text = orig;
}
}
$("#select").on("change", onDeviceSelection);
$("#select").on("click", resetDeviceSelectionText);
If you are already using jQuery, why not utilize data function to store the original value. This way you will also be able to specify different nest levels.
(function($){
$(document).on('change', 'select', function(event) {
$(this).find('option').each(function(index, element){
var $option = $(element);
// Storing original value in html5 friendly custom attribute.
if(!$option.data('originalValue')) {
$option.data('originalValue', $option.text());
}
if($option.is(':selected')) {
$option.html($option.data('originalValue').trim());
} else {
$option.html($option.data('originalValue'));
}
})
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select id="select">
<option value=""></option>
<option value="a"> a</option>
<option value="b"> b</option>
</select>
</form>
Once caveat I see is, the selected option will appear trimmed on the list as well, if dropdown is opened after a previous selection has been made:
Will it still work for you?
Instead of keeping the state of the selected element i would simply go over all options and add the space if that option is not selected:
function onDeviceSelection(event){
// Update textarea
output.val(output.val() + "\nonDeviceSelection");
// Higlight the selected
const {options, selectedIndex} = event.target;
for(let i = 0; i < options.length; i++)
options[i].innerHTML = (i === selectedIndex ? "":" ") + options[i].text.trim();
}
$("#select").on("change", onDeviceSelection);
Note that you need to use innerHTML to set the whitespace...

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

jQuery - Each loop to select all items by data attribute, but also dependent on select (option) values

I am in the process of building an e-Commerce shop and have hit a small bump in the road for my actual product page. Based on any product options set that would add to the price if selected, I would like to be able to update the price on the page live when these options have been added. I have managed to iterate through every element with a "data-price-effect" attribute attached to them, HOWEVER, when it comes to a select element, I would need to check if the item is selected as an option, each option has their respective price change attribute of course, but the value would only update to the actual select element.
Here is my code upto now:
function updatePrice(){
$('[data-price-effect]').each(function( index ) {
// do something
});
}
Basic HTML set-up to explain further:
<form>
<input type="text" name="foo" onchange="updatePrice();" data-price-effect="10.00" />
<select name="bar" onchange="updatePrice();">
<option selected value="Item1" data-price-effect="5.00">Item 1</option>
<option selected value="Item2" data-price-effect="8.00">Item 2</option>
<option selected value="Item3" data-price-effect="10.00">Item 3</option>
</select>
</form>
I have NO idea how to even logically do this, not even with some huge messy code. Any pointers here from someone more experienced with Javascript?
Instead of having "updatePrice()" on each element, you could have a listener for all form elements for the function:
var EffectElements = $('form input[data-price-effect], form select');
EffectElements.on('change', function() {
var PriceEffect = 0;
EffectElements.each(function() { // Loop through elements
if ($(this).is('select')) { //if this element is a select
$(this).children().each(function() { //Loop through the child elements (options)
if ($(this).is(':selected')) { //if this option is selected
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
} else {
PriceEffect += parseFloat($(this).attr('data-price-effect'));
}
});
});
You could then use the PriceEffect variable to update your price on the website.
Ultimately it's the IS function doing the dirty work you needed ~_o
Working Example

Mutual exclusion for <option>s in a <select>?

I need to combine the functionality of single selection and multiple select into a single control. Specifically, I have a number of options. The first one is mutually exclusive to the others. So, if I select the first one, it needs to uncheck all the others. If one of the others is selected, it must uncheck the first one (if selected). The other options should have no effect on each other.
<select id="myGroup" data-native-menu="false" multiple="multiple" >
<option value="" >Select Group(s)</option>
<option value="-1" selected="selected" >I am alone</option>
<option value="1" >I am not alone 1</option>
<option value="2" >I am not alone 2</option>
<option value="3" >I am not alone 3</option>
</select>
I installed an onchange() handler. So, I know when selections are made. But I can't seem to tell which option just got selected. So, in the example above, if the user select option 3, $(this).val() becomes -1,3. How can I tell that is was "3" that just got selected?
The only thing that I've come up with so far is to keep an array of selected options and then diff the arrays when a new option is selected.
$('select[id=myGroup]').change(function() {
// At this point, I know the sum total of what's been selectec.
// But I don't know which one just got added to the list.
// I want logic that says:
// if -1 just got added, then unselect all the others
// if something else was just added, make sure that -1 is not selected
var selected = $(this).val();
alert(JSON.stringify(selected));
});
Is there a better way?
You only need to keep state for the first option, not all of them:
var firstOption = $("#myGroup > option[value=-1]");
var firstSelectedBefore = firstOption.prop("selected");
$("#myGroup").on("change", function(event) {
if (firstOption.prop("selected") && this.selectedOptions.length > 1) {
if (firstSelectedBefore) { // non-first option just selected
firstOption.prop("selected", false);
} else { // first option just selected
$(this).find("option:not([value=-1])").prop("selected", false);
}
}
firstSelectedBefore = firstOption.prop("selected");
});

Showing and hiding <option> with jquery

I have three selects (html drop down lists), all contain the exact same values (except the ids of selects are different).
Now I want to do this:
When a user selects some option in the first select the same option is hidden in the other two. This rule applies to other two selects as well.
If the option in the second select is changed again then the previously selected option must reappear in the other selects.
I hope I was clear. I know this should probably be solved with javascript but I don't have enough knowledge of it to write an elegant solution (mine would probably be very long). Can you help me with the this?
$('#selectboxid').hide();
is the simplest way
http://api.jquery.com/hide/
try toggle it it matches your requirement
http://api.jquery.com/toggle/
you can call these onchange of the select box
if you want to hide individual options
use .addClass and add class to that option to hide it
http://api.jquery.com/addClass/
Little late the party, but here's a full working solution:
HTML:
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
JavaScript:
$(document).ready(function() {
$("select").change(function() {
var $this = $(this);
var selected = this.options[this.selectedIndex].value;
var index = $this.index();
$("select").each(function() {
var $this2 = $(this);
if($this2.index() != index) {
$(this.options).show();
var $op = $this2.children("option:[value='" + selected + "']");
$op.hide();
if($this2.val() == selected) {
if($op.index() + 1 == $ops.length) {
$this2.val($ops.eq(0).val());
}
else {
$this2.val($ops.eq($op.index() + 1).val());
}
}
}
});
});
});
Also demonstrated here: http://jsfiddle.net/thomas4g/u2sbd/21/

Categories

Resources