Loop through select from fields and validate - javascript

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;

Related

Make textbox required if a certain value is selected in dropdown box

On a form, I have the following required drop down box:
<select id="SelectBox" name="SelectBox" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
I also have the following textbox:
<input type="text" name="textbox" id="textbox">
I am trying to make the textbox required only if val4 is selected from the dropdown box using the required attribute (red border around textbox). I have done this with a radio button group, but need to do the same with this dropdown box.
Any help would be greatly appreciated. Thanks.
This should work to make text input attribute required and add some red border if you select the val4 option from the select box only.
var select = document.getElementById("SelectBox");
var textBoxElement = document.getElementById("textbox");
select.onchange = function(){
var selectedString = select.options[select.selectedIndex].value;
if(selectedString == 'val4'){
textBoxElement.required = true;
textBoxElement.style.border="1px solid red";
}else{
textBoxElement.required = false;
textBoxElement.style.border="";
}
}
See working fiddle : https://jsfiddle.net/nwk1tkb7/5/
One approach I'd suggest is the following:
// use of a named function, to be called via Elememt.addEventListener:
function elementRequiredIf(event) {
// 'this' will be the <select> element in this example, however
// the 'this' is automatically passed from Element.addEventListener
// (as is the 'event' object, though we don't use that here):
var changed = this,
// here we find the conditionally-required element, using
// the id of the element stored in the custom data-* attribute
// of the <select> element, here we retrieve that attribute-
// value from the dataset object, stored as a property of the
// Element:
requiredElement = document.getElementById(changed.dataset.required_elem_id),
// as above, we use the same approach to retrieve the
// value that makes the other element required:
ifRequiredValueIs = changed.dataset.required_if_value;
// here we set the required property of the element to
// true (if the <select> value is equal to the required
// value, or false if they are unequal:
requiredElement.required = changed.value === ifRequiredValueIs;
}
// here we find the <select> element via its id,
// and bind an event-listener for the 'change' event,
// which, upon a change event being fired, calls the
// named function (note the deliberate, required, lack
// of parentheses following the function name):
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
function elementRequiredIf() {
var changed = this,
requiredElement = document.getElementById(changed.dataset.required_elem_id),
ifRequiredValueIs = changed.dataset.required_if_value;
requiredElement.required = changed.value === ifRequiredValueIs;
}
document.getElementById('SelectBox').addEventListener('change', elementRequiredIf);
input:required {
box-shadow: 0 0 0.5em #f00;
}
<form>
<select id="SelectBox" name="SelectBox" data-required_elem_id="textbox" data-required_if_value="val4" required>
<option value="">Please Select ...</option>
<option value="val1">val1</option>
<option value="val2">val2</option>
<option value="val3">val3</option>
<option value="val4">val4</option>
</select>
<input type="text" name="textbox" id="textbox">
<button type="submit">Submit</button>
</form>
JS Fiddle demo.
References:
document.getElementById().
EventTarget.addEventListener().
HTMLElement.dataset.

Validating multiple select box

