jQuery select option hide not working on mobile - javascript

My cascading dropdown works fine, exactly how I want it to on a desktop device, however on mobile, the second option of the dropdown lets me choose any option, even those only meant for a different first dropdown input. Is there any way to fix this? I included a picture of what I am talking about and a link to my code.
html
<select name="category" id='dropdown1'>
<option value="0" rel='start'>Select Model</option>
<option value="1" rel="GFS">GFS</option>
<option value="2" rel="NAM">NAM</option>
</select>
<select name="items" class="cascade", id="imgList" style='display:none'>
<option value="" class='NAM'>Please select a timeframe</option>
<option value="" class='GFS'>Please select a timeframe</option>
<option value='.png' class="GFS">1-Day</option>
<option value='.png' class="GFS">5-Days</option>
<option value='.png' class="NAM">1-Day</option>
</select>
js
$('#dropdown1').change(function() {
$('#imgList').css('display','block');
});
$(document).ready(function(){
var $cat = $('select[name=category]'),
$category = $('select[name=items]');
$cat.change(function(){
var $this = $(this).find(':selected'),
rel = $this.attr('rel');
// Hide all
$category.find("option").hide();
// Find all matching accessories
// Show all the correct accesories
// Select the first accesory
$set = $category.find('option.' + rel);
$set.show().first().prop('selected', true);
});
});
function setClass() {
var img = document.getElementById("image");
img.src = this.value;
return false;
}
document.getElementById("imgList").onchange = setClass;
https://jsfiddle.net/7t5rLa3h/

