How to check if drop-down is selected in JavaScript - javascript

I have a validator function looping through to check and see if all inputs have been filled out, but I also need to check if the dropdown's have been selected as well. I would like to write that into the same function.
function validateSave (){
// reset status
var good = true
$('.errormessage-left').removeClass('active-left')
$('input').removeClass("warning")
$('input').each(function(){
if ($(this).val() == "") {
console.log("found an empty");
good = false
$(this).addClass("warning")
$('.errormessage-left').addClass('active-left'),
$('.modal').addClass('modal-active');
}
})
console.log(good)
return good
}
What's the best way to go about this?

You can use val() on a dropdown (<select> element) just like an input element, so just include it in your selector
$('input, select').each(function(){

You can do this :
Assuming the first element is :"please choose..."
if ($(".myDDL").get(0).selectedIndex>0)...
or
if ($(".myDDL").prop('selectedIndex')>0)...

Try this:
$('input').each(function(){
if($(this).prop('selected') == true){
// selected item
}
});

Assuming your HTML looks something like this:
<input type="text" name="whatever">
<select>
<option value="">Choose One...</option>
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
<option value="choice3">Choice 3</option>
</select>
Then your jQuery can figure it out like this
$('input, select').each(function(){
if($(this).val() == ''){
alert('Cannot be blank!');
}
else{
//proceed
}
}

you should be able to add this to your loop:
if ($(this).prop('type')=='select-one'){
if ($(this).prop('selectedIndex')==0){
console.log("found an empty");
good = false
$(this).addClass("warning")
$('.errormessage-left').addClass('active-left'),
$('.modal').addClass('modal-active');
}
}

Related

Hide either one of the option by selected value in javascript?

I have a form with two identical select lists like follows:
<select id="system" name="system[1][1]">
Option 1
Option 2
Option 3
</select>
<select id="system" name="system[1][2]">
Option 1
Option 2
Option 3
</select>
I want the user select either one of this select option2. If user choose option2 in first select then hide the option2 in second select and vice versa.
Example:
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
Which I think is bit of messy. Is it any elegant way that I can achieve this in Javascript or Jquery?
Thanks
Try following code :
<select id="system" name="system[1][1]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<select id="system" name="system[1][2]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
jQuery :
jQuery('select').change(function(e){
var value = $(this).val();
var selectboxId = $(this).attr('name');
jQuery('select option').show();
if(selectboxId == 'system[1][1]') {
jQuery('select[name="system[1][2]"]').find('option[value="'+value+'"]').hide();
} else if(selectboxId == 'system[1][2]') {
jQuery('select[name="system[1][1]"]').find('option[value="'+value+'"]').hide();
}
});
Try this Check out this fiddle
I hope this is what ur looking for ?
Html
<select id="system1" name="system[1][1]">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="system2" name="system[1][2]">
<option value="1">1</option>
<option value="2">2</option>
</select>
Jquery
$(document).ready(function(){
$('select').change(function(){
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select1.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select2.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
});
});
I'd suggest the following approach (note the change of id properties, this is not optional, it's required in order to have valid HTML):
// cache the relevant <select> elements, here we use
// a CSS attribute-selector to get those <select>
// elements whose id attribute begins with 'system':
var selectElements = $('select[id^=system]');
// binding the anonymous function as the event-handler
// for the 'change' event, using the on() method:
selectElements.on('change', function() {
// we retrieve the index of the selected option from
// the changed <select> element:
var chosen = this.selectedIndex;
// we hide all the previously-selected <select> elements:
selectElements.hide()
// we find the <select> element at the same index as
// the chosen <option>:
.eq(chosen)
// and then show that element:
.show();
})
/* This is just to give a visual cue to
show which of the elements is currently
visible on the page: */
#system1 {
box-shadow: 0 0 1em fuchsia;
}
#system2 {
box-shadow: 0 0 1em limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="system1" name="system[1][1]">
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="system2" name="system[1][2]">
<option>Option 1</option>
<option>Option 2</option>
</select>
JS Fiddle demo.
References:
CSS:
Attribute selectors.
JavaScript:
HTMLSelectElement.selectedIndex.
jQuery:
on().
although there are some answers, here's what i came up with:
$("select").on("change", function() { //on any change event in all selects
var currentSelection = $(this); //save the used select box
//then take all selects, except the activated one, take the 'option' childs and iterate through them
$("select").not(currentSelection).find("option").each(function() {
if ($(this).val() == currentSelection.val()) //if option value = chosen value
$(this).hide(); //hide it
else //if not
$(this).show(); //show it (to reshow already hidden elements)
});
});
this works with endless options! but as soon, as you have more then 2 selects, you have to rework the 'show' part of this script...
here's a working fiddle: https://jsfiddle.net/usksL955/1/

select on change jquery not working

I have the following code that does not seem to work:
$('.chosen-select').on('change', function() {
if ('.chosen-select'.value == '1') {
$("#tips").html("the color that you want to add.");
} else if ('.chosen-select'.value == '2') {
$("#tips").html("the text that you want to add.");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
My web browser console is not giving me any error. The code is suppose to change the html of the div based on changing the select option value.
This '.chosen-select'.value won't work as it's neither a valid jQuery expression nor JavaScript. Instead use $('.chosen-select').val(), this.value or $(this).val().
jsFiddle example
Use if($(this).val() == '1') { not as if('.chosen-select'.value == '1')
$(function() {
$('.chosen-select').on('change', function() {
if($(this).val() == '1') {$("#tips").html( "the color that you want to add.");}
else if($(this).val() == '2') {$("#tips").html( "the text that you want to add.");}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="tips"></div>
<select class="chosen-select" style="width:290px;" name="option">
<option value="1">change background colour</option>
<option value="2">insert text</option>
<option value="3">insert arrow</option>
</select>
The below expression doesn't yield the results you want:
'.chosen-select'.value
It attempts to access the value property of a String object, which is undefined, because strings don't have such properties.
Within the change event handler function, you can make good use of the fact that this references the <select> element:
var selectedValue = this.value; // get value from select element
Alternatively, use jQuery's .val() function to get the value:
var selectedValue = $(this).val();

Select a DropDown by values with jquery

<select id="id_deals-1-deal_template" name="deals-1-deal_template">
<option selected="selected" value="">---------</option>
<option value="1" selected="selected">Pear</option>
<option value="2">Apple</option>
<option value="4">Melon</option>
</select>
In order to select Melon I have to do this:
$('#id_deals-1-deal_template>option:eq(3)').prop('selected', true);
But I would rather have to select the primary key that is 4 in this case.
Hence is it possible to select a dropdown by its value rather than sequence?
Try using .val which can be a setter or getter based on the argument. Below is a setter..
$('#id_deals-1-deal_template').val(4);
$('#id_deals-1-deal_template').val(4);
Here is a demo:
http://jsfiddle.net/M3UBc/
use
$('#id_deals-1-deal_template').val(4);
or
$('#id_deals-1-deal_template').val('Melon');
Select by option name
$("#id_deals-1-deal_template option").each(function() {
if($(this).text() == 'Melon') {
$(this).attr('selected', 'selected');
}
});
Select by value id
$("#id_deals-1-deal_template option").each(function() {
if($(this).text() == '4') {
$(this).attr('selected', 'selected');
}
});

Jquery + form : no validation if val is null

My form is composed of chained select. When I arrive at last, I submit it, if and only if all the select are filled.
Here is my function.
$("#form_maps select").each(function(index, el){
var val = $(el).val();
if(val === null)
{
alert('error message');
return false;
}
else
{
$('#form_maps').submit();
}
});
When I do my testing, an error is generated (the alert), but after a few seconds (I would say 2 or 3), the form is still submitted.
here is my html form
<form id="form_maps" method="post" style="height: 100px;">
<select name="select_0" id="select_0">
<option value="c_5" class="c_4">Excavateur</option>
<option value="c_11" class="c_4">Compaction</option>
</select>
<select name="select_1" id="select_1">
<option value="c_6" class="c_5">série 100</option>
<option value="c_9" class="c_5">série 200</option>
</select>
<select name="select_2" id="select_2">
<option value="c_7" class="c_6">above</option>
<option value="c_10" class="c_6">thru</option>
</select>
<select name="select_3" id="select_3">
<option value="c_8" class="c_7">système hydraulique</option>
<option value="c_12" class="c_7">système électrique</option>
</select>
</form>
What is my problem please? Thank you for your assistance to come.
I guess your form is submitted because one of the your selects has a valid value and the return false isn't stopping the loop. If you want to prevent to submit to form unless all selects do have a valid value, then I would suggest to use a boolean that will be set to false if one of the selects is invalid.
Something like this:
var canSubmit = true;
$("#form_maps select").each(function(index, el){
var val = $(el).val();
if(val === null)
{
alert('error message');
canSubmit = false;
}
});
if(canSubmit) {
$('#form_maps').submit();
}
There is a triple is so that might be something to begin with...

Selecting an option in a dropdown menu based on node value?

Is there a way to set the value of a dropdown list in jQuery (or Javascript) based on the node value?
<select name="ddlProperty">
<option value="1" selected="selected"></option>
<option value="2">Animal Kingdom</option>
<option value="3">Epcot</option>
<option value="4">Hollywood Studios</option>
<option value="5">Magic Kingdom</option>
<option value="6">Downtown Disney</option>
</select>
I'd need to set the option of Magic Kingdom, so something like:
$("#ddlLocation").val("Magic Kingdom")
So that Magic Kingdom would become the selected item, that doesn't work as expected. Any ideas?
If you can use the value (not text!), do that using .val():
$("#ddlProperty").val("5");
If you don't have that, use .filter(), .text() and .attr() to find and set the selected <option>, like this:
$("#ddlProperty option").filter(function() {
return $(this).text() === "Magic Kingdom"
}).attr('selected', true);
Something like:
var box = document.getElementById('box'),
options = box.options;
for(var i = 0; i < options.length; ++i){
if(options[i].text == val){
options[i].selected = true;
}
}
$("#ddlProperty > option").each(function(i, elem) {
if($(elem).text() == "Magic Kingdom") {
$('#ddlProperty').val(elem.value);
return false;
}
});
And next time please make a proper example where the element has an id and that ID matches the ID in your code. I've spent about 5 minutes checking for an error until I've noticed the ID being different...
http://jsbin.com/ikibi3/2
myselect="Magic Kingdom";
$("select[name='ddlProperty'] option").each(function() {
if($(this).text() == myselect) {
$(this).attr('selected', true);
} else {
$(this).attr('selected', false);
}
});

Categories

Resources