Display option fields (child) based on parent option condition - JS solutions needed? - javascript

I am looking for a simple .js solution. I have two dropdown buttons - code:
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01">child_option_01</option>
<option value="opt02">child_option_02</option>
<option value="opt03">child_option_03</option>
<option value="opt04">child_option_04</option>
</select>
Now I need to accomplish this:
When option_01 in #parent is chosen ---> make available only child_option_01 and child_option_02 in #child dropdown
When option_02 in #parent is chosen ---> make available only child_option_03 and child_option_04 in #child dropdown
I tried some solutions I found online but so far no luck. I have a very basic .js knowledge.
Link to FIddle: http://jsfiddle.net/q5kKz/343/
Help will be appreciated.

Taking the next step with your fiddle, this will do (almost) what you want:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
}).change();
Notice the attribute selector: "option[value='opt01']" - that says "any options with value of opt01".
You should probably expand that selector to be "#child option[value='opt01']"
Using a "basic" programming method, you could do this for multiple options:
$('#parent').change(function() {
$("option[value='opt01']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
$("option[value='opt02']")[$(this).val() == "option_01" ? 'show' : 'hide']("fast");
// Adding multiple options here. This is a bad method for maintainability
}).change();
A better way to go would be to assign some sort of other attributes to the options that should show depending on which parent is selected. One example is using a class that matches the parent value desired - which would require modifying your child list like so:
<select name="child_dropdown" id="child">
<option value="opt01" class="option_01">child_option_01</option>
<option value="opt02" class="option_01">child_option_02</option>
<option value="opt03" class="option_02">child_option_03</option>
<!-- The below option would show whenever the parent is on option 2 OR 3 -->
<option value="opt04" class="option_02 option_03">child_option_04</option>
</select>
But then your script could be much more usefully constructed like so, and wouldn't need to be changed if you added / changed options:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
}).change();
This still leaves the problem of the list option hiding, and the select can still be set to a "hidden" value. This would need to be addressed somehow. Something like the below:
$('#parent').change(function() {
var val = $(this).val();
$("#child option")[$(this).hasClass(val) ? 'show' : 'hide']("fast");
var child_val = $('#child').val();
// If the selected option is not visible...
if ($('#child').find(":selected").not(":visible")) {
// Set it to the first option that has the proper parent class
$("#child").val($("#child option." + val + ":first").val());
};
}).change();

With newer versions of jQuery you could do something like:
var group1 = $("#child").find("option[value='opt01'], option[value='opt02']");
var group2 = $("#child").find("option[value='opt03'], option[value='opt04']");
$('#parent').change(function() {
var selected = $("#parent").find(":selected").text();
if (selected == "parent_option_01") {
group1.prop("disabled", false);
group2.prop("disabled", true);
} else {
group1.prop("disabled", true);
group2.prop("disabled", false);
}
}).change();

The other people may have it right. But when you want to make changes you have to change a bunch of JS code. I think this is a better approach. In our child HTML we add a data attribute to show what values of parent will make this child option show. This way if we ever need to add more elements or change what ones make the children appear we can just change the HTML and it leaves our javascript a lot cleaner.
http://jsfiddle.net/q5kKz/348/
var parent = $("#parent");
var child = $("#child");
var val;
$('#parent').change(function() {
//Get value of parent
val = $("#parent").val();
//cycle through children and find which data show matches the parent
child.children().each(function(){
var c = $(this);
//Jquery's .data wasn't working for some reason
if(c.attr("data-show") === val){
c.show()
}else{
c.hide()
}
})
}).change();
In the HTML
<select name="parent_dropdown" id="parent">
<option value="option_01">parent_option_01</option>
<option value="option_02">parent_option_02</option>
</select>
<br />
<select name="child_dropdown" id="child">
<option value="opt01" data-show="option_01">child_option_01</option>
<option value="opt02" data-show="option_01">child_option_02</option>
<option value="opt03" data-show="option_02">child_option_03</option>
<option value="opt04" data-show="option_02">child_option_04</option>
</select>

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...

How can I hide some elements from a select list?

