Javascript dropdown validation and alert - javascript

I have tried to get it to work but I simply can't find the mistake. Also I have no idea how to make the selection which you have not selected to turn red or some color to alert you.
<!DOCTYPE html>
<html>
<body>
<select id='Selection' name='Selection'>
<option value=''>Select</option>
<option value='1'>user1</option>
<option value='2'>user2</option>
<option value='3'>user3</option>
</select>
<br>
<select id='Candidate' name='Candidate'>
<option value=''>Select</option>
<option value='1'>candidate1</option>
<option value='2'>candidate2</option>
<option value='3'>candidate3</option>
</select>
<br>
<input type='button' onclick='Validate()' value='select' />
<script>
function Validate()
{
if(document.getElementById('Selection').value == '' ||
document.getElementById('Candidate').value == '' ||)
{
alert('Please complete all selections');
return false;
}
return true;
}
</script>
</body>
</html>

You have an extra || in you if condition, this will cause a syntax error, remove it (the last one not both). To change the element that has an invalid value you can just use css but you'll have to check them individually.

Related

How can I get id of span element inside select element?

My html form has the content below:
<form name="profile">
...
<select id="province" name="province">
<span id="provinceWarning" class="alert"></span>
<option value="">Select Province</option>
<option value="AB">Alberta</option>
...
In my javascript, I'm trying to grab the form's ID to show a message telling the user to choose something in the dropdownlist if they haven't chosen anything and pressed the submit button. The problem is that the javascript block returns undefined.
//validate the profile form
function validate(e){
e.preventDefault();
var valid=true;
if(document.profile.province.value == ""){
document.getElementById('provinceWarning').innerHTML="*Please choose a province*";
valid=false;
}
if(valid){
alert("Thank You!");
}
return valid;
};
You can't have a span tag inside a select tag. Browser while rendering this HTML would have stripped it off.
See the demo below (check in your browser's dev tools that browser is stripping off span tag while rendering)
<select id="province" name="province">
<span id="provinceWarning" class="alert"></span>
<option value="">Select Province</option>
<option value="AB">Alberta</option>
</select>
You need to put the span tag outside the select tag.
Try this, it comes down and reset once u select and submit.
function submit(){
if(!document.getElementById("province").value){
document.getElementById("provinceWarning").innerHTML="*Please choose a Province*";
valid=false;
}else{
document.getElementById("provinceWarning").innerHTML=""
valid=true;
window.alert("thank you")
}
}
<form name="profile">
<select id="province" name="province">
<option value="">Select Province</option>
<option value="AB">Alberta</option>
</select>
<span id="provinceWarning" class="alert"></span>
</form>
<button id="btnSubmit" onclick="submit();">Submit</button>
Problems:
1- You can not define span in select option then move it out of your select
2- To check select value you should getElementById("province") and then check the value
3- Testable code can be as below(You can change it as you want):
function func()
{
var ddl = document.getElementById("province");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == ""){
document.getElementById("provinceWarning").innerHTML="*Please choose a Province*";
valid=false;
}else{
alert("Thank You!");
}
}
<form name="profile">
<div>
<span id="provinceWarning" class="alert"></span>
</div>
<div>
<select id="province" name="province">
<option value="">Select Province</option>
<option value="AB">Alberta</option>
</select>
</div>
</form>
<button id="btnSubmit" onclick="func();">Click Me</button>

How to use if else statements in select form?

