Jquery autoselect select options of the same class - javascript

I have three select options drop down menus with class 'film', but the values are linked so that I have to select all to get result. In my case the HTML code looks like this:
<select name="sc30" id="sc30" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" onchange="autoSelect()" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>
If I select White option from id="sc30" the other two select options must take a value "---". Or if I select option Gold glossy from id="sc100" the other options from this class 'film' must take this value ---
I think that I have to use jQuery each() method. But how to check if any select option is selected and make other select options from this class with "---" value without already selected option. The code below don't work properly.
function autoSelect() {
$('.dummy').each(function(index, value){
if($(this).val() != '---') {
$(".dummy").val($(".dummy option:eq(1)").val());
}
});
}

$(function() {
$('select.film').on('change', function() {
var cb = $(this);
if (2 === cb.prop('selectedIndex')) {
$('select.film').not(cb).prop('selectedIndex', 1);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="sc30" id="sc30" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>White</option>
<option>Black</option>
</select>
<select name="ij10" id="ij10" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Red</option>
<option>Green</option>
<option>Gold</option>
</select>
<select name="sc100" id="sc100" class="film">
<option>Choose an option...</option>
<option>---</option>
<option>Gold glossy</option>
<option>Silver glossy</option>
</select>

Try this : remove onchange="autoSelect()" from all select boxes and bind change event as shown below and select second option for each select box except the current one for which change event fired -
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
// get selected option for the current select box
var $selected = $(this).find('option:selected');
// if index of selected option is greater than 1,
// it means option is selected.
if($selected.index()>1)
$(this).val($(this).find('option:eq(1)').val());
});
});
});
DEMO

I just remove these two rows code:
var $selected = $(this).find('option:selected');
if($selected.index()>1)
and already is ok!
$(function(){
$('.film').change(function(){
//iterate all other select box except current using `not(this)`
$('.film').not(this).each(function(){
$(this).val($(this).find('option:eq(1)').val());
});
});
});

Related

Add new select with unqiue name onchange of previous select

I have a job that requires several hundred select elements on a page. I want to show each select dynamically as the previous is changed. I have a working version in which I put all the select elements in the markup, and then used a simple function to hide them all and show only the first. Then on change of each select the next is added.
This works just fine, but is obviously not ideal. I don't want to put 500 select items in the markup and hide them all for no reason, and my JS function would be 1500 lines long. Plus that would make me feel silly.
How can I automate this process with JS?
I do not need each select to have a unique id, but I do need each select to have a unique and incremented name. Is this possible? I have a working fiddle.
HTML:
<select name="select-one" class="hidden" id="one">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-two" class="hidden" id="two">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-three" class="hidden" id="three">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
<select name="select-four" class="hidden" id="four">
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
JS:
$(document).ready(function() {
$('.hidden').hide();
$('#one').show();
$('#one').change(function(){
$('#two').show();
});
$('#two').change(function(){
$('#three').show();
});
$('#three').change(function(){
$('#four').show();
});
// and so forth...
});
HTML:
<select class="hidden" id="one" name='name_0'>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
jQuery
$('select').on('change', function() {
$('body').append($(this).clone(true))
})
Result:
Note we are using the overload of the clone() method. This means event handlers and data will be copied along with the elements. So whatever event handler you attached to the original select gets cloned.
If you want to increment the name just use a counter and add the attribute after the clone:
cnt=0;
$('select').on('change', function() {
cnt++
$('body').append($(this).clone(true).attr('name', 'name_' + cnt))
})
My solution:
CSS
.hidden {
display: none;
}
JS
const createSelect = index => `
<select name="select-${index}" class="hidden select" data-index=${index}>
<option value="">not this one</option>
<option value="">pick this one</option>
</select>
`;
$(document).ready(function() {
// Generate 100 selects
for (let i = 0; i < 100; i++) {
$("body").append(createSelect(i));
}
// Show first select
$(`.select[data-index='0']`).show();
$('.select').on('change', function() {
// Store index of a select currently changed
const index = parseInt($(this).attr('data-index'), 10);
// Show next select
$(`.select[data-index='${index + 1}']`).show();
});
});

I have two select boxes. I want to enable second select box only if i click a particular option in first select box [duplicate]

I have two dynamic dropdowns but both dropdown's value and options are same. What I want that if user select 'apple' from first dropdown then the second dropdown's apple option will be disabled (using javascript). In short user can not select same value from both.
//first drop down
<select name="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
//second dropdown
<select name="fruit2">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
I have tried with jQuery:
function witness()
{
var op=document.getElementById("witness1").value;
$('option[value='+op+']').prop('disabled', true);
}
But with this both dropdown's value are disabled and if I select mango then apple will not enabled it remains disabled. I know I did not pass id so both dropdown value are disabled but where should i pass ?
If user select apple then in second dropdown apple will be disabled, I want to do this using Javascript or jQuery.
Fiddle: https://jsfiddle.net/3pfo1d1f/
To get the functionality you're after, you need to hook into the change event on the first dropdown, in order to disable the matching element in the second drop-down.
I also initialised the first element in the second dropdown as disabled ( as this chosen by default in the first dropdown)
Used jquery as you are:
HTML:
<!-- first dropdown -->
<select id="fruit1">
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<br /> <br />
<!-- second dropdown -->
<select id="fruit2">
<option value="1" disabled>Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
$('#fruit1').on( "change", function() {
var op = $( this ).val();
$('#fruit2 option').prop('disabled', false);
$('#fruit2 option[value='+op+']').prop('disabled', true);
});
This should still work, no matter how many options you have in both the dropdowns
Try this out:
HTML:
<select id='fruit1' onchange="witness();">
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
<select id='fruit2'>
<option selected></option>
<option value="1">Apple</option>
<option value="2">Mango</option>
</select>
JQuery:
function witness(){
$("#fruit2 option").each(function(){
if($("#fruit1 option:selected").val() == $(this).val())
$(this).attr("disabled", "disabled");
else
$(this).removeAttr("disabled");
});
}
You can see a working exemple here:
https://jsfiddle.net/mqjxL4n0/
<select name="firstselect" id="firstselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<select name="secondselect" id="secondselect">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
</select>
<script>
$(document).ready(function(){
$('#firstselect').change(function(){
var firstselected = $(this).val();
if(firstselected ){
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
if($(this).val()==firstselected )
$(this).prop('disabled', true);
});
}
else {
$('#secondselect option').each(function(){
$(this).prop('disabled', false);
});
}
});
});
</script>

jquery get current selected value from multiple

