简体   繁体   中英

How to validate dynamic select DropDown using html and javascript?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM