Jquery select option val - javascript

im working in a project that i will have about 10 select boxes with same class and i want to check if ALL of selected boxes are selected with jquery. Here is my html code
<form class="form-horizontal" action="analysis.php" method="post" id="mobileform" >
<select class="form-control selectx" name="phone1">
<option value="" selected>Select phone</option>
<option value="iphone6" selected>Iphone 6</option>
<option value="galaxys5" selected>Galaxy S5</option>
</select>
<select class="form-control selectx" name="phone2">
<option value="" selected>Select phone</option>
<option value="iphone6" selected>Iphone 6</option>
<option value="galaxys5" selected>Galaxy S5</option>
</select>
<button type="submit" name="submit" class="btn btn-success" id="submit"> Submit !</button><br>
And here is my jquery
$(document).ready(function() {
$('form').submit(function(event) {
$(".selectx option:selected").each(function()
{
if($(this).val() === "") {
$('#selecterror').fadeIn(300);
event.preventDefault();
}else{
$('#selecterror').hide();
}
});
});
});
But it doesnt work if you example in 1st selectbox with name phone1 you dont select anything and in selectbox with name phone2 you select a phone.
Sorry for my english

In your case, both select options have to be empty for the validation. You can use .filter to see if any of the select options is empty:
$('form').submit(function(event) {
var empty = $(".selectx option:selected").filter(
function() {
return $(this).val() == "";
});
if(empty.length) {
$('#selecterror').fadeIn(300);
event.preventDefault();
}else{
$('#selecterror').hide();
}
});
DEMO: https://jsfiddle.net/hptqq1tL/

Related

Function to check option list validation not working

I have a select option list for my form and I want to make sure the user has selected one of the options. My function logic implies that if the user keeps the dropdown on the default option, an alert will pop up prompting them to change it. However, no alert shows up whatsoever. What am I doing wrong?
function isOption(form) {
var type = form.getElementByID("pastimetype")
var selectedValue = type.options[type.selectedIndex].value;
if (selectedValue == "selectpastime") {
alert("Please select a pastime.")
return false
}
return true
}
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="selectpastime">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
you need to add the function to the submit event of the form.
you misspelled getElementById
no need to use form.getElementById
easier to get the value using select.value
use preventDefault instead of returning true/false
Also
function isOption(e) {
var sel = document.getElementById("pastimetype");
var selectedValue = sel.value;
if (selectedValue == "") { // I removed the value from the "Please select"
alert("Please select a pastime.")
e.preventDefault(); // stop submission
}
}
window.addEventListener("load",function() {
document.getElementById("form1").addEventListener("submit",isOption)
})
<form id="form1">
<p><label for="pastime"> Favourite pastime: </label>
<select name="pastime" select id="pastimetype">
<option value="">---Please choose an option---</option>
<option value="surfingtheweb">Surfing the Web</option>
<option value="playingsport">Playing Sport</option>
<option value="listeningtomusic">Listening to Music</option>
<option value="watchingtv">Watching TV</option>
<option value="playinggames">Playing Games</option>
<option value="communityservice">Community Service</option>
<option value="daydreaming">Daydreaming</option>
<option value="reading">Reading</option>
<option value="meditation">Meditation</option>
</select>
</p>
<input type="submit" />
</form>

I Retained Select Option Value on First Dropdown but not Second or Third

