JQuery check multiple Selects value - javascript

I have a number of HTML selects like follows on one page:
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>
I want to use Jquery to check each select to ensure the initial value "select" has been changed - eg: another options has been selected. If it hasn't changed I want to change the selects color.
I've tried the following Jquery but it's not fully functional:
if($('select').val() == 'select') {
alert('got one...');
$(this).css({'color' : 'red'});
}
Note: the page has around 25 selects and I'm try to get one piece of jquery to cover all.

You can use change event handler and check for selected value: Check the snippet below
$('select').on('change', function() {
if ($(this).val() == 'select') {
alert('got one...');
$(this).css({
'color': 'red'
});
} else {
$(this).css({
'color': 'initial'
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>

check out this: .val()
$("select").each(function(){
if($(this).val() == "YourDefaulValue"){
$(this).css({'color' : 'red'});
}
});

You have to iterate the elements yourself. Luckily, it's quite simple and a very small change to your code:
$('select').each(function() {
var $this = $(this);
if($this.val() == 'select') {
// probably shouldn't alert here...
// alert('got one...');
$this.css({'color' : 'red'});
}
}

If you need to check all selects you have to test if one or more is "unselected". To achieve this you may do:
$(function () {
$('#resetBtn').on('click', function(e) {
$('select').each(function(index, element) {
$(this).css({'color' : 'black'});
});
});
$('#checkBtn').on('click', function(e) {
$('select').each(function(index, element) {
if (element.selectedIndex == 0) {
alert('got one...');
$(this).css({'color' : 'red'});
}
});
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<button id="checkBtn">Check select</button>
<button id="resetBtn">Reset select</button>
<div>
<h3>Ethnicity</h3>
<select>
<option value="select">Select</option>
<option value="african">African</option>
<option value="africanamerican">African American</option>
<option value="asian">Asian</option>
</select>
</div>

Related

How can I optimize this jquery script? Different classes and same function

I have this jquery function but it is too long for me. Is there any way to make as one jquery change function. I need your help.
$(document).ready(function () {
$('.sub-cat select').change(function () {
if ($('.sub-cat select option:selected').text() == "Other") {
$('.sub-cat .other-category').show();
}
else {
$('.sub-cat .other-category').hide();
}
});
$('.prod-type select').change(function () {
if ($('.prod-type select option:selected').text() == "Other") {
$('.prod-type .other-category').show();
}
else {
$('.prod-type .other-category').hide();
}
});
$('.prod-finnish select').change(function () {
if ($('.prod-finnish select option:selected').text() == "Other") {
$('.prod-finnish .other-category').show();
}
else {
$('.prod-finnish .other-category').hide();
}
});
$('.prod-color select').change(function () {
if ($('.prod-color select option:selected').text() == "Other") {
$('.prod-color .other-category').show();
}
else {
$('.prod-color .other-category').hide();
}
});
$('.prod-included select').change(function () {
if ($('.prod-included select option:selected').text() == "Other") {
$('.prod-included .other-category').show();
}
else {
$('.prod-included .other-category').hide();
}
});
$('.prod-series select').change(function () {
if ($('.prod-series select option:selected').text() == "Other") {
$('.prod-series .other-category').show();
}
else {
$('.prod-series .other-category').hide();
}
});
});
Assign a common class i.e. 'commonClass' to all the parent element i.e. 'sub-cat, prod-included,...', then use various DOM traversal methods to target 'other-category' element.
Learn to use this, element which initiated the event
$('.commonClass select').change(function () {
$(this).closest('.commonClass').find('.other-category').toggle($('option:selected', this).text() == "Other");
});
References
.closest()
.find()
.toggle()
Please check below code. On selection of other option
$(document).ready(function () {
$('select').change(function () {
if($(this).find('option:selected').text() == "other"){
$(this).next().show();
}
else{
$(this).next().hide();
}
});
});
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<div class="sub-cat">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="other">other</option>
</select>
<div class="other-category" style="display: none;">
<p>sub-cat other-category</p>
</div>
</div>
<div class="prod-type">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
<option value="other">other</option>
</select>
<div class="other-category" style="display: none;">
<p>prod-type other-category</p>
</div>
</div>
</body>
</html>
show below div .
You can select several elements at once by separating their class selections with a comma.
$('.sub-cat, .prod-type, .prod-finnish, .prod-color, .prod-included, .prod-series').change(function() {
var $this = $(this); // cache this so we don't have to wrap it twice
$this.toggle($this.find('option:selected').text() == "Other"));
});
It's then just a matter of using .toggle() and passing in a boolean; In our case whether the selected option has "Other" as its text.
This has a really good performance advantage since you only need one event delegate to handle the change event for all the elements in the selector.
You can utilize data-attributes to help you out. I didnt test out this code, but I think something like this could possibly work. Update your HTML to be something like this
<select data-target="sub-cat"></select>
<div class="other-category" data-target="sub-cat"></div>
Followed by this abbreviated jquery code...
$(document).ready(function () {
$('select').change(function() {
var target = $(this).data('target'),
isSelected = $(that).find('option:selected').text() == "Other";
$(this).find('.other-category[data-target="'+target+'"]').toggleClass(isSelected);
})
});
By storing the attributes in a data-attribute, you can easily access that in your javascript code, targeting specific elements much more easily.

2 identical select list, but don't allow the same values selected in them

Here i have the javascript code for my task: https://jsfiddle.net/gckkvLcv/4/
<select id="s1">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select id="s2">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>
I need to translate it to a jQuery version.
On a document load i can see the same values in a select lists. I need to disable that behavior.
Since you're using jQuery that could be done simply like :
$('.tracked_select').on('change', function() {
//Get selected options
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
//Disable the already selected options and enable others
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
});
Hope this helps.
trigger_chane();
$('.tracked_select').on('change', function() {
trigger_chane();
});
function trigger_chane(){
var selected_options = $('.tracked_select').map(function(){
return this.value
}).get();
$('.tracked_select option').each(function(index) {
$(this).prop('disabled', $.inArray($(this).val(), selected_options) != -1);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="tracked_select">
<option selected="selected">USD</option>
<option>KZT</option>
<option>EUR</option>
</select>
<select class="tracked_select">
<option>USD</option>
<option selected="selected">KZT</option>
<option>EUR</option>
</select>

Check whether both of the multiselect dropdown is selected

i am creating two dropsdowns like this
var drp_nt = $('<select />', {
'id' : 'drp_' + nt,
'name' : 'drp_' + nt+'[]',
on: {
change: check_data
},
'multiple': true});
var drp_cnt = $('<select />', {
'id' : 'drp_' + cnt,
'name' : 'drp_' + cnt+'[]',
on: {
change: check_data
},
'multiple': true});
Now i am defining the check_data_function like this
function check_data()
{
if($("select option:selected").length==2)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
I want to enable a button when both of the dropdown has some of the options selected.
in the above fragment of the code, the problem is, if i select 2 options from dropdown drp_nt, and select no option from drp_cnt, then also the alert 'Two Dropdown Selected' is taking place.
I want to have the alert 'Two Dropdown Selected' take place when both of the dropdowns will have some options selected. If one is having something selected while the other one don't, then the alert 'Two Dropdown Selected' won't take place
How can i achieve this?
This will do the trick:
function check_data() {
if ($('select option:selected').parent().length == 2) {
alert('Two Dropdown Selected');
}
}
The idea is that you still select selected options, but then you get their parent select elements and verify that there are exactly two of them.
Check the demo below.
$('select').change(check_data);
function check_data() {
if ($('select option:selected').parent().length == 2) {
alert('Two Dropdown Selected');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
<option>Text 4</option>
</select>
<select multiple>
<option>Text 1</option>
<option>Text 2</option>
<option>Text 3</option>
<option>Text 4</option>
</select>
you are selecting both dropdown in jquery using select
**
function check_data()
{
if($("select option:selected").length==2)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
**
$('select') will select both dropdown. So when you check in jquery, after you selected two in one drop down, this will give you result as two selected. So you need to check like following
function check_data()
{
if($("#id1 option:selected").length>1 && $("#id2 option:selected").length>1)
alert('Two Dropdown Selected');
else
alert('select any one of the option from both dropdown');
}
You can do this by filtering the list of selects so that you get only those with options selected and then check the length
$(function(){
$(document).on('change','select',function(){
var selectsWithOptionsSelected = $('select').filter(function(){
return $('option:selected',this).length>0;
});
alert(selectsWithOptionsSelected.length);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select rows="3" multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<select rows=3 multiple>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
You may want to fiddle with the selectors to only target the select instances you're interested in, for example you could give them a class and use that in both selectors (select.myClassName)
Use jQuery().each
function check_data()
{
var counter = 0;
jQuery('select').each(function() {
if(jQuery(this).find('option:selected').length == 2) {
counter++;
}
});
if(counter == jQuery('select').length)
alert('Two Dropdown Selected');
else
alert($("select option:selected").length);
}
Here's another alternative just for giggles:
function check_data() {
$('select:has(option:selected)').length > 1 && alert('Foo');
}

jquery change function hide and show div

have this code, i want to convert it to be able to allow the user to pick ANY possible select and have div [id='setprice'] show up or something to that effect. currently i have 4 options, but it could be up to 10+ depends on how many are in the database. but it shouldn't matter, i just want which ever gets selected to open the setprice div. Thanks.
$("#category").change(function () {
$("#setprice").hide();
if ($(this).val() == "cow") { $("[id='setprice']").show(); }
else if ($(this).val() == "dog") { $("[id='setprice']").show(); }
else if ($(this).val() == "monkey") { $("[id='setprice']").show(); }
else if ($(this).val() == "kungfoo") { $("[id='setprice']").show(); }
});
HTML
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice'>this is hidden onload, then shows on any #category selection</div>
Seems to be alot of cofusion in what im asking, These options i've given are random names, the categories that are going to be loaded, are from a database and more could be added depending how it expands, so i want the script to not show div=setprice, but when anything gets selected in #category to open setprice.
You will need to call the function only when the value of the select box isn't empty.
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
Here is a working fiddle.
This is the cleanest you will get this.
DEMO
$("#category").change(function () {
$("#setprice").toggle(!!this.value);
});
The $("#setprice").toggle(!!this.value); is just a way to use a boolean inside the .toggle() method,
otherwise you do it equally like:
var $setPriceEl = $("#setprice");
$("#category").change(function () {
$setPriceEl.hide(); // hide by default
if(this.value) $setPriceEl.show(); // show only if has value
});
or even:
$("#category").change(function () {
$("#setprice")[this.value ? "show" : "hide" ]();
});
Please find the answer below ...
HTML :
<select id="category">
<option value=''>Select</option>
<option value='cow'>Cow</option>
<option value='dog'>Dog</option>
<option value='monkey'>Monkey</option>
<option value='kungfoo'>kungfoo</option>
</select>
<div id='setprice' style="display:none;">this is hidden onload,
then shows on any #category selection</div>
JQUERY :
$(document).ready(function(){
$("#category").change(function() {
$("#category option:selected" ).each(function() {
var str = $( this ).text();
if(str == "Select"){
$("#setprice").hide();
}else{
$("#setprice").show();
$("#setprice").text(str);
}
});
}).trigger("change");
});

Disable select input if option value exists

I want to disable the select box if Free Shipping is available.
<select name="shipping_method" id="shipping_method">
<option value="">Select shipping</option>
<option value="free_shipping">Free Shipping</option>
<option value="international_delivery">International: $30.00</option>
</select>
I've tried this (without knowing if it would work):
$(document).ready(function(){
if($("option").val() == "free_shipping") {
$("select").prop("disabled");
}
});
And then assuming on form submit:
$(document).ready(function(){
$("form").submit(function() {
$("select", this).prop("disabled", false);
});
});
You can use $.has
$('#shipping_method').has('option[value="free_shipping"]').prop("disabled", true);
Demo: Fiddle
select the select
$('#shipping_method').change(function(){
var j = $(this);
if(j.val() == 'free_shipping') {
j.attr('disabled', true);
}
else {
j.removeAttr('disabled');
}
}).trigger('change');

Categories