How to validate dynamic select DropDown using html and javascript? - javascript

I have a form having education details in which there is a dropdown which gives 4 option
schooling
graduation
post graduation
others
now what I am doing is allowing user to fill those details but what I want is user can not select one education type more than once which means user can select schooling once,graduation once and so on and this validation i want on client end which is js/jquery
image for reference
function checkUserEducation() {
const userSelectedEducationArray = $("select[name='educationType[]']").map(function() {
return $(this).val();
}).get();
//checks if any education type is empty
if (userSelectedEducationArray.includes("")) {
$('#educationErrorMsg').show();
} else {
$('#educationErrorMsg').hide();
}
if (countElement('schooling', userSelectedEducationArray) > 1) {
// $('#educationErrorMsg').show();
$('#educationErrorMsg').after("*schooling can be chosen only one time");
} else {
}
if (countElement('graduation', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').after("</br>*graduation can be chosen only one time");
} else {
}
if (countElement('post_graduation', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').after("</br>*post graduation can be chosen only one time");
} else {
}
if (countElement('others', userSelectedEducationArray) > 1) {
$('#educationErrorMsg').html("</br>*others can be chosen only one time");
} else {
}
}
function countElement(item, array) {
var count = 0;
$.each(array, function(i, v) { if (v === item) count++; });
return count;
}
this validation i am trying to do but i am not getting appropriate outcome
so any help regarding this
<select class="form-control" id="educationType" name="educationType[]" aria-label="Select Education Type">
<option selected value="">Select type</option>
<option value="schooling">Schooling</option>
<option value="graduation">Graduation</option>
<option value="post_graduation">Post Graduation</option>
<option value="others">Others</option>
</select>
this is my select dropdown on which i want validation
so any hints or validation tips would be very helpful
THANK YOU !!

English is not my primary language but i'll try my best to explain.
Give same class to all selects that you want to check
then on change function loop through all element with given class
if you're using form-repeater then compare name of the elements to avoid comparing with the same element. if you are not using form-repeater add a "data-counter" element add increase its value on every new add,
after that just compare value of the element, if same then show alert
var count = 1;
$(document).on("click", ".add-btn", function () {
$("#clone")
.find(".gg").addClass('test-select')
.attr("data-counter", count++);
$("#Main").append($("#clone").html());
$("#clone")
.find(".gg").removeClass('test-select');
});
$(document).on("change", ".test-select", function () {
const This = $(this);
$(".test-select").map(function() {
if(this.getAttribute('data-counter') !== $(This).attr('data-counter')){
if($(this).val() == $(This).val()){
alert('repeat');
$(This).css('background-color','red')
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>stack question</title>
</head>
<body>
<div id="Main" class="row p-1">
<div class="col-md-8">
<select class="form-select test-select" data-counter="0" name="test[]" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary add-btn">Add</button>
</div>
</div>
<div class="d-none" id="clone">
<div class="mt-2"></div>
<div class="col-md-8">
<select class="form-select gg test-select" data-counter="" name="test[]" aria-label="Default select example">
<option selected>Open this select menu</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
<div class="col-md-4">
<button type="button" class="btn btn-primary add-btn">Add</button>
</div>
</div>
</body>
</html>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$("#educationType").change(function(){
if($(this).val() && !$(this).find('option:selected').attr("data-clicked")){
$(this).find('option:selected').attr("data-clicked","true")
}else if($(this).find('option:selected').attr("data-clicked")){
alert(`"${$(this).val().toUpperCase()}" can be chosen only one time`);
$(this).val("")
}
})
</script>

Related

How to add the fourth option in dropdown list using JQuery and HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/css/bootstrap.min.css">
</head>
<body>
<!-- Based on https://codepen.io/bahiirwa/pen/OjNYZb -->
<div class="container">
<h2>Demo dependent lists</h2>
<div class="row">
<div class="col-md-3">
<select class="form-control" name="select1" id="select1">
<option value="">--Please choose an option--</option>
<option value="1000">1000</option>
<option value="1500">1500</option>
<option value="1800">1800</option>
<option value="2000">2000</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" name="select2" id="select2">
<option value="1000" data-section1="1000">500</option>
<option value="1500" data-section1="1500">750</option>
<option value="1800" data-section1="1800">900</option>
<option value="2000" data-section1="2000">1000</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" name="select3" id="select3">
<option value="1000" data-section2="1000">250</option>
<option value="1500" data-section2="1000">450</option>
<option value="1800" data-section2="1000">500</option>
<option value="2000" data-section2="1000">750</option>
</select>
</div>
<div class="col-md-3">
<select class="form-control" name="select4" id="select4">
<option value="1000" data-section3="1000">250</option>
<option value="1500" data-section3="1000">450</option>
<option value="1800" data-section3="1000">500</option>
<option value="2000" data-section3="1000">750</option>
</select>
</div>
</div>
</div>
</body>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.5.1/dist/jquery.slim.min.js"></script>
<!-- Popper JS -->
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
//Reference: https://jsfiddle.net/fwv18zo1/
$(document).ready(function() {
var $order_name = $('#order-name');
var $output = $('#output');
var $select1 = $('#select1');
var $select2 = $('#select2');
var $select3 = $('#select3');
var $select4 = $('#select4');
var $options2 = $select2.find('option');
var $options3 = $select3.find('option');
var $options4 = $select4.find('option');
$select1.on('change', function(event) {
$select2.html(
$options2.filter(
function() {
return $(this).data('section1') == $select1[0].selectedOptions[0].value;
}
)
);
$select2.trigger('change');
}).trigger('change');
$select2.on('change', function(event) {
$select3.html(
$options3.filter(
function() {
return $(this).val() == $select2[0].selectedOptions[0].value;
}
)
);
}).trigger('change');
$select3.on('change', function(event) {
$select4.html(
$options4.filter(
function() {
return $(this).val() == $select3[0].selectedOptions[0].value;
}
)
);
}).trigger('change');
$select4.on('change', function(event) {
$select3.html(
$options4.filter(
function() {
// return $(this).data('section3') == $select4[0].selectedOptions[0].value;
return $(this).val() == $select4[0].selectedOptions[0].value;
}
)
);
}).trigger('change');
});
</script>
</html>
In this code, I am unable to do the thing which is happening in the second and third options, but not in the fourth option. I have created a demo dependent lists in which when user chooses the first option then the second option automatically comes with filtered data. Then again user have to select from the third option filtered data, but in the fourth option it doesn't automatically fetch the filtered data instead it's asking the user to select data from given options which the code doesn't want. For example, suppose I have chosen the first option 1000, then in the second option 500 comes automatically similarly in the third option but not in the fourth option. How can I code so that the fourth option also comes automatically filtered data.

Passing value from input field to selectbox option

Selectbox used for city name in application form
<select id="city" class="custom-select form-control" name="jobman-field-7[]">
<option value="" selected></option>
<option value="Other">Other Please Specify</option>
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
</select>
Input field shows when 'OTHER' selected from a Selectbox above
<div class="form-group" id="other-city">
<label>Enter your city here</label>
<input name="other-city" value="" type="text" class="form-control">
</div>
Javascript to toggle the fields
$(document).ready(function () {
toggleFields();
$("#city").change(function () {
toggleFields();
});
});
function toggleFields() {
if ($("#city").val() == 'Other') {
$("#other-city").show();
} else {
$("#other-city").hide();
}
}
Here your approach doesn't look meaningful I guess. You have options in your select box being retrieved from DB, appending user input as an option does not make your new data reflected in DB. Better try to trigger an ajax call to insert data into city column in your DB table when the form is submitted. This could be one way to solve your requirement so next time when a user visits page, the new result will be retrieved and shown in the select box again.
//I NEED SOMETHING LIKE THIS BUT OTHER and the NEW CITY get selected Can we only select one city when added?
<select multiple id="city">
<option value="PickCity"></option>
<option value="Other">Other Please Specify</option>
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
</select>
<input type="text" id="other-city">
$().ready(function() {
$('#other-city').change(function() {
var option = new Option($('#other-city').val(), "value");
$('#city option:selected').append(option);
});
});
Note: I havent added the saving to db part; Hope u can handle that;
I have focused on passing value from input box to dropdown;
Please see if this helps you
<!DOCTYPE html>
<html>
<body>
<head>
<meta charset="utf-8">
<title></title>
<meta name="author" content="">
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="city-form" onsubmit="return addCitytoDropDown()" method="POST">
<div class="form-group" id="other-city">
<label>Enter your city here</label>
<input name="other-city" type="text" class="form-control" id="inputBox">
</div>
</form>
<select id="city" class="custom-select form-control" name="jobman-field-7[]">
<option value="PickCity" selected>Pick a City</option>
<option value="Other">Other Please Specify</option>
<option value="Lahore">Lahore</option>
<option value="Karachi">Karachi</option>
<option value="Islamabad">Islamabad</option>
</select>
<script type="text/javascript">
function addCitytoDropDown(){
var x = document.getElementById("city");
var option = document.createElement("option");
var newCity = document.getElementById("inputBox").value;
option.text = newCity;
option.selected = true;
x.add(option);
return false;
}
</script>
</body>
</html>

javascript jquery chosen not working

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JavaScript</title>
</head>
<body>
<h1 id="hey">List King</h1>
<div class="Select-DB">
<select id="DB" class="chosen-select" title="Select Database" data-placeholder="Select database you want!" style="width: 300px;">
<option value=""></option>
<option value="Pubchem3D"> Pubchem3D</option>
<option value="molport"> Molport</option>
<option value="ChemAxon"> ChemAxon</option>
<option value="ChemSpider"> ChemSpider</option>
</select>
</div>
<script src="jquery-1.12.4.js" type="text/javascript"></script>
<script src="chosen_v1.6.2/chosen.jquery.js" type="text/javascript"></script>
<script src="ff.js" type="text/javascript"></script>
</body>
</html>
jquery chosen not working, what's wrong in my code?
My select tag just appear as default form....
p.s. Jquery code is located in another file ("ff.js")
$(document).ready(function(){
$(".chosen-select").chosen({no_results_text: "Sorry, We don't have such database ;-)"});
});
You need to change your javascript file like this
$('.chosen-select').change(function(){
var aaa = $("#DB").val(); // get option value
if(aaa === '') {
// user select empty item
console.log("Sorry, We don't have such database ;-)");
}
else{
// user select valid item
console.log(aaa);
}
});
How about using on change event?
$('.chosen-select').change(function(){
console.log(this.val());
});
I don't quite understand your question but try this
LINK
HTML
<h1 id="hey">List King</h1>
<div class="Select-DB">
<select id="DB" class="chosen-select" title="Select Database" data-placeholder="Select database you want!" style="width: 300px;">
<option value=""></option>
<option value="Pubchem3D"> Pubchem3D</option>
<option value="molport"> Molport</option>
<option value="ChemAxon"> ChemAxon</option>
<option value="ChemSpider"> ChemSpider</option>
</select>
</div>
JS
$('.chosen-select').change(function(){
var aaa = $("#DB").val();
if(aaa != ""){
console.log(aaa);
}
else{
console.log("Sorry, We don't have such database ;-)");
}
});

How to change border color of Bootstrap-select

For a custom framework like Bootstrap select https://silviomoreto.github.io/bootstrap-select/ how do I change the border color of a select box in Javascript?
I tried this but does not work.
document.getElementById("box").style.borderColor = "red";
Javascript
function validate() {
var ok = true;
var box = document.getElementById("box").value;
if (!box) {
document.getElementById("box").style.borderColor = "red";
ok = false;
}
return ok;
}
HTML
<form action="#" onsubmit="return validate()" method="POST">
<select id="box" name="num" class="selectpicker form-control">
<option value="" selected="selected">select number</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="text-center">
<button type="submit" class="btn btn-primary">submit</button>
</div>
</form>
If you see the DOM element generated by bootstrap-select, it actually hides the original select element and creates its own structure with div,span and buttons. There isn't any official documentation provided to change its border, but as a workaround you could do it as below:
You need to change border of the button whose class is btn dropdown-toggle btn-default, which is generated by bootstrap-select. Since the element created will not be given any id we will make use of its class with document.getElementsByClassName("classnames")[0]
document.getElementsByClassName("btn dropdown-toggle btn-default")[0].style.borderColor = "red";
Update
Explanation in comments.
$(document).ready(function() {
//add a change event to each selectpicker
$('.selectpicker').selectpicker().on('change', function() {
var id = $(this).attr('id'); //get current element's id
var selected = $(this).find("option:selected").val(); //get current element's selected value
var condition = false; //default false to form valid
$(this).selectpicker('setStyle', 'btn-danger', selected == "" ? "add" : "remove");
if (id == "box") {//if its first select box
condition = !(selected == 2 || selected == ""); //check if its value==2 or value=="" so that form validation depends of respective selects
$("#box2").selectpicker(selected == 2 ? "show" : "hide").val("");
//show or hide box2 based on selected val
$("#box2").selectpicker('setStyle', 'btn-danger',"remove");
//remove danger from 2nd selectpicker when its hidden or shown
} else {
condition = !(selected == "");
//if its box 2 check if any value is selected
}
$(this).closest('form').data('valid', condition);
//set it to form's data-valid attribute
});
$("#box2").selectpicker('hide');//default hide on page load
//form submit event instead of validate() inline function
$("form").on("submit", function(e) {
e.preventDefault();//prevent default action of submit
var isValid = $(this).data('valid');//check if its valid
if (!isValid) {
//if not valid loop through each selectpicker
$.each($('.selectpicker'),function(){
var selected=$(this).val();
//check appropriate values for each select and set/remove the btn-danger class for respective selectpickers
$(this).selectpicker('setStyle', 'btn-danger', selected == "" ? "add" : "remove");
})
}
else{
alert(isValid);
//Submit your form
}
})
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/css/bootstrap-select.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.10.0/js/bootstrap-select.min.js"></script>
<!--add data-valid attribute to form to make sure its valid or not and default to false-->
<form action="#" data-valid="false" method="POST">
<select id="box" name="num" class="selectpicker form-control">
<option value="" selected="selected">select number</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="box2" name="num" class="selectpicker form-control">
<option value="" selected="selected">select number</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<div class="text-center">
<button type="submit" class="btn btn-primary">submit</button>
</div>
</form>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet">
<link href="https://silviomoreto.github.io//css/highlight.css" rel="stylesheet">
<link href="https://silviomoreto.github.io//css/base.css" rel="stylesheet">
<link href="https://silviomoreto.github.io//css/custom.css" rel="stylesheet">
<link href="https://silviomoreto.github.io//dist/css/bootstrap-select.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div class="row">
<div class="col-xs-3">
<div class="form-group">
<select id="box" name="num" class="selectpicker form-control" data-style="warning">
<option value="" selected="selected">Select number</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="button" style="width: 180px; height: 30px" onclick="changeColor()" value="Validate"/>
</div>
</div>
</div>
</form>
<script>
function changeColor() {
document.getElementById("box").style.borderColor = "red";
document.getElementById("box").style.borderWidth = "1px";
return false;
}
</script>
</body>
</html>
You can override the CSS
.bootstrap-select{ border: 1px solid red //sample }
Hope this helps
Update:
By using JavaScript, this can be done as shown below (considering all required JS file as added already)
<form id="form1" runat="server">
<div class="row">
<div class="col-xs-3">
<div class="form-group">
<select id="box" name="num" class="selectpicker form-control" data-style="warning">
<option value="" selected="selected">Select number</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="button" style="width: 10px; height: 30px" onclick="changeColor()" value="Validate"></input>
</div>
</div>
</div>
</form>
<script>
function changeColor() {
document.getElementById("box").style.borderColor = "red";
document.getElementById("box").style.borderWidth = "1px";
return false;
}
</script>

How can I build multiple step selectors in HTML page?

I have a problem with HTML contact form.
For example I have that schema with element dependencies:
Where are many selectors and inputs depends on what is selected in previous steps.
How can I build that logic in HTML and Javascript (Jquery)?
For result I need to return one input hidden field, where are placed all selected values, for example:
Cash - at Compensa partners - Outside Riga - Serviss from selected option
Maybe there are some Jquery solutions for that purpose?
P.S. I can only use HTML pages
Minimal example: write out all the different selects and only show the relevant one. You can add all the other dependencies in a similar way. Building the selects dynamically will be less, but more complicated code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Example</title>
<style>
.hide {
display: none;
}
.show {
display: block;
}
</style>
</head>
<body>
<div id="claim">
<select>
<option value="default" disabled="disabled" selected="selected">Select a claim type</option>
<option value="cash">Cash</option>
<option value="repair">Repair</option>
<option value="glazing">Glazing</option>
</select>
</div>
<div id="cash" class="hide">
<select>
<option value="partners">At Compensa partners</option>
<option value="office">Compensa Office</option>
<option value="broken">Verhicle is broken</option>
</select>
</div>
<div id="repair" class="hide">
<select>
<option value="age">Car age</option>
<option value="place">Serviss place</option>
</select>
</div>
<script>
var dependencies = {
'claim' : {
'cash' : 'nextDep',
'repair' : 'nextDep',
'glazing' : 'nextDep'
}
};
document.querySelector('#claim select').addEventListener('change', function ( event ) {
var parentID = event.target.parentNode.id,
value = event.target.value;
Object.keys(dependencies[parentID]).forEach(function ( key ) {
var select = document.querySelector('#' + key),
currentClass = select.className;
if (select.id === value && currentClass === 'hide') select.className = 'show';
else if (currentClass !== 'hide') select.className = 'hide';
});
});
</script>
</body>
</html>

Categories

Resources