Home > Mobile >  How to validate dynamic select DropDown using html and javascript?
How to validate dynamic select DropDown using html and javascript?

Time:03-15

I have a form having education details in which there is a dropdown which gives 4 option

  1. schooling
  2. graduation
  3. post graduation
  4. others

now what I am doing is giving user a form with select option and after that he can fill his details what i am checking is if user has selected schooling option two times or any other education type more than one time then i want to prompt a danger message to user that a education type must be chosen only one time

and this validation i want using js

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  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 !!

CodePudding user response:

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/[email protected]/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" >
  <div >
    <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 >
    <button type="button" >Add</button>
  </div>
</div>

<div  id="clone">
  <div ></div>
  <div >
    <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 >
    <button type="button" >Add</button>
  </div>
</div>
</body>
</html>

CodePudding user response:

 <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