JavaScript Validation for Listbox when mulitple values are selected - javascript

I want to do JavaScript validation for listbox
If Value from Lisbox is not selected, it should get alert "Please Select Your Skill"
But if user select 3 Skill from 6 Skill. I need that 3 skiils should get alert using JavaScript.
Here is my Code...
call script on submit button..
<html>
<head>
<script></script>
</head>
<body>
<form name="registration" id="registration_form_id" action="" method="post">
<select id="skillid1" name="skill[]" multiple="multiple" size="3" >
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit" onClick="myFunction()">Submit</button>
</form>
</body>
</html>
Thank you
Rahul

First of all use onsubmit form event instead of button click. In this case you return false when the form should not be submitted. Here is an example:
function myFunction(form) {
var select = form['skill[]'];
// Check if skill is selected
if (select.selectedIndex === -1) {
alert("Please Select Your Skill");
return false;
}
// Check if selected 3 skills out of 6
if (select.selectedOptions.length) {
var options = [].map.call(select.selectedOptions, function(option) {
return option.text;
}).join('\n');
alert("You selected: \n" + options);
return true;
}
return false;
}
<form name="registration" id="registration_form_id" action="" method="post" onsubmit="return myFunction(this)">
<select id="skillid1" name="skill[]" multiple="multiple" size="3">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="javascript">JAVASCRIPT</option>
<option value="php">PHP</option>
<option value="mysql">MY-SQL</option>
<option value="jquery">JQUERY</option>
</select>
<button type="submit">Submit</button>
</form>
Note that returning true from event handler will submit the form (in above demo submission is suppressed).
Here is JSFiddle demo.