I am new to programming and I would like to know how to hide some options from a select control I have...
I am going to explain the thing: So, i have two select controls.. according to the option from the select number 1, I want to hide some items from the second select, but I don't know how to do it, I was trying with some jQuery .hide but it is not working... Hope you can help me...
Thank you
Hope this gives you an idea, since you didn't post any code.
HTML
<select id="selectA">
<option value="">Select Fruit or Veg</option>
<option value="fruit">Fruit</option>
<option value="vegetable">Vegetable</option>
</select>
<select id="selectB">
<option value="">All</option>
<option value="apple" data-type="fruit">apple</option>
<option value="orange" data-type="fruit">orange</option>
<option value="carrot" data-type="vegetable">carrot</option>
<option value="tomato" data-type="vegetable">tomato</option>
</select>
JS
var selectA = document.querySelector('#selectA')
var selectB = document.querySelector('#selectB')
selectA.addEventListener('change', event => {
var type = event.target.value;
[].slice.call(selectB.querySelectorAll('option'))
.forEach(el => {
el.style.display = (el.dataset.type === type ? 'block' : 'none')
})
})
JSFiddle Demo: https://jsfiddle.net/hw76aLqv/1/
Try this.
if($("#APU").val("1")) {
$("#celda option[value = 'raven']").wrap('<span>')
}
To show again, just find that option(not span) and
$("#celda option[value = 'raven']").unwrap()
I hope this helps . Although the jQuery function is pretty lengthy but This way you will be able to get what is actually happening . After selecting an option from first select element , do a check whether id is 'selectA' or not .
Take the selected option as an object in the variable OPTIONS.
and then go to the next select Element using .next() function .
There use a loop which will go through all the child elements of select element .
after that I am doing a check . If the data-type of the child element is not equal to options.val() hide the child element using .hide()
Here is the code
$(document).ready(function(){
$('select').on('change',function(){
if($(this).attr('id')=='selectFirst'){
var options = $(this).find('option:selected');
var nextSelect = $('select').next();
nextSelect.children().each(function(){
child = $(this);
if(child.attr('data-type') != options.val()){
child.hide();
}
});
}
});

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 to update a div depending on the selection from dropdowns

We have two dropdowns that according to your selection it changes part of the string in some div containers. The purpose of this is to return URLs to give to clients.
This is a sample of the code
<select name="lstLanguage" id="lstLanguage">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION ID="Arabic" VALUE="AR">Arabic</OPTION>
<OPTION ID="German" VALUE="D">German</OPTION>
</select>
<select name="lstTemplate" id="lstTemplate">
<OPTION VALUE="">-- Generic default ---</OPTION>
<OPTION VALUE="1">Member</OPTION>
<OPTION VALUE="2">NonMember</OPTION>
</select>
<div id='Ind_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Ind_W_URL'>http://example.com/Registration.asp?Language_Code=?Role=</div>
<div id='Login_URL'>http://example.com/?Language_Code=</div>
And this is the jQuery we currently have, which was provided by irama.
$(function(){
divIDs = [
'Ind_URL',
'Ind_W_URL',
'Login_URL',
];
$('#lstTemplate').bind('change', function(){
role = $(this).find('option:selected').val();
updateURLDivs(langCode=null, role);
});
$('#lstLanguage').bind('change', function(){
langCode = $(this).find('option:selected').val();
updateURLDivs(langCode, role=null);
});
updateURLDivs = function (langCode, role) {
for (i in divIDs) {
currentDiv = $('#'+divIDs[i]);
if (langCode !== null) {
currentDiv.data('Language_Code', langCode);
}
if (role !== null) {
currentDiv.data('role', role);
}
// Cache original div contents, so that the select menu can be changed more than once.
if (typeof currentDiv.data('contents') == 'undefined') {
divContents = currentDiv .html();
currentDiv .data('contents', divContents);
} else {
divContents = currentDiv .data('contents');
}
currentDiv.empty().append(
divContents
.replace('role=','role='+currentDiv.data('role'))
.replace('Language_Code=','Language_Code='+currentDiv.data('Language_Code'))
);
}
}
});
This is working fine, but this morning we found a few issues
It is currently updating both parameters, no matter if you change one or both. We need it to update if you change the template, just the template and if you change the language just the language.
If nothing is selected we need it to replace it with a blank not with undefined as it is currently doing
If we change the Template it also needs to replace Registration.asp to PersonImport.asp from the URLs
This is how it should work
The div containers need to have the default URLs in them
If I change the language (lstLanguage) it should just change the Language_Code on the DIV containers. Then if I select the language option with no value ("Generic default") the Language_Code should be blank ''
If I change the template (lstTemplate) it should change the Role on the DIV containers. Also should change Registration.asp to PersonImport.asp. Then if I select the template option with no value ("Generic Default) the Role should be blank '' and PersonImport.asp should go back to Registration.asp.
I'm not a good coder on this, but it would be great if any of you can give me a hand with this.
Thanks in advance
Federico
I have create a fiddle with a lot of improvement in your code. Take a look.
Working demo

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