I have select drop down where I use array sign in name like
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Now I need to get current (last) selected value from drop down on change event.
What I have tried so far is
var clicked = $('#service_id option:selected').last().val();
alert(clicked);
//also tried as
//$(this).closest('select').find('option').filter(':selected:last').val();
//and this is tried too
// $(this).val();
// this.value;
All these giving me wrong value when multi select.
What I need
If select four then next select one it should alert 1 (remember when multi selection).
If select three and then next select four then it should alert 4
In brief ALWAYS need Clicked option's value even in multi select
** Not possible to remove array sign from name services[]
There is no native way, but you could save the order of the options clicked, then get the last.
ie, against a data attribute on the select:-
$('#service_id option').click(function() {
var values = $(this).parent().data('values') || [];
var index = values.indexOf(this.value);
index >= 0 ? values.splice(index, 1) : values.push(this.value);
$(this).parent().data('values', values);
});
$('#service_id').click(function() {
var values = $(this).data('values');
console.log(values);
var last = values[values.length - 1];
console.log('last:' + last);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
Try this demo
$(function(){
var last_selected;
$("#service_id option").click(function(){
if($(this).is(":selected")) {
last_selected = $(this).attr('value');
}
$("#result").html(last_selected);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>
<p>Last selected : <span id="result"></span></p>
So you just want to get the last selected element?
Just create a variable to store the last selected element in each option click as shown by this demo:
var currLast = null;
$('#service_id').children().on('click', function(){
var val = $(this).val();
if (currLast === val) { // do nothing if current selected is the same elem
return;
}
currLast = val;
console.log(currLast)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="services[]" id="service_id" multiple>
<option value="4">four</option>
<option value="1">one</option>
<option value="3">three</option>
</select>

jquery target selected option in dropdown

<select id="dropdown">
<option value="200" selected>AMD Athlon 7x</option>
<option value="300">Core i7</option>
<option value="400">Core i5</option>
</select>
<select id="dropdown">
<option value="250" selected>GTX 560 ti</option>
<option value="350">GRX 680</option>
<option value="40">ATI 6870</option>
</select>
Im calculating price of final product base on selected value.
$('select').change(function() {
});
I need this function to remove selected attribute and assign it to selected option but i dont know how to target newly selected option.
$('select').change(function() {
$(this).children(':selected').attr('selected', true);
});
But i don't understand why you need this :)
Like this:
$('select :selected').change(function(){
//more code
});
To grab the selected option, your drop down lists should first have unique IDs
<select id="dropdown1">
<option value="200" selected>AMD Athlon 7x</option>
<option value="300">Core i7</option>
<option value="400">Core i5</option>
</select>
<select id="dropdown2">
<option value="250" selected>GTX 560 ti</option>
<option value="350">GRX 680</option>
<option value="40">ATI 6870</option>
</select>
$("#dropdown1 option:selected");
Now, that said, your drop down menu will change the first drop down selected option for you automatically.
In addition, if you want to grab the value of the selected option when it is selected, use .val()
$('select :selected').change(function(){
$("#dropdown1 option:selected").val();
});
The above examples have a syntax error. The following is incorrect (I tried it, it doesn't work):
$('select :selected').change(function(){
Below is from the jQuery site example code (I tried it too, and it does work):
<select name="garden" multiple="multiple">
<option>Flowers</option>
<option selected="selected">Shrubs</option>
<option>Trees</option>
<option selected="selected">Bushes</option>
<option>Grass</option>
<option>Dirt</option>
</select>
/* ... */
<script>
$( "select" ).change(function() { // <<<<< this is the correct syntax
var str = "";
$( "select option:selected" ).each(function() {
str += $( this ).text() + " ";
});
})
</script>

Disable Drop Down Options Once Chosen In Other Dropdown

I have 12 drop downs input areas, 1 for each of the months of the year. Each drop down has the choice of the same 24 options.
I need to make it so that, for example, if in the January drop down box you chose option #4, that option #4 cannot be selected in any of the other drop down menus. It would still be in the drop down, but would just be disabled.
This would have an ajax trigger to check the value against the other drop downs and dynamically change the other drop down menus.
Is there a loop I can do to check and disable these values dynamically without having to make a lot of if statements?
You can use jQuery to find the option element in all other dropdowns (in my example, designated by a certain class...and can easily be changed to another selector - I thought the selector "select" was too broad), and then disable the actual option element by using .prop("disabled", true). But it's a little more tricky than this, as you need to keep track of the previous selected value to enable the dropdown again when a different value is chosen. Here's an example that will hopefully help:
http://jsfiddle.net/p5Arj/
$(document).ready(function () {
$(".test").each(function () {
var $self = $(this);
$self.data("previous_value", $self.val());
});
$(".test").on("change", function () {
var $self = $(this);
var prev_value = $self.data("previous_value");
var cur_value = $self.val();
$(".test").not($self).find("option").filter(function () {
return $(this).val() == prev_value;
}).prop("disabled", false);
if (cur_value != "") {
$(".test").not($self).find("option").filter(function () {
return $(this).val() == cur_value;
}).prop("disabled", true);
$self.data("previous_value", cur_value);
}
});
});
So this disables all other dropdowns' same options when you choose one, and makes sure that when you choose another, the previous one is enabled in all other dropdowns. For example, choose "3" in the first dropdown...look at the second dropdown - see that "3" is disabled...go back to the first dropdown and choose "1"...look at the second dropdown - see that "3" is enabled again but "1" is disabled. That's what the use of .data is for in my code.
Of course, you can replace the use of value with selectedIndex if you are 100% sure that all of the options will be the same for each select in question.
http://jsfiddle.net/Rk5e9/9/
Only about 10 lines, and no ajax!
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="unique-value">
<option value="-1" selected="selected">Default</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
Script:
$(document).ready(function(){
$('.unique-value').focus(function(){
var val = $(this).val();
$(this).attr('data-current-value', val);
});
$('.unique-value').change(function(){
var val = $(this).val();
if(val != -1)
$('.unique-value option[value=' + val + ']').attr('disabled', 'disabled');
var oldval = $(this).attr('data-current-value');
$('.unique-value option[value=' + oldval + ']').removeAttr('disabled');
});
});​
I think this would be the shortest solution:
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
<select class="select-value">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
and the jquery code:
$(document).on('change', '.select-attendee', function(){
$current=$(this);
$(".select-attendee").not($current).children("option[value='"+$current.val()+"']").attr('disabled', "disabled");
});
Assuming you had a dropdown for each month, and an option for each week.
<select class="month" id="october">
<option class="week" value="week1">Week One</option>
<option class="week" value="week2">Week Two</option>
</select>
Lets say you select a week, and you listen for the event.
$(".month").change(function(event) {
// Get the week just selected.
var selectedWeek = $(this).children(".week:selected").val();
// Enabled all weeks before disabling the selected week.
$("option.week").removeAttr("disabled");
// Disable all week options matching this selection.
$("option.week[value="+selectedWeek+"]").attr("disabled", "disabled");
});

Categories

Resources