To get the selected options from a multiple select, you should iterate over the options collection and collect the ones that are selected.
There is also the selectedOptions collection (per dfsq's answer), but support is patchy across browsers.
The looping method is made easier with a simple toArray function:
// Return an array of list members in numeric index order
// Respect sparse lists.
function toArray(list) {
var array = [];
// Use for loop for maximum compatibility
for (var i=0, iLen=list.length; i<iLen; i++) {
// Respect sparse lists
if (list.hasOwnProperty(i)) {
array[i] = list[i];
}
}
return array;
}
So if you have a reference to the select element, you can get the selected options using:
var selectedOptions = toArray(select.options).filter(function(option) {
return option.selected;
});
Now you can show the displayed text of each option in an alert using:
alert(selectedOptions.map(function(option){return option.text}).join('\n'));

Related

Loop through select from fields and validate

Im trying to loop through multiple text and select boxes in a form and validate they have been answered.
I have used the following code to loop through the text boxes but can work out how to do something similar on the select boxes.
<form name="Form1"></form>
<label>Question 1</lable>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>';
</form>
<script>
(function (){
$('#Go').on('click', function(e){
e.preventDefault();
genericValidationText('form[name="Form1"]');
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationText (formName) {
document.forms.noValidate = true;
var notValid;
// PERFORM GENERIC CHECKS
// INPUT form fields
$(formName + ' *').filter(':input').each(function(){
var formElement = formName + ' input[name="'+ (this.name) + '"]' ;
performValidation(formElement);
});
function performValidation(formElement){
if ($(formElement).hasClass('required')) {
notValid = false;
if (!($.trim($(formElement).val()))){
notValid = true;
};
if (notValid === true) {
showErrorMessage(formElement);
};
};
}
}
function genericValidationSelect (formName) {
?????
}
</script>
You can validate <select> elements in much that same way as <input /> elements, by examining the result of the select element's .val().
Something to keep in mind is that the <select> will have a value by default (that corresponds to the <option> that is initially visible to the user in the browser). This will in effect cause validation on the <select> to pass (even when a selection option hasn't been explicitly picked by the user).
To address this, consider adding a default <option> to the <select> like this:
<option selected disabled>Please select something</option>
Adding this option means that validation on the <select> will fail until the user has actually engaged with the <select> by picking a valid option (after which, validation on the select will pass):
(function() {
/* Consider using submit on form, rather than a click event
listener on the Go button */
$('form[name="Form1"]').submit(function(e) {
e.preventDefault();
/* Exclude call to genericValidationText() for
this snippet to simplify it
genericValidationText('form[name="Form1"]');
*/
genericValidationSelect('form[name="Form1"]');
});
}());
function genericValidationSelect(formName) {
let notValid = false;
/* Iterate each select in the form */
$('select', formName).each(function() {
/* Check value in similar way. If null value,
then consider the select invalid */
var selectedOption = $(this).val();
if (selectedOption === null) {
notValid = true;
}
});
if(notValid) {
alert('Please select an option');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Fixed : remove closing form tag -->
<form name="Form1">
<!-- Fixed : typo -->
<label>Question 1</label>
<input type="text" class="required" name="question1">
<label>Question 2</lable>
<select class="required" name="question3">
<!-- Added default "no value option" to demonstrate validation -->
<option selected disabled>Please select something</option>
<option value="0">a</option>
<option value="1">b</option>
<option value="2">c</option>
<option value="3">d</option>
</select>
<button role="button"id="Go">Go</button>
</form>
Hope this helps!
The following should work:
const changeEventHandler = e => {
const value = e.target.options[e.target.selectedIndex].value;
console.log(value); //Validate value...
}
const select = document.querySelector('select[name=question3]').onchange = changeEventHandler;

Textbox value to check multiselect parameter based on values JS

Trying to assign ticks to a checkbox and have options selected if the value matches the values in the textbox. This a multi-select parameter.
E.g. if the textbox contains 1,2 when the page refreshes I want to ensure Cheese and Tomatoes is selected. If the textbox contains 1,5,6 then I want to ensure Cheese, Pepperoni and Onions are selected. If the textbox contains 1,2,3,4,5,6 then I want to ensure all checkboxes are selected.
Trying to write some javascript to do this. I tried to use local storage but can't get it working. See code example: https://www.codeply.com/go/rupzwTzBMY
ASPX:
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
Currently when the page refreshes, even if the textbox has values assigned - the checkboxes clear and nothing is selected.
I am trying to ensure when users select items from the multi-parameter when the page refreshes those values are not gone and still remain on the page.
Javascript functionality that works so far. This puts values in a textbox when you select items from the drop-down. However, when the page refreshes the text box keeps these selected values but the multi-select parameter doesn't:
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
document.getElementById("txt1").value = selectedOptions;
},
});
Firstly, you must reload the select once after populating default values as below
$('#basic').multiselect('refresh')
Secondly, try to use onInitialized method as described here
Finally, You're trying to assign back values from TextBox to Dropdown as below, where you're trying to assign the value as such with a comma 1,2 which actually doesn't exist as a value in dropdown.
External Fiddle
$('#basic').children("option[value=" +
document.getElementById("txt1").value + "]").prop("selected", true);
Split the values as 1 and 2 and then assign and it works.
$(document).ready(function () {
document.getElementById("txt1").value = "1,2,3"
$('#basic').multiselect({
includeSelectAllOption: true,
numberDisplayed: 5,
onInitialized: function(select, container) {
console.log("Init");
selectListValues();
}
});
$("#basic").multiselect('refresh');
});
function selectListValues()
{
var txtValue = document.getElementById("txt1").value;
var selectedValues = txtValue.split(",");
for(var i = 0; i < selectedValues.length; i++)
{
var val = selectedValues[i];
if (val == null || val == "") continue;
$('#basic').children("option[value=" + val + "]").prop("selected", "selected");
}
}
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.15/css/bootstrap-multiselect.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
</head>
<body>
<input type="text" runat="server" id="txt1" visible="true" value="" onchange="selectListValues()" />
<div class="container">
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
</body>
</html>
You can get and populate the value using local storage and split the item.
Note
I had to comment out the local storage so the demo code will work as local storage won't work cross domain. You will need to test this locally.
$(function() {
//$("#txt1").val(localStorage.getItem('topping'));
var str = $("#txt1").val().split(",");
$('#basic').val(str);
$('#basic').on('change', function(){
var list = $("#txt1").val($(this).val());
//localStorage.setItem('topping', list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="1,2,4" />
<select id="basic" multiple="multiple">
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
you can store input value in local storage, then get inputvalue from local storage then iterate on option set and set selected attribute to true of option if value is present in localstorage.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.js"></script>
<input type="text" runat="server" id="txt1" visible="true" value="" />
<div class="container">
<select id="basic" multiple>
<option value="1">Cheese</option>
<option value="2">Tomatoes</option>
<option value="3">Mozzarella</option>
<option value="4">Mushrooms</option>
<option value="5">Pepperoni</option>
<option value="6">Onions</option>
</select>
</div>
<script>
$(document).ready(function () {
$('#basic').multiselect({
onChange: function () {
var selectedOptions = $('#basic').val();
console.log(selectedOptions);
setInputAndLocatStorage();
}
});
function onLoad() {
if(!localStorage.getItem('selectedItems')) return false;
var selItems = localStorage.getItem('selectedItems').split(',');
document.getElementById('txt1').value = selItems.join(',');
$('#basic').multiselect('select',selItems);
}
function setInputAndLocatStorage() {
var selItems = $('#basic').val();
var val = selItems == null ? '': selItems.join(',');
document.getElementById('txt1').value = val;
localStorage.setItem('selectedItems', val);
}
onLoad();
});
</script>

Select decides which form action to open

I have a form that starts with a select. Based on the choice of that first select (which report is chosen) I need to change the action path of which .cfm the form submits to. Will someone please assist me in how I should do this? I am open to any proper way whether is HTML, ColdFusion or jQuery (Javascript).
So starts with a select:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option id ="checklistreports" value="checklistreports" >Checklist Stats</option>
<option id ="locationreports" value="locationreports" >Location Stats</option>
</select>
If #checklistreports is chosen the form should be
<form name="generatereport" method="post" action="_checklists_queries.cfm">
But if #locationreports is chosen the form should be
<form name="generatereport" method="post" action="_location_queries.cfm">
Any help with this would be greatly appreciated.
I was trying to do in IF statement in CF but it has me stuck unfortunately with no results.
You can use a .change handler to change the action attribute of the form.
$("#reporttype").change(function() {
if ($(this).val() == "checklistreports") {
$("form[name=generatereport]").attr("action", "_checklists_queries.cfm");
} else {
$("form[name=generaterport]").attr("action", "_location_queries.cfm");
}
});
I would recommend to just indicate the action values of the form in the values of the options.
$('#reporttype').change(function(){
form_action = $(this).val();
$('form').attr('action', form_action);
$('span').text(form_action);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="_checklists_queries.cfm" >Checklist Stats</option>
<option value="_location_queries.cfm" >Location Stats</option>
</select>
<form name="generatereport" method="POST" action="#">
<p>This forms action value is <span>#</span></p>
</form>
You could always do it all with ColdFusion. It's so much simpler. Here is one approach.
formPage
<form action = "action.cfm" method="post">
<select name="pageToInclude">
<option value="locationQueries.cfm">Location</option>
rest of form.
action.cfm
<cfinclude template = "#form.pageToInclude#">
You already have an accepted answer, but I would like to propose a slightly cleaner solution to the answer you selected, as well as an alternative:
Option #1 (Inline and Clean):
// Cache the selector for better reuse.
var form = $("form[name=generatereport]");
$("#reporttype").change(function() {
var action = $(this).val() === 'checklistreports' ? '_checklists_queries.cfm' : '_location_queries.cfm';
form.attr('action', action);
});
The above option is just a more compact version of the answer you selected, but utilizes selector caching, which is good for performance.
Option #2 ('Global' Config Options):
// Cache the selector
var form = $('form[name=generatereport]');
// Now you can define the variable states for your app.
var config = {
checklistreports: {
action: '_checklists_queries.cfm'
},
locationreports: {
action: '_location_queries.cfm'
}
};
// Updating is trivial
$('#reporttype').change(function() {
var selected = $(this).val();
form.attr('action', config[selected].action);
});
This option is interesting because it lets you define all the different "states" for your components in one place, which is nice for readability and maintenance, and it makes the actual updating of components as simple as looking up the values it should have.
If the forms contains differents elements, you could hide the forms with css and with an onchange handler on the select unhide the right form.
html:
<select class="form-control" id="reporttype" name="reporttype">
<option value="" selected="selected">Select Report</option>
<option value="checklistreports" >Checklist Stats</option>
<option value="locationreports" >Location Stats</option>
</select>
<form method="post" action="_location_queries.cfm" id="locationreports" style="display: none;">
<input type="text" name="location" placeholder="location">
</form>
<form method="post" action="_checklists_queries.cfm" id="checklistreports" style="display: none;">
<input type="text" name="location" placeholder="checklist">
</form>
js:
var locationReport = document.getElementById("locationreports");
var checklistReport = document.getElementById("checklistreports");
function onChangeForm(e) {
if (e.target.value === "locationreports") {
locationReport.style.display = "block";
checklistReport.style.display = 'none';
} else {
checklistReport.style.display = "block";
locationReport.style.display = "none";
}
}
document.getElementById("reporttype").onchange = onChangeForm;
jsfiddle example

How do I have my drop down selections submit in the HTML form?

I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.

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>

Categories

Resources