I have 3 form select drop downs and have successfully retained the first select value after page loads, but am unable to get the second and third select values to be retained.
I'm using JavaScript and Jquery only for this.
I've tried over and over and finally got to bring my code here to see if someone more advanced can point out what I'm not doing correctly.
<form id="form">
<select id="select0" type="text">
<option type="text" value="" >make</option>
<option type="text" value="ford" >ford</option>
</select>
<select id="select1" type="text">
<option type="text" value="" >model</option>
<option type="text" value="mustang" >mustang</option>
</select>
<select id="select2" type="text">
<option type="text" value="">year</option>
<option type="text" value="1967" >1967</option>
</select>
<input type="submit" value="go">
</form>the
// JavaScript
var storeMake = sessionStorage.getItem("themake");
var storeModel = sessionStorage.getItem("themodel");
var storeYear = sessionStorage.getItem("theyear");
var make = $("#form #select0");
var model = $("#form #select1");
var year = $("#form #select2");
if(storeMake != undefined || storeMake != null){
make.find(":selected").removeAttr("selected");
make.find("option").each(function () {
if ($(this).val() == storeMake) {
$(this).attr("selected", true);
}
});
}
if(storeModel != undefined || storeModel != null){
model.find(":selected").removeAttr("selected");
model.find("option").each(function () {
if ($(this).val() == storeModel) {
$(this).attr("selected", true);
}
});
}
if(storeYear != undefined || storeYear != null){
year.find(":selected").removeAttr("selected");
year.find("option").each(function () {
if ($(this).val() == storeYear) {
$(this).attr("selected", true);
}
});
}
make.change(function () {
sessionStorage.setItem("themake", make.val());
});
model.change(function () {
sessionStorage.setItem("themodel", model.val());
});
year.change(function () {
sessionStorage.setItem("theyear", year.val());
});
The jQuery .val() method can be used to set the value of a select. This will replace each if statement.
Try the code below. The snippet will not work in Stack Overflow because sessionStorage is disabled.
var storeMake = sessionStorage.getItem("themake"),
storeModel = sessionStorage.getItem("themodel"),
storeYear = sessionStorage.getItem("theyear");
$("#select0").val(storeMake).change(function () {
sessionStorage.setItem("themake", $(this).val());
});
$("#select1").val(storeModel).change(function () {
sessionStorage.setItem("themodel", $(this).val());
});
$("#select2").val(storeYear).change(function () {
sessionStorage.setItem("theyear", $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<select id="select0">
<option value="">make</option>
<option value="ford">ford</option>
</select>
<select id="select1">
<option value="">model</option>
<option value="mustang">mustang</option>
</select>
<select id="select2">
<option value="">year</option>
<option value="1967">1967</option>
</select>
<input type="submit" value="go">
</form>
A few added notes:
The type attribute is not needed on select or option elements.
$("#form #select0") can updated to $("#select0") since the id will be unique. Same with select1 and select2.

show hide div based on select option value jQuery

I have a select list with value 0,1,2,3,4,5,6,7 .On select with value 0 and 1 I want to show a div, but on select with value 2,3,4,5,6,7 I want to hide that div.The code I have right now is below
HTML
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
jQuery
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function(){
$('.rel_status').change(function(){
if($('.rel_status').val() == '2','3','4','5','6','7') {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
The code actually works when I put
.val() == '2')
instead of
.val() == '2','3','4','5','6','7')
But then I cant show the div for other values
You can do it like this if ($.inArray($(this).val(), "2,3,4,5,6,7") == -1) {
Demo
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function() {
$('.rel_status').change(function() {
if ($.inArray($(this).val(), "2,3,4,5,6,7") == -1) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
use this it will works
$('.rel_status').change(function(){
if($('.rel_status').val() < 2) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function(){
$('.rel_status').change(function(){
if($('.rel_status').val() < 2) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
That's not a valid way of comparing one value to many others.
if($('.rel_status').val() == '2','3','4','5','6','7')
Use a logic OR Operator instead:
if($('.rel_status').val() == '0' || $('.rel_status').val() = '1') {
$('.rel_part').hide();
} else {
$('.rel_part').show();
}
Notice, that I switched the cases in the if clause so it's less code to write.
The problem is this is not a valid way to use , in Javascript, because you will end up validating if($('.rel_status').val() == '7') { instead.
You can change the code into this
if($.inArray($('.rel_status').val(), ['2','3','4','5','6','7']) != -1) {
and it should work.
Hope it helps!

How to change a border color of html select tag if value is empty or 0

I have 4 select tag with class name select2 assigned to it. I want to make the border turn to red if there's no selected options or has an value equal to empty or 0. I've tried to add class using jquery but it makes all select.select2 border turns red.
Style
<style>
.errorType {
border-color: #F00 !important;
}
</style>
HTML
<select name="category" class="form-control select2" id="category" onChange="search_Operator(this.value)">
<option value="0"> Select Operator Category</option>
<option value="1">one</option> <option value="2"> two</option>
</select>
<select name="operatorName" class="form-control select2" id="operatorName" onChange="">
<option value="0"> Select operator Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="regionName" class="form-control select2" id="regionName">
<option value="0"> Select region Name</option>
<option value="1">one</option>
<option value="2"> two</option>
</select>
<select name="type" class="form-control select2" id="type">
<option value="0"> Select type </option>
</select>
JQUERY
$(function () {
$(".select2").select2();
});
$(".select2-selection").addClass('errorType');
Any idea?
Thanks in advance.
I've attached a function to the click event of the submit button, in order to check the value of every select element on the page:
$(function () {
$('.form-control-select2').select2();
$('#submit_btn').on('click', function(){
var submit_form = true;
$(".form-control-select2").each(function(){
var selected_value = $(this).val();
if (selected_value==0 || selected_value=='') {
$(this).next().find('.select2-selection').addClass('errorType');
submit_form = false;
} else {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
return submit_form;
});
});
Fiddle here: https://jsfiddle.net/64a41thz/21/.
Also, if you want to remove the red border when valid selection is made, add the following code:
$('.form-control-select2').on('change', function(){
if ($(this).val()!=0 && $(this).val()!='') {
$(this).next().find('.select2-selection').removeClass('errorType');
}
});
Fiddle here: https://jsfiddle.net/64a41thz/24/.
This does the trick. You just need to replace #yourButton with the actual ID you use.
$(document).on("click", "#yourButton", function() {
$(".select2").each(function(index, element) {
$(element).removeClass("errorType");
if ($(element).val() === "0") {
$(element).addClass("errorType");
}
});
});
Put your select tag inside a form with an id="submit" as shown
<form class="" action="" method="post" id="submit">
and add a button below the 4 select tags with this attribute
onclick="return submit_form('form#submit')"
the button should be like this,
<button type="button" class="btn btn-default" onclick="return submit_form('form#submit')">Submit</button>
In your jquery
function submit_form (form_id) {
$(form_id).find('select[name]').each(function (index, node) {
if (node.value == 0) {
var id = "select#" + node.id;
$(id).addClass('errorType');
}
});
}
This will search select tag with name as attribute, if found, it will get the value of the name and check of its empty or not. If found empty it will add new class that turns that select tag into a red border.
Hope this will help

Display HTML while <option> is viable selection

I have something like the below:
<select name="blah">
<option disabled="disabled" selected="selected">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select><br/>
<input type="submit" value="Submit"/>
I want it such that the submit button only appears if the user has selected an option with value >= 1 So on page load it will not display the submit button because the currently selected option has no value, but the moment a user selects a valid option, the submit button appears.
Is this something that can be accomplished with JS/JQ?
If you don't want to display submit button when page loads then add below css
input[type=submit] {display:none;}
To show submit button on value changes try below js code
$(function(){
$('select').change(function(){
var value = parseInt($(this).val().replace(/[^0-9-]/,""),10)
if(value >= 1)
{
$('input[type=submit]').show();
}
});
});;
Working Demo
Try following code in java script
function isSelected() {
var value =document.getElementById("blah").selectedIndex;
if(value >='1'){
document.getElementById('btnSubmit').style.display='block';
}else{
document.getElementById('btnSubmit').style.display='none';
}
}
Your HTML
<select id="blah" onChange="isSelected();">
<option disabled="disabled" selected="selected">Select an option</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
</select><br/>
<input type="submit" value="Submit" style="display:none" id="btnSubmit"/>
change this
<input type="submit" value="Submit"/>
to
<input type="button" value="Submit" id="submit"/>
in jQuery:
$(document).ready(function(){
$('#submit').click(function(){
if($('select[name="blah"]').val() > 1)
$('#yourform').submit();
else
alert('selected value > 1');
});
});
you form need to have an id for example, in my case yourform
DEMO

Categories