Looks like hiding the option (display:none) on mobile browsers doesn't work. But you can disable and enable them like options.attr('disable', true).
Alternatively, you can save a set of options in a variable and filter and re-populate the select later.
$(document).ready(function() {
var $cat = $('select[name=category]'),
$category = $('select[name=items]'),
$options = $('select[name=items] option');
$cat.change(function() {
var $this = $(this).find(':selected'),
rel = $this.attr('rel'),
$set = $options.filter('[data-category=' + rel + ']');
$category.html($set)
$set.show().first().prop('selected', true);
});
});
$('#dropdown1').change(function() {
$('#imgList').css('display', 'block');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Choose Model and Timeframe</h1>
<h2>
<select name="category" id='dropdown1'>
<option value="0" rel='start'>Select Model</option>
<option value="1" rel="GFS">GFS</option>
<option value="2" rel="NAM">NAM</option>
</select>
<select name="items" class="cascade", id="imgList" style='display:none'>
<option value="" data-category='NAM'>Please select a timeframe</option>
<option value="" data-category='GFS'>Please select a timeframe</option>
<option value='Model_Data/GFS/meteogram/trends/images/NYC/gfs_1day_temp.png' data-category="GFS">1-Day</option>
<option value='Model_Data/GFS/meteogram/trends/images/NYC/gfs_5day_temp.png' data-category="GFS">5-Days</option>
<option value='Model_Data/NAM/meteogram/images/1_day/NYC/nam_1day_temp.png' data-category="NAM">1-Day</option>

Related

How to make select required upon parent option selected with JavaScript or jQuery

I'm trying to make subcategory required only upon PDF option selected from the category select.
I have tried this JavaScript but its not working.
function getVal(ele){
var element = document.getElementById("category")
ele.value == "pdf" ? element.required =true : element.required =false
}
getVal(document.getElementById("subcat"))
<select id="category" name="category" required>
<option value="">select category</option>
<option>doc</option>
<option value="pdf">pdf</option>
<option>gifs</option>
</select>
<select id="subcat" name="subcat">
<option value="">select type</option>
<option>normal pdf</option>
<option>other pdf</option>
</select>
But its not working, what am I doing wrong?
using jQuery:
var $category = $("#category")
var $subcat = $("#subcat")
$category.on('change', function() {
$subcat.prop('required', $(this).val() === "pdf")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="category" name="category" required>
<option value="">select category</option>
<option>doc</option>
<option value="pdf">pdf</option>
<option>gifs</option>
</select>
<select id="subcat" name="subcat">
<option value="">select type</option>
<option>normal pdf</option>
<option>other pdf</option>
</select>
With pure JS:
var $category = document.querySelector("#category")
var $subcat = document.querySelector("#subcat")
$category.addEventListener('change', function() {
$subcat.required = this.value === "pdf"
})
This runs before the user selected something from the menu.
Adding a change event listener to the select will do it.
Also, you're mixing up ele and element.
function getVal(ele) {
ele.addEventListener('change', function() {
var element = document.getElementById("category")
element.value == "pdf" ? ele.required = true : ele.required = false
})
}
getVal(document.getElementById("subcat"))

How to get data attribute of option tag in JavaScript

Want to get data attribute value from selected dropdown option.
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
var rc = ? //value of data-rc
var clnc = ? //value of data-clnc
No jQuery please only JavaScript :)
You can read them out via dataset property.
var option = document.getElementsByTagName("option")[0];
console.log(option.dataset.rc)
console.log(option.dataset.clnc)
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
Or, if you want to get the values of the selected option:
var selection = document.getElementById("mySelect");
selection.onchange = function(event){
var rc = event.target.options[event.target.selectedIndex].dataset.rc;
var clnc = event.target.options[event.target.selectedIndex].dataset.clnc;
console.log("rc: " + rc);
console.log("clnc: " + clnc);
};
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
<option value="21" data-rc="23" data-clnc="30">Treatment1</option>
<option value="21" data-rc="31" data-clnc="50">Treatment2</option>
<option value="21" data-rc="14" data-clnc="75">Treatment3</option>
</select>
suppose we have a select field
<select id="ddlViewBy">
<option value="1" data-rc="25" data-clnc="10" selected="selected">test1</option>
<option value="2" >test2</option>
<option value="3">test3</option>
</select>
Now we will get the select list and its selected option
var e = document.getElementById("ddlViewBy");
var option= e.options[e.selectedIndex];
Now we have the selected option we can get its attribtues
var attrs = option.attributes;
attrs is the attributes array you can get attribtues by index you want.
Or you can get attribtues by
var datarc = option.getAttribute("data-rc");
Check this working pen
working pen
$('#options').on('change', function(){
alert($(this).find("option:selected").attr('data-rc'))
alert($(this).find("option:selected").attr('data-clnc'))
});
var mySelect = document.querySelector('#mySelect')
console.log('mySelect value ' + mySelect.value)
console.log('mySelect data-rc ' + mySelect.selectedOptions[0].getAttribute("data-rc"))
console.log('mySelect data-clnc ' + mySelect.selectedOptions[0].getAttribute("data-clnc"))
<select name="selection" id="mySelect">
<option value="21" data-rc="25" data-clnc="10">Treatment</option>
</select>
$(selector).find("option:selected").data("rc") for rc and clnc for clnc where selector is your "select" tag id/class
You can do that with jquery selector
var rc = $('select option:selected').data('rc');

Change select box value depending other selected option box

i am new to Javascript/ Jquery
so my problem is :
i want to change the select/option box text and value depending on the other selected option/box
so for examplemy first option is :
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
and then one i want to change depending on selected option is :
When its male :
<select id="name">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
when its female :
<select id="name">
<option>Select Your Name</option>
<option value="female1">Female 1</option>
<option value="female2">Female 2</option>
</select>
Thanks for the help! :)
There you go with DEMO
var options=""; //store the dynamic options
$("#gender").on('change',function(){ //add a change event handler to gender select
var value=$(this).val(); //get its selected value
options="<option>Select Your Name</option>"
if(value=="Male") //value ==Male then set male required options
{
options+="<option value='Male1'>Male 1</option>"
+"<option value='Male2'>Male 2</option>";
$("#name").html(options);
}
else if(value=="Female") //else set female required options
{
options+='<option value="female1">Female 1</option>'
+'<option value="female2">Female 2</option>';
$("#name").html(options);
}
else
$("#name").find('option').remove() //if first default text option is selected empty the select
});
I would suggest to have a better HTML architecture to achieve this kind of things. Have each name in one Dropdown only and categorise with some data attribute. When changing the value of Gender Dropdown, filter with type and toggle the options. Follow this:
$(function(){
$("#gender").on("change", function(){
var $target = $("#name").val(""),
gender = $(this).val();
$target
.toggleClass("hidden", gender === "")
.find("option:gt(0)").addClass("hidden")
.siblings().filter("[data-type="+gender+"]").removeClass("hidden");
});
});
.hidden{
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select id="gender">
<option value="">Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name" class="hidden">
<option value="">Select Your Name</option>
<option value="Male1" data-type="Male">Male 1</option>
<option value="Male2" data-type="Male">Male 2</option>
<option value="female1" data-type="Female">Female 1</option>
<option value="female2" data-type="Female">Female 2</option>
</select>
Fiddle link: http://jsfiddle.net/ashishanexpert/qzxedcut/
Whenever a change occurs, use the value of the gender dropdown to populate the names one. We use a for loop to produce more than one option per gender.
$('#gender').change(function(){
if(!this.selectedIndex) return;
var gender = $(this).val(),
$name = $('#name').empty(),
$option = $('<option />').text('Select Your Name').appendTo($name);
for(var i = 1; i <= 2; i++)
$option.clone().prop('value', gender + i).text(gender + ' ' + i).appendTo($name);
});
JSFiddle
Follow the Practice:
Do not hardcode options this case.Best practice is get value from Json.
Then later changes are easy instead of change all codings.
Build dynamic Dropdowns. Dont Hide and Show.
HTML
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="gtr" name="location" placeholder="Anycity"></select>
Jquery
jQuery(function($) {
var gender = {
'Male': ['Male1', 'male2'],
'Female': ['Female1','Female1'],
}
var $gndr = $('#gtr');
$('#gender').change(function () { debugger
var GNDR = $(this).val(), gndrs = gender[GNDR] || [];
var html = $.map(gndrs, function(gndr){
return '<option value="' + gndr + '">' + gndr + '</option>'
}).join('');
$gndr.html(html);$gndr.append(new Option("Select Name", "0"));$gndr.val("0");
});
});
JsFiddle
https://jsfiddle.net/2pza5/1135/
I suggest you to try this way:
Change you jquery:
<select id="nameMale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
<select id="nameFemale">
<option>Select Your Name</option>
<option value="Male1">Male 1</option>
<option value="Male2">Male 2</option>
</select>
Inser this javascript:
<script>
<![CDATA[
$(function() {
$('#nameFemale').hide();
$('#nameMale').hide();
function changeGen(val){
if(val == 'Female'){
$('#nameFemale').show();
$('#nameMale').hide();
}else{
$('#nameFemale').hide();
$('#nameMale').show();
}
}
$('#gender').change(function() {
changeGen($('#gender').val());
});
});
]]>
</script>
FIDDLE
$('#gender').change(function (e) {
var val = $("option:selected", this).val()
console.log(val);
if(val =='Male'){
$('#name').find('option.female').hide();
$('#name').find('option.male').show();
}else if(val =='Female'){
$('#name').find('option.female').show();
$('#name').find('option.male').hide();
}else{
}
});
Added class for each option since it is static.
Then you can hide the option from second select depending on the value of first select
Try this:
$("#gender").on("change",function(){
var sel="";
if($(this).val() == "Female"){
sel=' <option>Select Your Name</option>';
sel+=' <option value="female1">Female 1</option>'
sel+='<option value="female2">Female 2</option>'
}else{// no other if since you have only two options male/female
sel= '<option>Select Your Name</option>';
sel+= '<option value="Male1">Male 1</option>';
sel+= '<option value="Male2">Male 2</option>';
}
$("#name").html(sel);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="gender">
<option>Select Your Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<select id="name">
</select>

JQuery convert string to link

I have 3 select fields, and the combined value of these I would like to use as a extra part of an url.
Here's the HTML code:
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
And the JavaScript:
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text(str);
})
.trigger('change');
https://jsfiddle.net/eZKUU/264/
Right now it's working.. after I select an option in all 3 of the selectfields I get an output like /squad/redblack/1985.
I would like to use this output in an url, so it would look like:
mysite.com/squad/redblack/1985
Is there an easy way of doing this? And also.. To only get the link visible after all three of the selectfields have an option selected?
You can use the following. Add an a element and keep it hidden until is completed. Update a element href attribute with selected options:
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
//update href with selected values
$("#mySite").attr("href", "mysite.com/" + str);
});
//keep anchor element hidden until all three options is selected
$("#mySite").toggle($("#cos").find("option:selected").length > 0 && $("#color").find("option:selected").length > 0 && $("#year").find("option:selected").length > 0);
$("div#output").text(str);
})
.trigger('change');
#mySite {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/>
<br/>
<div id="output"></div>
<a id="mySite" href="#">Redirect Link</a>
You can check to see if the number of selected options is the same amount as the number of select elements.
var selectedAllLength = $("select").length;
$("select").change(function () {
var str = location.origin;
var selected = $("select option:selected");
var selectedCount = selected.length;
if(selectedCount == selectedAllLength) {
selected.each(
function () {
str += $(this).attr('value');
}
);
$("#output").html('<a href=' + str + '>The link is here</a>');
}
})
.trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name="cos" id="cos" size="5">
<option value="/squad">Squad</option>
<option value="/class">Class</option>
</select>
<select name="color" id="color" size="5">
<option value="/purpleblack">PurpleBlack</option>
<option value="/redblack">RedBlack</option>
<option value="/aquablack">AquaBlack</option>
</select>
<select name="year" id="year" size="5">
<option value="/1984">1984</option>
<option value="/1985">1985</option>
<option value="/1986">1986</option>
</select>
<br/><br/>
<div id="output"></div>
To only get the link after all three have been selected, simply use an if statement to only generate and display the link if 3 options are selected. To make it a URL, just append the path you get to the base URL. Something like:
$("select").change(function () {
var str = "";
if(#("select option:selected").length === 3){
$("select option:selected").each(function () {
var id = $(this).parent().attr('name');
str += $(this).attr('value');
});
$("div#output").text("mysite.com" + str);
// Or, if you want a clickable link and not just a URL:
// $("div#output").append($("<a>").attr({href: "mysite.com" + str}).append("Click me"));
}
})
.trigger('change');

