jQuery - Autoselect option on selectbox doesn't function well - javascript

I have 2 select boxes. When I select an option on selectbox1, it automatically changes the corresponding value on selectbox2 regardless of value but order.
The thing is, the code is working fine until after a few tries. Then even if I change the option on selectbox1, it doesn't update the one on selectbox2.
To reproduce the issue; go through A to E, then repeat.
Code:
$(".firstSelectBox").change(function(e) {
var selectedOption = $("option:selected", this);
var idx = $(this).children().index(selectedOption)
var secChildIdx = $(".secondSelectBox").children()[idx];
$(".secondSelectBox").find(":selected").removeAttr('selected');
$(secChildIdx).attr("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>
Also JSFiddle version: https://jsfiddle.net/153w074d/

No need for all that code, just work with selectedIndex:
$(".firstSelectBox").change(function(e) {
var selectedIndex = $(this).get(0).selectedIndex;
$(".secondSelectBox").get(0).selectedIndex = selectedIndex;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>
What happened in your original code is that, in some way, the selected attributes are being messed around. Try this: Change to each option from A to E, then start over from A, the selection stops working. Then inspect the second select to see that there are more than one option with selected="selected" attribute. Not sure what caused that tho.

#DontVoteMeDown's answer will certainly work, but the reason you're having this issue is because of the discrepancy between .prop and .attr. Both are similar, but don't refer to the same, identical underlying value.
If you change the below two lines to use the .prop value instead of .attr, your code will work. See the working code example below.
$(".secondSelectBox").find(":selected").removeAttr('selected'); // change to .removeProp
$(secChildIdx).attr("selected", "selected"); // change to .prop
$(".firstSelectBox").change(function(e) {
var selectedOption = $("option:selected", this);
var idx = $(this).children().index(selectedOption)
var secChildIdx = $(".secondSelectBox").children()[idx];
$(".secondSelectBox").find(":selected").removeProp('selected');
$(secChildIdx).prop("selected", "selected");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>

You can also use prop to select option.
$(".firstSelectBox").change(function(e) {
var selectedIndex = $(this).get(0).selectedIndex;
$('.secondSelectBox option:eq('+selectedIndex+')').prop('selected', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="control-group">
<div class="controls">
<label>First Selectbox</label><br/>
<select class="firstSelectBox validate[required]">
<option value="1">Select A</option>
<option value="2">Select B</option>
<option value="3">Select C</option>
<option value="4">Select D</option>
<option value="5">Select E</option>
</select>
</div>
</div>
<br />
<div class="control-group">
<div class="controls">
<label>Second Selectbox</label><br />
<select class="secondSelectBox validate[required]">
<option value="A">Select 1</option>
<option value="B">Select 2</option>
<option value="C">Select 3</option>
<option value="D">Select 4</option>
<option value="E">Select 5</option>
</select>
</div>
</div>

Related

Get a value from a data-attribute of multiple selected dropdowns (Dynamic dropdowns)

I'm trying to get the data attribute of the selected dropdown to an input box and the given code works perfectly for single dropdown included in the page and it outputs the data attribute to the input box.
But when i add two or more dropdowns the value doesn't come properly. I'm working with dynamic data which i retrieve from a DB so the amount of dropdowns can differ. How can i write the js code to be dynamic?
$(document).ready(function() {
$('select.material-price').change(function() {
var materialValue = $('select.material-price').find(':selected').data('price');
$('.material-total').val(materialValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<select class="material-price">
<option data-price="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
<div class="row">
<select class="material-price">
<option data-price="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
</div>
Make use of $(this) jquery to get the value from fired select's data and use $next() to assign value to input sits immediate next to select.
$(document).ready(function() {
$('select.material-price').change(function() {
var materialValue = $(this).find(':selected').data('price');
$(this).next('.material-total').val(materialValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<select class="material-price">
<option data-price="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
<div class="row">
<select class="material-price">
<option data-price="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
Update: when using select2 jquery surely your structure will get change on dom. so obviously we need to restructure the query too. check below snippet for reference.
$(document).ready(function() {
$('.select2').select2();
});
$(document).ready(function() {
$('select.material-price').change(function() {
var materialValue = $(this).select2().find(":selected").data("price");
$(this).parent('.row').find('.material-total').val(materialValue);
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/css/select2.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.min.js"></script>
<div class="container">
<div class="row">
<select class="material-price select2">
<option value="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
<div class="row">
<select class="material-price select2">
<option data-price="100000" value="10">Material A</option>
<option data-price="400000" value="20>">Material B</option>
<option data-price="500000" value="30">Material C</option>
</select>
<input type="text" class="material-total" readonly />
</div>
</div>

Using jquery find() to select a dropdown deselects other dropdowns

I am attempting to select a dropdown option (out of several dropdowns on the page) by its value. I'm posting below code I think is relevant but if more is needed please let me know!
HTML
<form class="controls" id="Filters">
<fieldset>
<select id="select1" class="dropdowns">
<option selected="selected" value=".default1">Default 1</option>
<option value=".option1">Option 1</option>
<option value=".option2">Option 2</option>
</select>
</fieldset>
<fieldset>
<select id="select2" class="dropdowns">
<option selected="selected" value=".default2">Default 2</option>
<option value=".option3">Option 3</option>
<option value=".option4">Option 4</option>
</fieldset>
<fieldset>
<select id="select3" class="dropdowns">
<option selected="selected" value=".default3">Default 3</option>
<option value=".option5">Option 5</option>
<option value=".option6">Option 6</option>
</fieldset>
</form>
jQuery
var example = ".option3";
var example = ".option3";
$('#Filters').find('.dropdowns').val(example).click();
<form class="controls" id="Filters">
<fieldset>
<select id="select1" class="dropdowns">
<option selected="selected" value=".default1">Default 1</option>
<option value=".option1">Option 1</option>
<option value=".option2">Option 2</option>
</select>
</fieldset>
<fieldset>
<select id="select2" class="dropdowns">
<option selected="selected" value=".default2">Default 2</option>
<option value=".option3">Option 3</option>
<option value=".option4">Option 4</option>
</select>
</fieldset>
<fieldset>
<select id="select3" class="dropdowns">
<option selected="selected" value=".default3">Default 3</option>
<option value=".option5">Option 5</option>
<option value=".option6">Option 6</option>
</select>
</fieldset>
</form>
enter code here $('#Filters').find('.dropdowns').val(example).click();
This works, selects the correct dropdown option and the dropdown initiates the filtering process (I'm using MixItUp), but it deselects all other dropdowns making them blank instead of their default values, which should be (in this example) Default 1, Default 2, Default 3, etc. (except of course the dropdown that contains the correct value).
I'm hoping to have jQuery code find the dropdown option with the correct value (example = ".option3") but not affect the other dropdowns and make sure they're still on their default initial values.
I haven't been able to find answers to my problem anywhere so any help would be appreciated!
If I got your point you can use .find('option[value="'+example+'"]').prop('selected', true);
Demo
var example = ".option3";
$('#Filters').find('option[value="'+example+'"]').prop('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="controls" id="Filters">
<fieldset>
<select id="select1" class="dropdowns">
<option selected="selected" value=".default1">Default 1</option>
<option value=".option1">Option 1</option>
<option value=".option2">Option 2</option>
</select>
</fieldset>
<fieldset>
<select id="select2" class="dropdowns">
<option selected="selected" value=".default2">Default 2</option>
<option value=".option3">Option 3</option>
<option value=".option4">Option 4</option>
</fieldset>
<fieldset>
<select id="select3" class="dropdowns">
<option selected="selected" value=".default3">Default 3</option>
<option value=".option5">Option 5</option>
<option value=".option6">Option 6</option>
</fieldset>
</form>
find does not deselect your selects. val does.
What happens is, $('#Filters') finds the form object. Then .find('.dropdowns') finds all the select objects within it. Then .val(example) sets the value of all of those select objects to .option3. However, that value happens to be invalid for most of them.
What I assume you want is to find only the select objects that actually can take your value, and set the value for those only:
var example = ".option3";
$('#Filters').find('.dropdowns:has(option[value="' + example + '"])').val(example);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="controls" id="Filters">
<fieldset>
<select id="select1" class="dropdowns">
<option selected="selected" value=".default1">Default 1</option>
<option value=".option1">Option 1</option>
<option value=".option2">Option 2</option>
</select>
</fieldset>
<fieldset>
<select id="select2" class="dropdowns">
<option selected="selected" value=".default2">Default 2</option>
<option value=".option3">Option 3</option>
<option value=".option4">Option 4</option>
</select>
</fieldset>
<fieldset>
<select id="select3" class="dropdowns">
<option selected="selected" value=".default3">Default 3</option>
<option value=".option5">Option 5</option>
<option value=".option6">Option 6</option>
</select>
</fieldset>
</form>
(Hopefully your option values won't have crazy things like quotes inside them.)
Please find below solution, I hope this will help you.
var example = ".option3";
$('#Filters').find('.dropdowns').val(example).prop('selected',true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="controls" id="Filters">
<fieldset>
<select id="select1" class="dropdowns">
<option selected="selected" value=".default1">Default 1</option>
<option value=".option1">Option 1</option>
<option value=".option2">Option 2</option>
</select>
</fieldset>
<fieldset>
<select id="select2" class="dropdowns">
<option selected="selected" value=".default2">Default 2</option>
<option value=".option3">Option 3</option>
<option value=".option4">Option 4</option>
</select>
</fieldset>
<fieldset>
<select id="select3" class="dropdowns">
<option selected="selected" value=".default3">Default 3</option>
<option value=".option5">Option 5</option>
<option value=".option6">Option 6</option>
</select>
</fieldset>
</form>
You need to be more specific when selecting your dropdown.
Use the dropdown ID to select it, then choose a value using val(), then trigger a click event, ei.:
var example = ".option3"; $('#Filters').find('.dropdowns #select2 ').val(example).click();
Otherwise you're assigning the value "option3" for all three dropdowns, which is why #select1 and #select3 look empty.

Drop-Down List using Javascript HTML and jQuery

I'm trying to create a function in javascript that will see what day it is and depending on a day have a certain drop box list appear. However, for some reason it won't work and I'm not sure where the syntax error is in my code.
HTML:
<html>
<head></head>
<body>
<div class="Questions">
<div id="myAnswers" style="display : none">>
<div id="A">
<p><strong>Where are you Studying</strong></p>
<select>
<option value disabled selected>Choose Location</option>
<option value="1">Answer 1</option>
<option value="1">Answer 2</option>
<option value="1">Answer 3</option>
<option value="1">Answer 4</option>
<option value="1">Answer 5</option>
<option value="1">Answer 6</option>
</select>
</div>
<div id="B" style="display : none">
<select>
<option value disabled selected>Choose Answer</option>
<option value="1">Answer 1</option>
<option value="1">Answer 2</option>
<option value="1">Answer 3</option>
<option value="1">Answer 4</option>
</select>
</div>
</div>
</div>
</body>
</html>
Javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var day= new Date();
var weekday= day.getDay();
$("#A","#B").hide();
function showAnswer(){
if(weekday==3 || weekday==4){
$("#B").show();
}else{
$("#A").show();
}
}
window.onload=showAnswer;
</script>
A few issues to fix before your code can work:
As noted by #junkfoodjunkie you do not need the style="display:none;"
Use new Date(), not new Day()
Use $("#A,#B").hide(), not $("#A","#B")
Feel free to liberally use jQuery since ... :)
$(function() {
var day= new Date();
var weekday= day.getDay();
$("#A,#B").hide();
function showAnswer(weekday) {
if(weekday==3 || weekday==4) {
$("#B").show();
} else {
$("#A").show();
}
}
showAnswer( weekday );
console.log( weekday );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Questions">
<div id="myAnswers">
<div id="A">
<p><strong>Where are you Studying</strong></p>
<select>
<option value disabled selected>Choose Location</option>
<option value="1">Answer 1</option>
<option value="1">Answer 2</option>
<option value="1">Answer 3</option>
<option value="1">Answer 4</option>
<option value="1">Answer 5</option>
<option value="1">Answer 6</option>
</select>
</div>
<div id="B">
<select>
<option value disabled selected>Choose Answer</option>
<option value="1">Answer 1</option>
<option value="1">Answer 2</option>
<option value="1">Answer 3</option>
<option value="1">Answer 4</option>
</select>
</div>
</div>
</div>

jQuery if Form with Selects are Filled out, show div

I am look for a way to make it so that when the user selects an item form all the select (for which the value of the option is not nil) the div with id "js-market" is shown.
This is my html code:
<form class="js-chose">
<div class="col-md-6 col-xm-12">
<div class="form-group js-select">
<label>Select a Market</label>
<select class="form-control">
<option value='' disabled selected>Chose a Market</option>
<%Item.all.each do |item|%>
<option value="<%=item.id%>"><%=item.name.capitalize%></option>
<%end%>
</select>
</div>
</div>
<div class="col-md-6 col-xm-12">
<div class="form-group">
<label>Enter Market with:</label>
<select class="form-control js-select">
<option value='' disabled selected>Chose a Company</option>
<%Company.where(user_id: current_user.id).each do |company|%>
<option value="<%=company.id%>"><%=company.name%></option>
<%end%>
</select>
</div>
</div>
</form>
In short I need to make jQuery show the div with id="js-market" when both selects have been filled by the user and get the values of the selected items and assign them to a variable.
Thank you. Please let me know if I wasn't clear enough.
Example that works with multiple select elements
Link to jsfiddle
var counter = $('.select').length;
$('.select').change(function() {
$.each($('.select'),function(i,e) {
var t = $(this);
if (t.val() == undefined || t.val() == '') {
$('#js-market').fadeOut();
return;
}
if (i+1 == counter) {
$('#js-market').fadeIn();
}
});
});
#js-market {
display: none;
}
<select class="select">
<option value="">No Value</option>
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
<option value="value1">Value 4</option>
</select>
<select class="select">
<option value="">No Value</option>
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
<option value="value1">Value 4</option>
</select>
<select class="select">
<option value="">No Value</option>
<option value="value1">Value 1</option>
<option value="value2">Value 2</option>
<option value="value3">Value 3</option>
<option value="value1">Value 4</option>
</select>
<div id="js-market">Lorem ipsum</div>
See this fiddle
You can do this by onchange() event in javascript. In the fiddle specified above, what I do is that, I've placed 2 select boxes and a div with id demo will be shown only if two of the select boxes are selected.
HTML
<select id="mySelect1" onchange="myFunction()">
<option value="0">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="mySelect2" onchange="myFunction()">
<option value="0">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<div id="demo"></div>
JS
function myFunction() {
if (document.getElementById("mySelect1").value > 0 && document.getElementById("mySelect2").value > 0) {
document.getElementById("demo").style.display = "block";
} else document.getElementById("demo").style.display = "none";
}

Hiding Form Options when selecting an option with jquery

I am trying to have certain options of a dropdown display/hide when an option from a proceeding dropdown menu is selected, a friend sent me this sort of format for the script but i cant figure out how to get it to work as im not the most experienced with jquery and javascript but this worked for him (he was using text links instead of options in a dropdown)
HTML
<form class="form-horizontal" role="form">
<div class="form-group">
<label for="location" class="col-sm-4 control-label">Choose a Location</label>
<div class="col-sm-8">
<select id="selection" class="form-control">
<option selected="selected" value="none">None</option>
<option value="Dubai">Dubai</option>
<option value="bora">Bora Bora</option>
<option value="vancouver">Vancouver</option>
<option value="rio">Rio De Janeiro</option>
</select>
</div><br></br>
<label for="length" class="col-sm-4 control-label">Choose a Resort</label>
<div class="col-sm-8">
<select class="form-control">
<option id="none">None</option>
<option class="location dubai">Resort 1</option>
<option class="location dubai">Resort 2</option>
<option class="location bora">Resort 3</option>
<option class="location bora">Resort 4</option>
<option class="location vancouver">Resort 5</option>
<option class="location rio">Resort 6</option>
</select>
</div><br></br>
SCRIPT
<script src="assets/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$("#selection").change(function(){
var selection = $(this).val();
if(selection == "none"){
$("#none").find(".location").show();
}else{
$("#none").find(".location").not("."+selection).hide();
$("."+selection).show();
}
});
});
</script>
Here Is the complete code
HTML
<select id="firstSelect">
<option value="0" selected="selected">None...</option>
<option value="dubai">Dubai</option>
<option value="bora">Bora Bora</option>
<option value="vancouver">Vancouver</option>
<option value="rio">Rio De Janeiro</option>
</select>
<select id="secondSelect">
<option value="0" selected="selected">None...</option>
<option class="location dubai">Resort 1</option>
<option class="location dubai">Resort 2</option>
<option class="location bora">Resort 3</option>
<option class="location bora">Resort 4</option>
<option class="location vancouver">Resort 5</option>
<option class="location rio">Resort 6</option>
</select>
JScript
$(function(){
var conditionalSelect = $("#secondSelect"),
// Save possible options
options = conditionalSelect.children(".location").clone();
$("#firstSelect").change(function(){
var value = $(this).val();
conditionalSelect.children(".location").remove();
options.clone().filter("."+value).appendTo(conditionalSelect);
}).trigger("change");
});
Here is the working example
Change the value of dubai option from Dubai to 'dubai', because it is case sensitive and make it like this:
$(document).ready(function(){
$("#selection").change(function(){
var selection = $(this).val();
if(selection == "none"){
$(".location").show();
}else{
$(".location").not("."+selection).hide();
$("."+selection).show();
}
});
})
YOu can also set a ID to the select like: <select id ="locSelect" class="form-control"> and then use the selection like this $("#locSelect .location").

Categories