Firstly, this is my first ever time using jQuery, so my code is not going to be the best. I'm adding a filter to my works website based off 3 drop boxes: fuel type, drive-type, and vehicle type. I want that when someone selects petrol it shows all the petrol cars, which I have managed to achieve, but now I'm a bit stuck. I now want it to show based on all 3 boxes, so if someone selects petrol, and then auto and then cars, it will show only petrol automatic cars. I can't seem to make the 3 boxes work together. so please help.
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// fuels
$("#fuel").change(function() {
if ($("#fuel option[value='petrol']").attr('selected')) {
$('div[class*=petrol]').css('display','block');
}
if ($("#fuel option[value='diesel']").attr('selected')) {
$('div[class*=diesel]').css('display','block');
}
// end
//drivetype
});
$("#drive").change(function() {
if ($("#drive option[value='man']").attr('selected')) {
$('div[class*=manual]').css('display','block');
}
if ($("#drive option[value='auto']").attr('selected')) {
$('div[class*=auto]').css('display','block');
}
//end
});
// vech type
$("#type").change(function() {
if ($("#type option[value='car']").attr('selected')) {
$('div[class*=car]').css('display','block');
}
if ($("#type option[value='4']").attr('selected')) {
$('div[class*=4]').css('display','block');
}
if ($("#type option[value='7']").attr('selected')) {
$('div[class*=7]').css('display','block');
}
if ($("#type option[value='van']").attr('selected')) {
$('div[class*=van]').css('display','block');
}
// end
});
});
<select id="fuel">
<option value="none">fuel</option>
<option value="petrol">petrol</option>
<option value="diesel">diesel</option>
</select>
<select id="drive">
<option value="none">drive</option>
<option value="man">manual</option>
<option value="auto">auto</option>
</select>
<select id="type">
<option value="none">type</option>
<option value="car">car</option>
<option value="4">4x4</option>
<option value="7">people carrier</option>
<option value="van">van</option>
</select>
Basically at the time when you want to show the cars, you want to check all 3 select boxes for their values so you know which cars to show
In this case when showing cars for "auto" you need to check petrol as well as auto. when showing cars for "cars" you need to check all 3.
edit:
$("#type").change(function() {
// check previous select box value, check this box value
// output the correct cars
});
for the last one you simply check both of the previous boxes and this box and output the correct cars
Try to do something like:
$("#fuel").change(function() {
var value = $(this).val();
$(".elements_to_hide").hide(); //check if needed
$("." + value).show();
});
Please dont take it personally, but Ill give some suggestions about your code:
Try to avoid such complex constractions like: $('div[class*=diesel]').It will affect the performance.
JQuery contains build-in functions for show/hide DOM elements — .show(), .hide()
To get selected option of "select" use .val();
Hope answer will helpful for you. Best regards!
Related
This is my dropdown.
<select id="sortBySelector" onchange="chooseSort(value)" style="display:block;border-color: #e0e0e0;">
<option value="nameSort" selected>Alphabetical</option>
<option value="gradSort">Graduation Date</option>
</select>
I have two <ul> with id= "nameSort" and "gradSort"
I wrote jquery code that will show only the selected one.
I tried this
<script>
function chooseSort(value) {
$("#nameSort").hide();
$("#gradSort").hide();
$(value).show();
}`
but it shows both lists when its on the Alphabetical option and shows nothing when i click on the Graduation option. Im not sure why this is happening. Please let me know if you can help. thank you for your time
Consider what this is doing with the given value:
$(value).show();
If the value is gradSort then you're doing:
$("gradSort").show();
Which is an incorrect selector. If you're looking by id then it's missing the # at the beginning. You can add that to the values:
<option value="#nameSort" selected>Alphabetical</option>
<option value="#gradSort">Graduation Date</option>
Or, if for a reason outside of this you don't want to change the values, you can add it to the string in the selector:
$('#' + value).show();
or:
$(`#${value}`).show();
it shows both lists when its on the Alphabetical option
It sounds like it shows both lists when the page first loads. If that's the case you can just call the function manually on page load to set the initial state:
chooseSort('#nameSort');
or:
chooseSort('nameSort');
(depending on which solution you used above)
The value itself will represent the actual value of option. So if the selected option value be gradSort this part of your code
$(value).show();
will be pointed to
$("gradSort").show();
which is not refer to anything in DOM. Because it is not a valid selector (tag), so to make this work, you should add # either
before your query selector
$('#' + value).show();
or before the value of your options.
<option value="#nameSort" selected>Alphabetical</option>
<option value="#gradSort">Graduation Date</option>
I will go with the query selector choice, so it will be something like this:
function chooseSort(value) {
$("#nameSort").hide();
$("#gradSort").hide();
$("#" + value).show();
}
$(document).ready(function() {
chooseSort("nameSort");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="sortBySelector" onchange="chooseSort(value)" style="display:block;border-color: #e0e0e0;">
<option value="nameSort" selected>Alphabetical</option>
<option value="gradSort">Graduation Date</option>
</select>
<div id="nameSort">nameSort</div>
<div id="gradSort">gradSort</div>
You need a conditional to determine which will be shown and which will stay hidden. There are a few different ways to do this but I would do it like so:
<select id="sortBySelector" onchange="chooseSort(value)" style="display:block;border-color: #e0e0e0;">
<option id="nameSort' value="nameSort" selected>Alphabetical</option>
<option id="gradSort value="gradSort">Graduation Date</option>
</select>
function chooseSort(value) {
if (value === 'nameSort'){
$('#' + value).show(); // $("#nameSort").show(); would work
$("#gradSort").hide();
} else{
$('#' + value).show(); // $("#gradSort").show(); would work
$("#nameSort").hide();
}
}
Let me know if this works!
EDIT: In the spirit of keeping your HTML the same, I did have to add the id to each option to make it work. Also, I had to redo the value.show()
This question already has answers here:
Show Hide select options based on previous selection dropdown in Jquery or Javascript
(3 answers)
Closed 4 years ago.
I'm making two dropdown menus. The second menu will be filtered according to the selection in the first menu. The first will be a list of over 20 regions; the second menu will have three transportation options.
Most of the regions have only one transportation option, "car." One region is an exception and has "bike," "car" and "walk." (I tried to do an if/else but couldn't figure it out; I'm not well-versed in jQuery.) I want to have most of the regions in the same data-category, a simple "all." The problem is that I haven't been able to figure out how to create an "all" category because there's only two categories but many different values.
<form name="locator">
<select class="selectregion" id="regionselector" name="selectregion">
<option value="" selected="selected">Select Region</option>
<option data-category="all" value="al1">Alabama: Birmingham</option>
<option data-category="all" value="al2">Alabama: Montgomery</option>
<option data-category="all" value="al3">Alabama: Tuscaloosa</option>
<option data-category="all" value="ga1">Georgia: Atlanta</option>
<option data-category="all" value="ga2">Georgia: Augusta</option>
<option data-category="bikewalk" value="ga3">Georgia: Foo</option>
</select>
<select class="vehicle" id="vehicleselector" name="selectvehicle">
<option value="" selected="selected">Select Transportation</option>
<option data-value="all" value="car">Car</option>
<option data-value="bikewalk" value="bike">Bike</option>
<option data-value="bikewalk" value="walk">Walk</option>
</select>
</form>
My JavaScript (customizing code in this post:
$('#regionselector').change(function() {
var $options = $('#vehicleselector')
.val('')
.find('option')
.show();
if (data-value != '0')
$options
.not('[data-category="' + data-value + '"],[data-category=""]')
.hide();
});
I replaced this.value with data-value and unsurprisingly it didn't work. Right now, nothing filters down.
What can I do to show "car" for every region and "car," "bike," and "walk" for the one exception? (Foo, Georgia in this example). Thank you for your help.
JSFiddle
UPDATE: The post suggested as a duplicate – where classes are used instead of data-categories – solved the problem. Combining that code with mine, just use "all" and "bikewalk" as classes for Foo (the region with all three vehicle options) and "all" as the single class on the rest. Then bike/car/walk are the options on Foo and car is the option for the other regions.
You can think in reversed approach. All options are hidden and on select action show right options.
$('#regionselector').change(function() {
// always on change hide all options
$('#vehicleselector option').not('[value=""]').hide();
// get selected value from #regionselector
let option = $(this).find('option[value="' + $(this).val() + '"]');
// get value start with 2 chars
let value = option.val().substring(0,2);
// get all options start with value
let optionsStartWithValue = $(this).find('option[value^="' + value + '"]');
// for each options for region show vehicle
optionsStartWithValue.each(function(i, v) {
// show all options in #vehicleselector which contain selected data category
$('#vehicleselector option[data-value="' + $(v).data('category') + '"]').show();
});
});
// reset values
$('#vehicleselector').change(function() {
if($(this).val() == '') {
$('#regionselector').val('');
}
});
JSFIDDLE
I want to Modify text contents of dynamically generated drop down list using jQuery. Here is my example:
Drop Down Text look like below:
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
jQuery:
var previous;
$('#s1').focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
//Modify the SelectedOption Display only Number Value
$('#s1').find(':selected').text($('#s1').find(':selected').val());
//Restore the Previous Option : Format 'Number Value : data-name'
alert($("#s1 option[value='"+previous+"']").val());
alert($("#s1 option[value='"+previous+"']").attr('data-name'));
$("#s1 option[value='"+previous+"']").text($("#s1 option[value='"+previous+"']").val() +' '+ $("#s1 option[value='"+previous+"']").attr('data-name'));
});
I also used following attributes :
value: stores number value of that car
data-name: stores the Name of that Car
This is what I want:
Whenever any user select any option, then the selected option text will be modified and removes that Name part: For example: selecting 1:Volvo become 1 only.However if user select another option then the previous option text will be restore back to previous format e.g: 1 becomes 1:Volvo again. That is why i used given attributes to restore format.
I have written a code that works fine if i used alert .But i want to do it without using alert and then it does not work.
Here is my code:
jsfiddle
please help.
You have set data-name and value attributes, so you can easily loop over the options and use those attributes to update the text:
$('#s1').change(function() {
$(this).find('option').each(function(){
$(this).text(
$(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
);
});
});
$('#s1').change(function() {
$(this).find('option').each(function(){
$(this).text(
$(this).attr('value')+( $(this).is(':selected') ? '' : ':'+$(this).attr('data-name'))
);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
EDIT (comment)
I'd say that with a normal usage, the code above will have no impact on user experience. It will be slower in a mathematics(?) meaning - negligible differences in execution time, as DOM is modified (each <option> is updated) inside $.each() loop, which isn't the best idea. But nothing that usar can notice.
For the OP example, where only 5 options are involved, it's arguable that updating all of them VS updating only 2, won't make any difference in speed. If there would be hundrets of options, then (speaking about user experience) I, as a user, wouldn't be so glad having so many options to pass through, searching the one I need. So the main issue would be there.
But, if there are any concerns about the above script speed, there's another (a better?) way, without using global flags and loops.
It creates a temporary data-last attribute for identifying previously selected <option> and only two options are modified at a time :
$('#s1').change(function() {
$(this).find('option:selected').attr('data-last','Yes').text(this.value)
.siblings('[data-last]').removeAttr('data-last').text(function(){
return this.value+':'+$(this).attr('data-name');
});
});
$('#s1').change(function() {
$(this).find('option:selected').attr('data-last','Yes').text(this.value)
.siblings('[data-last]').removeAttr('data-last').text(function(){
return this.value+':'+$(this).attr('data-name');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="s1">
<option data-name="volvo" value="1">1:Volvo</option>
<option data-name="saab" value="2">2:Saab</option>
<option data-name="mercedes" value="3">3:Mercedes</option>
<option data-name="audi" value="4">4:Audi</option>
<option data-name="BMW" value="11">11:BMW</option>
</select>
And there's a speed comparison between these two methods (200 options) :
JSFiddle
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
<select class="distinctrank" name="rank[]" required>
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
I am trying to prevent the user to select the same option twice
EX:
value 1 -> B
value 2 -> C
value 3 -> A
But not allow
value 1 -> B
value 2 -> B
value 3 -> A
I can't use this: answer
because I have 8 <select> with 8 <option>and the user is allow to change his/her option.
Unfortunately, I can't use a single select set to "multiple".
I found this answer just now, but since I don't jquery or Javascript well, I can't make it work without the select tag inside a table:
Here is the answer
UPDATE:
I found a better way to do it, but I am having some problems.
I tried to modify this code: with input tags to make it work with select tags. The problem that I am facing now is that every time you select the same option twice, the error "Please enter a Unique Value" show up (I do want to see it, when the user select the same value twice or more) and when you change the value the "Please enter a Unique Value" does go away. But, It keep a "this field is required" warning behind (when a click a new select tag). So, "this field is required" doesn't go away until the user pick an option for all select tag.
Here is the Jquery code:
jQuery.e
jQuery.validator.addMethod("notEqualToGroup", function(value, element, options) {
// get all the elements passed here with the same class
var elems = $(element).parents('form').find(options[0]);
// the value of the current element
var valueToCompare = value;
// count
var matchesFound = 0;
// loop each element and compare its value with the current value
// and increase the count every time we find one
jQuery.each(elems, function() {
thisVal = $(this).val();
if (thisVal === valueToCompare) {
matchesFound++;
}
});
// count should be either 0 or 1 max
if (this.optional(element) || matchesFound <= 1) {
//elems.removeClass('error');
return true;
} else {
//elems.addClass('error');
}
}, jQuery.validator.format("Please enter a Unique Value."))
// validate form
$("#signupform").validate({
rules: {
'rank[]': {
required: true,
notEqualToGroup: ['.distinctrank']
},
},
});
I wonder if you could simply use a single select set to "multiple"...
<select multiple class="form-control" name="rank[]">
<option value="">Select</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select>
It seems appropriate :-)
Your code...
rules: {
'rank[]': { // <-- will only match one of your three
required: true, ....
You cannot have three different select element all share the same name, in your case, rank[].
The jQuery Validate plugin requires that every form data input element contain a unique name. It's how the plugin keeps track of the form inputs, and there is no workaround for this. You'll have to include an index or change the name.
rules: {
'rank[1]': {
// rules
},
'rank[2]': {
// rules
},
'rank[3]': {
// rules
}
}
If the same rules are used on all three, then you can use the .rules() method to apply them all at once...
$("#signupform").validate({ // plugin initialization
// other rules & options
});
$('[name^="rank"]').each(function() {
$(this).rules('add', {
required: true,
notEqualToGroup: ['.distinctrank']
});
});
$('[name^="rank"]') matches all elements that have a name that "starts with" rank. Then .each() applies the rule to every instance matched by the selector.
You can try something like this:
$(document).ready(function() {
$('select').change(function() {
self = $(this);
choosen = $(this).val();
$('select').not(self).each(function() {
if ($(this).val() == choosen) {
// $(this).prop('disabled', true);
alert('Option is already selected');
$(self).val($(this).find("option:first").val());
}
});
});
});
This is actually partial implementation of code you found in another answer. Commented line would disable already selected options, but... then users can't change their minds... However i would probably use that commented line (edit:probably not, it causes other problems), rather than annoying alerts -> because, with alerts - if user tries to change his mind - user experience is not so great, again...
DEMO: http://jsfiddle.net/dq9j4s32/2
I am working on a form. One of my colleagues have used the are_you_sure.js which confirms to leave before saving a form.
Now the problem is if I have a dropdown say like this
<script type="text/javascript">
function get_cpc(cst_type)
{
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").show();
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
}
</script>
<select name="cost_type" id="cost_type" onchange="get_cpc(this.value);" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
When I am switching from non-selected options to selected option, then the change of state takes too much time
This means if I am selecting CPC/Do Not Track from CPA, then the dropdown works fast. But if I am selecting CPA from CPC/Do Not Track, then the state change takes almost 4 seconds..
That's due to the jquery.are-you-sure.js. So, I need to remove the select from the dropdown. How can I achieve this?
I put this code, $("select option").prop("selected", false);
but it doesn't even let me select any other option.
I'm not sure what you mean exacly, but can you share the are_you_sure.js file?¿
Also I have change your code maybe it helps and it´s a better way to do it. because it´s not a good practice use onchange(), so remove onchange from your html and do this, link: http://jsfiddle.net/hg5nz1w6/1/
js:
$(document).ready(function(){
$('#cost_type').on('change', function(){
var cst_type = $(this).val();
if(cst_type==0 || cst_type==1)
{
$("#camp_cpc").val("'.(!empty( $html['camp_cpc'] )?(double)$html['camp_cpc']:'').'");
$("#camp_cpc").show();
}
else
{
$("#camp_cpc").hide();
$("#camp_cpc").val("0");
}
});
});
html:
<select name="cost_type" id="cost_type" class="ultra-select">
<option value="0">CPC</option>
<option value="1" selected="selected">CPA</option>
<option value="2">Do Not Track</option>
</select>
Below you can see some examples to remove the selected:
document.getElementById('myselect').selectedIndex = -1;
you can deselect all the options:
$("select").val([]);
or
$("select option").prop("selected", false);
Hope it´s helps!