Manipulating dropdowns populated by AJAX

JQuery is my best friend in good and bad Javascript times. However, some times it takes some figuring out for me before I finally achieve my goal. This is one of these days. This they I bumped into a certain issue I can't really find my way around. I'll try explaining it below.
My HTML
<select name="one" id="one">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
....
</select>
<select name="two" id="two">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
....
</select>
<select name="three" id="three">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
....
</select>
My JQuery
$(document).ready(function() {
if (one != 0) {
// Set select dropdown one
}
if (two != 0) {
// Set select dropdown two
}
if (three != 0) {
// Set select dropdown three
}
});
$(document).on('change', '#three', function() {
var item = $(this).val();
var url = basePath + 'item/' + item;
window.location = url;
});
PHP
<script type="text/javascript">
var one = <?= $one; ?>;
var two = <?= $two; ?>;
var two = <?= $three; ?>;
</script>
The issue
What I want to achieve is that when an option is selected in dropdown one, JQuery loads dropdown two. When an option is selected in dropdown two, JQuery loads dropdown three.
I've got this working. However, when dropdown three is selected, it does a refresh. But as soon as that refresh is done, all select values would be set again and another refresh would be triggered.
I want JQuery to only refresh the first time, set all select values after the refresh (thus triggering the change event on the select dropdowns and loading the values) but not refreshing when the third select dropdown value is set.
If I need to do more explaining on this please let me know. Any suggestions and help would be very welcome.
Progress
if (false !== rootpfgroup && false !== hoofdpfgroup && false !== subpfgroup) {
$('#one').val(rootpfgroup).trigger('change');
$('#two').val(hoofdpfgroup).trigger('change');
$('#three').val(subpfgroup);
}
I've found the following to be working. However, it only sets the first dropdown. Selecting a value in the first dropdown triggers an ajax call that loads the options for the second one. Selecting an option in the second drop down triggers an ajax call that loads the options for the third one. Can somebody tell me more on how to go about this and what I'm doing wrong? Thanks in advance.
As per my comment above, setting the selected dropdown value using PHP to set the HTML selected attribute would also work, eliminating your refresh problem and meaning that the value persistence works without JS (whether you care about that is a different matter):
<?php
$one = '';
$two = '';
$three = '';
if (!empty($_POST['one'])) {
$one = $_POST['one'];
}
if (!empty($_POST['two'])) {
$two = $_POST['two'];
}
if (!empty($_POST['three'])) {
$three = $_POST['three'];
}
?>
$(document).on('change', '#three', function() {
var form = $('#form');
var item = $(this).val();
var url = basePath + 'item/' + item;
form.attr('action', url);
form.submit();
});
<form action="" method="POST" id="form">
<select name="one" id="one">
<option value="1" <?php if ($one == 1):?>selected<?php endif;?>>One</option>
<option value="2" <?php if ($one == 2):?>selected<?php endif;?>>Two</option>
<option value="3" <?php if ($one == 3):?>selected<?php endif;?>>Three</option>
</select>
<select name="two" id="two">
<option value="1" <?php if ($two == 1):?>selected<?php endif;?>>One</option>
<option value="2" <?php if ($two == 2):?>selected<?php endif;?>>Two</option>
<option value="3" <?php if ($two == 3):?>selected<?php endif;?>>Three</option>
</select>
<select name="three" id="three">
<option value="1" <?php if ($three == 1):?>selected<?php endif;?>>One</option>
<option value="2" <?php if ($three == 2):?>selected<?php endif;?>>Two</option>
<option value="3" <?php if ($three == 3):?>selected<?php endif;?>>Three</option>
</select>
</form>
As I mentioned, depending on what your data actually looks like (assuming it isn't just lists of numbers ;) you might be able to add some loops in your PHP to avoid repetition.
<?php
$one = '';
$two = '';
$three = '';
if (!empty($_POST['one'])) {
$one = $_POST['one'];
}
if (!empty($_POST['two'])) {
$two = $_POST['two'];
}
if (!empty($_POST['three'])) {
$three = $_POST['three'];
}
?>
$(document).ready(function() {
var one = '<?= $one; ?>';
var two = '<?= $two; ?>';
var three = '<?= $three; ?>';
if (one != '') {
$('#one').val(one);
}
if (two != '') {
$('#two').val(two);
}
if (three != '') {
$('#three').val(three);
}
});
$(document).on('change', '#three', function() {
var form = $('#form');
var item = $(this).val();
var url = basePath + 'item/' + item;
form.attr('action', url);
form.submit();
});
<form action="" method="POST" id="form">
<select name="one" id="one">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select name="two" id="two">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select name="three" id="three">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</form>
This should now set the values as intended.

Categories

Resources