Select box 1
<select name="slt_drop1" id = "slt_drop1">
<option value ="0">----------</option>
...........
</select>
Select box 2
<select name="slt_drop2" id = "slt_drop2">
<option value ="0">----------</option>
...........
</select>
Select box 3
<select name="slt_drop3" id = "slt_drop3">
<option value ="0">----------</option>
...........
</select>
Select box 4
<select name="slt_drop4" id = "slt_drop4">
<option value ="0">----------</option>
...........
</select>
In a HTML form I've used 4 select buttons, if the user selects the value as "0" i.e (Default value) in any of the select button it should show message near to the select button , "please select the correct value" for that particular for example if the value of slt_drop3 is "0" it should alert near slt_drop3 select option . The message should be displayed for individual button and not common alert .
maybe this is what you want ? Demo
$("select").change(function()
{
if($(this).val() == "0")
$(this).after(' <small> please select the correct value</Small>');
else
if($(this).next().prop("tagName").toLowerCase() == "small")
$(this).next().remove();
});
$("select").trigger("change");
Do you use jQuery in your project? I think you can listen when you change the value of select and validate it:
$(function() {
$('select').on('change', validate);
function validate(e) {
var select = $(e.currentTarget);
var id = select.attr('id');
var val = select.val();
if (val === '0') {
showMessage(id);
} else {
hideMessage(id);
}
}
function showMessage(id) {
$('.message[data-select-id="' + id + '"]').show();
}
function hideMessage(id) {
$('.message[data-select-id="' + id + '"]').hide();
}
});
Add blocks for messages near each select tag and show it if necessary
<select name="slt_drop1" id = "slt_drop1">
<option value ="0">----------</option>
...........
</select>
<div class='message' data-select-id='slt_drop1'>please select the correct value</div>
Add a common class to each SELECT element.
Use jQuery to select that elements which match that class.
Bind a change event to the selector and apply the logic to check for "0" value
$(document).ready(function() {
$('select.is-valid').change(function() {
var $el = $(this);
if($el.val() == 0) {
$el.after('<div>Select a different value</div>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
<select name="test[]" class="is-valid">
<option value="0">---</option>
<option value="1">1</option>
</select>
That's a basic example of what you're trying to achieve. Actual element/validation placement is up to you. I would recommend making a "Submit" button to check the validation but I assume you know how to do that.

JavaScript Validation for Listbox when mulitple values are selected

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'));

HTML SELECT JS onchange() disable comment box

This may be an absurdly easy question, but I'm new to JS.
I would like to have a SELECT box allowing a person to indicate where they heard about the event they're registering for. There would be a comment box, disabled by default but if the user selects 'Other' in the SELECT option the comment box would become available.
I am aware of onchange() but I don't know how to trigger a response in the separate form element. Any help?
Probably something like this.
HTML:
<select id="menu">
<option value="0">News</option>
<option value="1">Friends</option>
<option value="2">Other</option>
</select>
<input id="comment" type="textbox" disabled="true"/>
JS:
document.getElementById('menu').addEventListener('change', function() {
if (this.value == 2) {
document.getElementById('comment').disabled = false;
} else {
document.getElementById('comment').disabled = true;
}
});
Here's a fiddle.
Probably something like this.
HTML:
<select id="IDE">
<option value="0">Xcode</option>
<option value="1">Android Studio</option>
<option value="2">Others</option>
</select>
<input id="comment_box" type="textbox" disabled="true"/>
JS:
document.getElementById('IDE').addEventListener('change', function() {
if (this.value == 2) {
document.getElementById('comment_box').disabled = false;
} else {
document.getElementById('comment_box').disabled = true;
}
});
Here's a fiddle.

Enable / Disable submit button on a dropkick enabled form?

I have a form styled with jQuery's Dropkick however I'm unable enable / disable a submit button once the forms get the style. The JS validation works as expected without Dropkick.
The HTML:
<form method="get" id="dropkickform" action="">
<select id="min" class="list">
<option selected="selected" value="">Selection 1</option>
<option value="1">100</option>
<option value="2">200</option>
</select>
<select id="max" class="list">
<option selected="selected" value="">Selection 2</option>
<option value="1">500</option>
<option value="2">600</option>
</select>
<input type="submit" value="Submit"/>
</form>
The JS:
$('.list').dropkick();
$(document).ready(function () {
$form = $('#dropkickform');
$form.find(':input[type="submit"]').prop('disabled', true);
$form.find(':input').change(function () {
var disable = false;
$form.find(':input').not('[type="submit"]').each(function (i, el) {
if ($.trim(el.value) === '') {
disable = true;
}
});
$form.find(':input[type="submit"]').prop('disabled', disable);
});
});
http://jsfiddle.net/L3FCV/
From what I can see once you apply dropkick it will not update the selects behind the scenes so your validation will not work because of that (the selects have the initial option selected all the time, have a look in firebug/chrome web inspector to see it).
I've been able to get close with http://jsfiddle.net/Qguh5/ but it does break sometimes.
I used:
$('.list').dropkick({
change: function(value, label){
var disable = true;
$('.dk_option_current > a').each(function(){
if($(this).data('dk-dropdown-value')){
disable = false;
} else {
disable = true;
}
});
$form.find(':input[type="submit"]').prop('disabled',disable);
}
});
The change event is mentioned on the dropkick page.
I suggest you give http://uniformjs.com a try if you want custom looking forms. It might not be as pretty as dropkick but it is a lot easier to use in your scenario.

Categories

Resources