In my registration page, I'm gonna use two drop-down select that one of them should be hidden if its Negative and if its positive new drop-down will open to choose ...
In mysql table I've table as diabetes name with enom
enum('negative', 'insulin', 'drug', 'ndm', 'mody', '')
Here's my code:
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
For example: If Diabetes is negative value is negative as default then Diabetes Type is hidden
and
If Diabetes is positive then Diabetes type will be appeared to choose items.
those values like insulin, drug, mdm, mody should be inserted into this:
value="positive"
How can I make it through java script?
I can't add class or div or span. Is it possible just through JavaScript using ??
Thank you so much
Use jquery, it is comparatively easier.
$(document).ready(function(){
$("#diabetestype").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").show();
}else{
$("#diabetestype").hide();
}
});
});
To make this code workable, you need to add value of Positive option also. So instead value="" change it to value="positive".
You can even hide the label also:
$(document).ready(function(){
$("#diabetestype").closest("div").hide();
$("#diabetes").on("change", function(){
var v = $(this).val();
if(v=="positive"){
$("#diabetestype").closest("div").show();
}else{
$("#diabetestype").closest("div").hide();
}
});
});
<div><label for="diabetes">Diabetes:</label>
<select id="diabet" name="diabet" onchange="checkDiabet();">
<option value="negative">Negative</option>
<option value="positive" id="isDiabet">Positive</option>
</select>
</div>
<div id="type" style="display: hidden;">
<label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
<script>
function checkDiabet() {
var isDiabet = document.getElementById("isDiabet").selected;
if (isDiabet == true) { document.getElementById("type").removeAttribute("style"); }
else { document.getElementById("type").style.display = "none"; }
}
</script>
First, set the first select to fire the function checkDiabet() by the attribute onchange. Then give the option an id, which needs to be checked, so you can access it easily.
Then, set the second select to display: none This could be done in a CSS header or file, or like in this case inline. (div style=""), also add an id to access it easily. (div id="type")
Now comes the function checkDiabete(). It checks if the select is selected (can be true or false (bool)). Is selected => show (div id="type"), if not, hide this div (and all of it's contents)
(if is already hidden, it then overwrites the (style="display: none;") with (style="display: none;))
That's it! :)
Try this:
function SelectDiabetes() {
var d = document.getElementById("diabetes").value;
var dType = document.getElementById("diabetestypebox");
if(d == "negative")
dType.style.display = "none";
else
dType.style.display = "block";
}
SelectDiabetes();
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="SelectDiabetes(this.value);">
<option value="negative">Negative</option>
<option value="positive">Positive</option>
</select>
</div>
<div id="diabetestypebox"><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Call a js function onchange of select id diabetes
<div><label for="diabetes">Diabetes:</label>
<select id="diabetes" name="diabetes" onchange="toggleTypes()">
<option value="negative">Negative</option>
<option value="">Positive</option>
</select>
</div>
<div><label for="diabetestype">Diabetes Type:</label>
<select id="diabetestype" style="display:none" name="diabetestype">
<option value="insulin">Insulin</option>
<option value="drug">Drug</option>
<option value="ndm">NDM</option>
<option value="mody">MODY</option>
</select>
</div>
Use the following javascript
function toggleTypes(){
var el=document.getElementById('diabetes');
var medElem=document.getElementById('diabetestype');
if(el.value=='positive') {
medElem.style.display='block';
} else {
medElem.style.display='none';
}
}

Display other field onchange

I have here selectbox with option value USA and OTHERS. What I need is if I choose OTHERS on Selectbox1 the Selectbox2 should be display none and textbox1 comes out. Other problem also is it's name field, If I POST the value of name="cboState" . How to remove the name of a field? Any help will appreciate.
<form action="try.php" method="POST">
<select id="cboCountry">
<option value="USA">USA</option>
<option value="OTHERS">OTHERS</option>
</select>
Selectbox 2
<select id="cboState" name="cboState">
<option value="Alabama">Alabama</option>
</select>
Textbox 1
<input type="text" id="cboState" name="cboState"/>
<input type="submit">
</form>
Try this
HTML
<select id="cboCountry">
<option value="USA">USA</option>
<option value="OTHERS">OTHERS</option>
</select>
<select id="cboState" name="cboState">
<option value="Alabama">Alabama</option>
</select>
<input type="text" id="txtcboState" name="cboState" style="display:none;"/>
JS
$("#cboCountry").change(function() {
if ( $(this).val() == "OTHERS") {
$("#cboState").hide();
$("#txtcboState").show();
}
else{
$("#cboState").show();
$("#txtcboState").hide();
}
});
Note: ID Must be unique for each element.
To remove The name attribute of input, you can use the following
$("#txtcboState").removeAttr('name');
DEMO HERE
Something like this?
$("#selectbox1").onchange(function() { selectionChanged();});
function selectionChanged() {
if ( $("#selectbox1").val() == "other") {
$("#selectbox2").hide();
$("#textBox1").show();//should already be hidden
}
}
Make sure the IDs for your elements are unique.

How to show alert if multiple option values are empty

I have the following HTML and Javascript, that is not working:
<select id="shirtinfo[0]" name="shirtinfo[0]">
<option value="">Confederation</option>
<option value="6770">Europe (UEFA)</option>
<option value="16272">South America (CONMEBOL)</option>
<option value="21684">Africa (CAF)</option>
<option value="21771">North & Central America (CONCACAF)</option>
<option value="18091">Asia (AFC)</option>
<option value="19193">Oceania (OFC)</option>
</select>
...
<select id="season" name="season">
<option value="">Season</option>
<option value="2013">2013</option>
...
</select>
...
<input id="submit" type="submit" value="[[Save:raw]]" onclick="validate()" />
<script>
function validate() {
if (document.querySelectorAll("#shirtinfo[0], #shirtinfo[1], #shirtinfo[2], #shirtinfo[3], #shirtinfo[4], #season, #style, #status").value)
{
alert("[[Please enter the mandatory fields]]");
return false;
}
}
</script>
All the first option values are empty with just the title, and the alert will be shown if any of the options are not selected. So the user needs to select from the lists at least something else that is not the first option.
How can I do that?
Alter the following code as necessary. Just loop through the proper elements, and if the select's value is empty, then break and handle as necessary.
function validate() {
"use strict";
var selectEls = document.querySelectorAll('select'),
numSelects = selectEls.length;
for(var x=0;x<numSelects;x++) {
if (selectEls[x].value === '') {
alert('[[Please enter the mandatory fields]]');
return false;
}
}
// If the code execution reaches this point, all the tests pass
// ...
}
The code can be improved, for example, if you want to continue looping through all the elements, and highlight the problem select elements, but that is beyond the scope of this question.
Try this: Also in this fiddle: http://jsfiddle.net/9f76X/
<select id="shirtinfo" name="shirtinfo[0]">
<option value="">Confederation</option>
<option value="6770">Europe (UEFA)</option>
<option value="16272">South America (CONMEBOL)</option>
<option value="21684">Africa (CAF)</option>
<option value="21771">North & Central America (CONCACAF)</option>
<option value="18091">Asia (AFC)</option>
<option value="19193">Oceania (OFC)</option>
</select>
...
<select id="season" name="season">
<option value="">Season</option>
<option value="test">test</option>
</select>
...
<input id="submit" type="submit" value="[[Save:raw]]" onclick="return validate();" />
<script type="text/javascript">
function validate() {
var controls, cnt, showAlert;
controls = document.querySelectorAll("#shirtinfo,#season");
for (cnt=0;cnt < controls.length; cnt++)
{
if (!controls[cnt].value)
{
showAlert = true;
break;
}
}
if (showAlert) {
alert("[[Please enter the mandatory fields]]");
}
return !showAlert;
}
</script>

How to show form input fields based on select value?

I know this is simple, and I need to search in Google. I tried my best and I could not find a better solution. I have a form field, which takes some input and a select field, which has some values. It also has "Other" value.
What I want is:
If the user selects the 'Other' option, a text field to specify that 'Other' should be displayed. When a user selects another option (than 'Other') I want to hide it again. How can I perform that using JQuery?
This is my JSP code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="otherType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
Now I want to show the DIV tag**(id="otherType")** only when the user selects Other.
I want to try JQuery. This is the code I tried
<script type="text/javascript"
src="jquery-ui-1.10.0/tests/jquery-1.9.0.js"></script>
<script src="jquery-ui-1.10.0/ui/jquery-ui.js"></script>
<script>
$('#dbType').change(function(){
selection = $('this').value();
switch(selection)
{
case 'other':
$('#otherType').show();
break;
case 'default':
$('#otherType').hide();
break;
}
});
</script>
But I am not able to get this. What should I do? Thanks
You have a few issues with your code:
you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">
should be <select name="dbType" id="dbType">
$('this') should be $(this): there is no need for the quotes inside the paranthesis.
use .val() instead of .value() when you want to retrieve the value of an option
when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function
try this:
$('#dbType').on('change',function(){
if( $(this).val()==="other"){
$("#otherType").show()
}
else{
$("#otherType").hide()
}
});
http://jsfiddle.net/ks6cv/
UPDATE for use with switch:
$('#dbType').on('change',function(){
var selection = $(this).val();
switch(selection){
case "other":
$("#otherType").show()
break;
default:
$("#otherType").hide()
}
});
UPDATE with links for jQuery and jQuery-UI:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>‌​
Demo on JSFiddle
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
You have to use val() instead of value() and you have missed starting quote id=dbType" should be id="dbType"
Live Demo
Change
selection = $('this').value();
To
selection = $(this).val();
or
selection = this.value;
I got its answer. Here is my code
<label for="db">Choose type</label>
<select name="dbType" id=dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
<div id="other" class="selectDBType" style="display:none;">
<label for="specify">Specify</label>
<input type="text" name="specify" placeholder="Specify Databse Type"/>
</div>
And my script is
$(function() {
$('#dbType').change(function() {
$('.selectDBType').slideUp("slow");
$('#' + $(this).val()).slideDown("slow");
});
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function myfun(){
$(document).ready(function(){
$("#select").click(
function(){
var data=$("#select").val();
$("#disp").val(data);
});
});
}
</script>
</head>
<body>
<p>id <input type="text" name="user" id="disp"></p>
<select id="select" onclick="myfun()">
<option name="1"value="1">first</option>
<option name="2"value="2">second</option>
</select>
</body>
</html>
$('#dbType').change(function(){
var selection = $(this).val();
if(selection == 'other')
{
$('#otherType').show();
}
else
{
$('#otherType').hide();
}
});

Categories

Resources