Validating multiple select box - javascript

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.

Related

Hide an option in a multiple select, when a specific option has been selected from another select

I have seen questions similar to this but mine is different.
so I have these first 2 dropdown menu (data are selected from my database) and another dropdown which is attributed with multiple,
now my code works on the first 2 dropdowns but when it comes to the multiple dropdown it's not working.
here are my dropdown menu;
<select class="custom-select" name="option_one">
<option>test1</option>
<option>test2</option>
<select class="custom-select" name="option_two">
<option>test1</option>
<option>test2</option>
<select id="multiple" class="custom-select" name="option_three[]" multiple="multiple">
<option>test1</option>
<option>test2</option>
Here is my javascript
$(document).ready(function() {
function intializeSelect() {
$('.custom-select').each(function(box) {
var value = $('.custom-select')[box].value;
if (value) {
$('.custom-select').not(this).find('option[value="' + value + '"]').hide();
}
});
};
intializeSelect();
$('.custom-select').on('change', function(event) {
$('.custom-select').find('option').show();
});
});
With a single on change attached to all select , you could check value and hide depending on innerHtml or value ( in your case no value , so checking by text) ,
What I've done is first showing all option , then check value if not undefined ,
if thre were a value hide other options input , that has same text value ,
See below working snippet :
$(document).ready(function() {
$('.custom-select').on('change', function(event) {
let value = $(this).val();
// show all options of all select
$('.custom-select').find("option").show();
// reset values after change of other select
$('.custom-select').not(this).val("");
if (value.length > 0) {
$('.custom-select')
.not(this)
.find("option")
.filter(function() {
return $(this).html() == value;
}).hide();
};
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="custom-select" name="option_one">
<option></option>
<option>test1</option>
<option>test2</option>
</select>
<select class="custom-select" name="option_two">
<option></option>
<option>test1</option>
<option>test2</option>
</select>
<select id="multiple" class="custom-select" name="option_three[]" multiple="multiple">
<option></option>
<option>test1</option>
<option>test2</option>
</select>

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;

Disabled option from select box if already selected

I have a table with id = fields-list and inside this table 4 select box with the same class db-list. Now I want if the option in first select is selected disable this option in the rest of selectbox
<table id="fields-list" class="table table-hover">
<select class="form-control db-list" >
<option value="">All</option>
<option value="d">1</option>
<option value="t">2</option>
<option value="t">3</option>
<option value="h">4</option>
</select>
<select class="form-control db-list" >
<option value="">All</option>
<option value="d">1</option>
<option value="t">2</option>
<option value="t">3</option>
<option value="h">4</option>
</select>
</table>
I tried like this :
$('.db-list').on('change', function () {
if( $('#fields-list').find('select option[value='+$(this).val()+']:selected').length>1){
$(this).val($(this).find("option:first").val()).prop('disabled', true);
}
});
But not work. Can you help me please ? Thx in advance and sorry for my english.
Situations how need to work :
1. First Select choose option 1 (all select box from the page should disable option 1);
2. Second Select choose option 3 (all select box from the page should disable option 3 + option 1 from previous selectd)
3. First Select choose option 4 (now all select box should disable option 4 + option 3 and enable option 1)
table should be changed to something else, div for example, because table should contain thead, tbody or tr
this line:
$(this).val($(this).find("option:first").val()).prop('disabled', true);
will disable select, but not option, so try this:
$('#fields-list').find('select option[value='+$(this).val()+']:not(:selected)').prop('disabled', true);
working example
$('.db-list').on('focus', function () {
var ddl = $(this);
ddl.data('previous', ddl.val());
}).on('change', function () {
var ddl = $(this);
var previous = ddl.data('previous');
ddl.data('previous', ddl.val());
if (previous) {
$('#fields-list').find('select option[value='+previous+']').removeAttr('disabled');
}
$('#fields-list').find('select option[value='+$(this).val()+']:not(:selected)').prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fields-list" class="table table-hover">
<select class="form-control db-list" >
<option value="">All</option>
<option value="d">1</option>
<option value="t">2</option>
<option value="t">3</option>
<option value="h">4</option>
</select>
<select class="form-control db-list" >
<option value="">All</option>
<option value="d">1</option>
<option value="t">2</option>
<option value="t">3</option>
<option value="h">4</option>
</select>
</div>
You can use .filter() to get options with a similar value
$('select').on('change', function() {
$('option').prop('disabled', false);
$('select').each(function() {
var val = this.value;
$('select').not(this).find('option').filter(function() {
return this.value === val;
}).prop('disabled', true);
});
}).change();
$('.db-list:first').on('change', function () {
// enable all first
$('.db-list:last option').prop('disabled', false);
// disable the selected value
$('.db-list:last option[value="'+ $(this).val() +'"]').prop('disabled', true);
});
And by the way, option's shouldn't have the same value in one select option.

pass element ID as a parameter to jquery

I have a select box on a web form that, depending on what is selected, will show a hidden div.
<script>
$(document).ready(function () {
$("#Select1").change(function () {
$(this).find("option:selected").each(function(){
if($(this).attr("Value")=="2"){
$("#hiddentable11").show();
}
else if($(this).attr("Value")=="3"){
$("#hiddentable11").show();
}
else{
$("#hiddentable11").hide();
}
});
}).change();
});
</script>
The form will have 35 to 40 of these Select box/hidden div combinations. The option values in the select boxes will all be the same every time (0,1,2,3,4). If the user chooses option 2 or 3 for Select1, hiddentable11 appears. If they choose option 2 or 3 for Select2, hiddentable 12 appears I don't want to copy/paste this code 40 times and in the code change Select1/hiddentable11 to Select2/hiddentable12, Select3/hiddentable13 etc. How do I change this code so that I can reuse it for all of the select/div combinations?
Give all the select boxes a class, e.g. class="select". Then you can usethis.id` to get the ID of the target element, and concatenate it to the DIV id.
$(".select").change(function() {
var num = this.id.slice(6); // get N from id="SelectN"
$("#hiddentable1" + num).toggle($(this).val() == "2" || $(this).val() == "3"));
});
Then just make a .Select class, and use this, pass in the corresponding hidden table as a user defined unique data attribute (I'll use data-hidden as an example). Then you can create the proper selector for each item by doing "#"+$(this).attr("data-hidden"):
$(".Select").change(function () {
$(this).find("option:selected").each(function(){
if($(this).attr("Value")=="2") {
$("#"+$(this).attr("data-hidden")).show();
}
else if($(this).attr("Value")=="3") {
$("#"+$(this).attr("data-hidden")).show();
}
else {
$("#"+$(this).attr("data-hidden")).hide();
}
});
}).change();
Try this. With this you don't need to depend on ID's. You may multiple select boxes to your code and table combo and never have to change your js code.
<select id="select1">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable11">
Hidden Contents of Select1
</div>
<select id="select2">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable12">
Hidden Contents of Select2
</div>
<select id="select3">
<option val="0">0</option>
<option val="1">1</option>
<option val="2">2</option>
<option val="3">3</option>
<option val="4">4</option>
</select>
<div id="hiddentable13">
Hidden Contents of Select3
</div>
$("select").change(function () {
var index = $('select').index($(this));
index++;
var $this = $(this).find("option:selected").val();
$("#hiddentable1" + index).css("display", $this === "2" || $this === "3" ? "inline-block" : "none");
});
http://jsfiddle.net/njzatgku/1/

Showing and hiding select boxes using javascript/

I have a little bit of test code that intends to have a select box display when a certain option is selected and then hide when that option is changed.
HTML:
<form>
<select id="sel1" name="sel1" class="chzn-select">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="sel2" name="sel2" selected="selected" style="display:none">
<option value="1">1</option>
<option value="2">2</option>
</select>
</form>
JS:
var selCategory = $('#sel1');
$(selCategory).change(function () {
$('option:selected').each(function () {
if ($(this).text() ==='2') {
$('#sel2').show();
}
else if($(this).text() ==='1') {
$('#sel2').hide();
}
else if($(this).text() ==='3') {
$('#sel2').hide();
}
});
});
This bit of code works great if only this:
if ($(this).text() ==='2') {
$('#sel2').show();
}
Is the JavaScript but falls down when adding the else if statements. Also would it be better to display the select box itself or a containing div Tag? The only reason the second select box isn't a chosen-select is that chosen doesn't seem to like elements that are already hidden (problems with width).
Any help would be appreciated.
Your $('option:selected') selector is looking at the options from all select elements, not just #sel1. So #sel2 is shown (due to "2" selected in the #sel1), then immediately hidden (due to "1" selected in #sel2 itself). Make sure you're looking only at the value you want:
var selCategory = $('#sel1');
selCategory.change(function () {
selCategory.find('option:selected').each(function () {
if ($(this).text() =='2') {
$('#sel2').show();
}
else {
$('#sel2').hide();
}
});
});
I would make it easier, grab the value and concatenate the sel ID from that:
$("#sel1").change(function() {
$("select:not(#sel1)").hide(); //hide other selects, excluding #sel1
$("#sel" + this.value).show();
});

Categories

Resources