validation of select option in javascript - javascript

i am using select option through Struts HTML tags for a particular jsp. The values of the option are Yes and No. Here is the code.
<select name="select" id='choice'>
<option value="<%YES%>" selected><%="YES"%></option>
<option value="<%=NO%>"></option>
The value seen in the select option list by default will be YES.
I am performing validation such that if no value is selected(as Selected property given on 'YES') and form is submitted, a alert should be thrown to select new value. Below is my code.
if( document.form.select.value == "YES" )
{
alert( "Please select other value" );
return false;
}
if( document.form.select.value == "NO" )
{
alert( "Please select other value" );
return false;
}
The above code is not validating properly. Can anyone suggest me some changes.
Thanks

This is how to check if the selected value is the default value, even though I am not understanding very well your intentions.
el = document.getElementById('choice');
if( el.options[el.selectedIndex].defaultSelected){
alert("Please select other value");
return false;
}
PS: you probably need to fix your code :
<select name="select" id='choice'>
<option value="<%=YES%>" selected><%="YES"%></option>
<option value="<%=NO%>"></option>
</select>

Related

JQuery show/hide gives weird results

Im having some weird issues with javascript I can't really resolve.
I have three html input boxes with a small js file to show or hide the second and third one depending on what is picked in the first box. I'm using these functions:
$('#maintype').on('change', function() {
if (this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
The problem im running to is that the second dropdown is not shown when I highlight "fries". The third input box is never shown. I've tried all sorts of solutions, but I just can't figure out why.
I put my code on github
Anyone that can give me some insight on where I am going wrong? Is there maybe another, simpler way to get this done?
You have two issues:
The problem im running to is that the second dropdown is not shown when I highlight "fries"
Your check for fries is wrong, you have:
if ( this.value == '1') {
$("#fries").show();
} else {
$("#fries").hide();
}
but the check should be for '6' since that is the value you assigned to it in your #maintype select.
The other issue:
The third input box is never shown.
You assigned the different IDs (eg. #fries, #icecream, etc.) to the <div> and not to the <select>.
You should also not have several elements with the same id or name (ie. #selectlist) in your case this will be solved when you fix the second issue.
There is no handler for <option value="6">fries</option> , i mean there is no if ( this.value == '6') type line in your javascript code. I added below lines in your js file and it worked.
$('#maintype').on('change', function() {
if ( this.value == '6')
//.....................^.......
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
});
Demo : https://jsfiddle.net/gd548j0g/
In your #maintype select, fries has a value of '6'. But in your change handler, you are looking for a value of 1. In fact, there is no value in the select that has a value of 1. Hence, the fries select box is never shown. Either change your handler to look for the id of 6:
$('#maintype').on('change', function() {
if ( this.value == '6') {
$("#fries").show();
} else {
$("#fries").hide();
}
});
Or change your option value for fries to 1:
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="1">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
Working example: https://jsfiddle.net/mspinks/vnofjobu/2/
<select class="select" id="maintype" name="maintype">
<option value=""></option>
<option value="3">filler</option>
<option value="161">Icecreams</option>
<option value="6">fries</option>
<option value="7">Others</option>
<option value="162">burgers</option>
<option value="163">drinks</option>
</select>
$('#maintype').on('change', function() {
if ( this.value == 6)
{
$("#fries").show();
}
else
{
$("#fries").hide();
}
be careful with the values that you assign to the options
your value of fries is 6, not 1
I have checked your code in Git, you can achieve your output with below code in your showhide.js file.
$(document).ready(function(){
$('#maintype').on('change', function() {
$('input[type="text"]').hide(); //Hides all input with type Text, better if we do this using class
var id = '#' + this.value;
$(id).show(); //Show input with id which you have returned with this.value
});
});

Jquery event for option box and typing action

I am doing the jquery event programming for option box for premium box.
For example, i can type on the option box.
So, I type in the option box instead of selecting my select option box.
the following code is the example:
But seems like it is not correct. Is the event is 'change' event ?
My HTML code is as following:
<div id = 'divContent'>
<select id="my_id" style="width: 120px;"
onchange="$('input#my_id').val($(this).find('option:selected').text());"
name="my_id">
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="30000">30000</option>
<option value="50000">50000</option>
<option value="80000">80000</option>
<option value="100000">100000</option>
</select>
</div>
You need to replace my_id with the id of your select box:
$("#divContent").on('change', "select[id='my_id']", function () {
Will work only when you have a select like:
<select id="my_id">
...
I don't see any elements with the id divContent so change the first line to
$("select[id='my_id']").on('change', function () {
Secondly, even when the code is working, with the example given, there won't be any alerts because none of the if statements will evaluate to true
You have a syntax error here -
if (selectedValue = '') {
alert("Please enter Premium")
}
it should be == not =
if (selectedValue == '') {
alert("Please enter Premium");
}
you can also use -
if(!selectedValue) or if(selectedValue == null)

jQuery validation on select box not working

I am using jQuery validation plugin for client side validation, but my validation does not work on my select box.
HTML
<select id="select" class="required">
<option value="-1">Choose</option>
<option value="child">test2</option>
</select>
JavaScript
$("#formid").validate({
select: {
required: function(element) {
if ($("#select").val() == '-1') {
return false;
} else {
return true;
}
}
}
});
How do I get this working?
A simple way to fix this problem is to give the non valid option the value of "". Then simply call validate on your form and it will not submit when "Choose" is selected.
HTML
<form id="formid">
<select name="select" class="required">
<option value="">Choose</option>
<option value="child">test2</option>
</select>
<input type="submit" />
</form>​
JavaScript
$("#formid").validate(); ​
Demo
Although this probably works with some of the aforementioned methods,if you're looking to use a custom validation function, you should use addMethod as documented here: http://docs.jquery.com/Plugins/Validation/Validator/addMethod
So you would first add the method through something like
$.validator.addMethod("requiredSelect", function(element) {
return ( $("#select").val() !='-1' );
}, "You must select an option.");
Then simply assign the validator with
$("#formid").validate({
rules: {
select: { requiredSelect : true }
}
});
For some reason no solution provided worked in my case, it boiled down to jQuery Validate calling the "optional" check on the value of the drop down, which that called the !required rule.
When the select box selected an empty value, the required showed "false" which inverted meant it was always optional when the required failed, so it never ran the required rule.
I overwrote the optional function with the below, which returned "False" on optional if it was a required item:
// Get Select to work
$.validator.prototype.optional = function (element) {
var val = this.elementValue(element);
// Custom logic to get Select to show validate when value is empty
if (element.nodeName.toLowerCase() === "select") {
if (element.hasAttribute("data-val-required") || element.hasAttribute("required")) {
return false;
}
}
return !$.validator.methods.required.call(this, val, element) && "dependency-mismatch";
};
instead of:
$("#select").val()
try:
$("#select :selected").val()
$("#select").val() returns all the option values instead of the selected one.
Here, my assumption is that you want to check if the user has chosen the option -1 when the control report-crime is validated.
by default
<option value="">Choose</option>
works with
required: true
There is missing name attribute in your select element.
In my case that was the issue since the jQuery Validatation Plugin looks for the name not id while validating.

How can I verify that all select boxes have a selected option through JavaScript or JQuery or...?

I have 2 select boxes on a page with a variable number of options in them.
For instance:
<fieldset>
<label for="fizzwizzle">Select a Fizzwizzle</label>
<select name="fizzwizzle" id="fizzwizzle" size="10">
<option>Fizzwizzle_01</option>
<option>Fizzwizzle_02</option>
<option>Fizzwizzle_03</option>
<option>Fizzwizzle_04</option>
</select>
</fieldset>
<fieldset>
<label for="fizzbaggot">Select a Fizzbaggot</label>
<select name="fizzbaggot" id="fizzbaggot" size="10">
<option>Fizzbaggot_01</option>
</select>
</fieldset>
I would like to verify that both of these select boxes have a selected option. My initial thought is to simply use JQuery but I can't seem to figure out how to do that. My attempts so far have been futile but I have the following code that I think should work with the missing link.
function verify_selectboxen_selection() {
var allSelected = true;
$('select').each(function() {
/* if select box doesn't have a selected option */
allSelected = false;
break;
});
if (!allSelected) {
alert('You must select a Job and a Disposition File.');
}
return allSelected;
}
Seems simple enough. Thoughts?
In jQuery you can use the :selected selector to get the total options selected. This number out to match the number of select's themselves:
if ($("select").length === $("option:selected").length) {
// they match
}
I would like to verify that both of these select boxes have a selected option
It's not possible for a (non-multiple) select box not to have a selected option! If you don't declare selected on one of the option​s, the browser will automatically select the first option.
So: return true; :-)
If you want to have an ‘unselected’ initial state, you'd have to include a no-option option for it, usually the first one:
<select name="fizzbaggot">
<option value="" selected="selected">(Select a fizzbaggot)</option>
<option>foo</option>
<option>baz</option>
<option>bar</option>
</select>
Then you can check whether a different option to that one has been selected, either by saying:
$('select').each(function() {
if ($(this).val()!=='')
allSelected= false;
});
Or, if you might want to use the empty string as a valid value, you can just look at the index of the selected option:
$('select').each(function() {
if (this.selectedIndex===0)
allSelected= false;
});
You can use the :selected selector for this.
var unselected = []
$('select').each(function(){
if (0 == $(this).find('option:selected').length) {
unselected.push(this.id);
}
});
if (unselected.length != 0) {
// unselected contains the ids of non-selected select boxes
}
Or you could check their values with val(). This presumes that you have a default option with no value (ie empty string value).
var unselected = []
$('select').each(function(){
if ('' == $(this).val()) {
unselected.push(this.id);
}
});
if (unselected.length != 0) {
// unselected contains the ids of non-selected select boxes
}
function checkSelects() {
return $("select :selected").length == $("select").length;
}
alert(checkSelects());

Check HTML DropDown option

I have a HTML dropdown control. I want to check that if the text in it is "Select", it must display error message. I am using following code to do this, but it is not working.
if (document.getElementById("StudentCountry").value == "Select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
document.GetElementById("StudentCountry").SelectedIndex=0;
or
function getDropDownListvalue()
{
var IndexValue = document.GetElementById("StudentCountry").selectedIndex;
var SelectedVal = document.GetElementById("StudentCountry").options[IndexValue].value;
alert(SelectedVal);
}
check for selected value="select"
var box = document.getElementById("StudentCountry");
if(box.options[box.selectedIndex].text == "Select")
How is this javascript code embedded in your html file? Is it just inside a script element and not in a distinct function? If so, this will probably always return null for the function, as the dropdown is not loaded at the moment it is used. Otherwise the code should work. Just put in a function, let's say checkCountry() and add it as onchange="checkCountry();" to the tag.
The second thing that could break your code is the check for the "Select" text. If you check for value on an option, it will most likely check for the value attribute, such as:
Select
And in this example select is written all lowercase, which would not compare to your ==.
I hope this helps.
Your code seems to be perfect .check onceagain Default options values is "select" or not..
<html>
<head>
<script language="javascript">
function validate(){
alert('ddddddddddd ='+document.getElementById("StudentCountry").value);
if (document.getElementById("StudentCountry").value == "select")
{
alert("Please select your country.");
document.getElementById("StudentCountry").focus();
return false;
}
return false;
}
</script>
</head>
<body>
<select id="StudentCountry">
<option value="select" >---------Please Select ---------</option>
<option value="India" >India</option>
<option value="USA" >UAS</option>
<option value="UK" >UK </option>
</select>
<a onclick="javascript:validate();" href="#">click here to validate</a>

Categories

Resources