Xtreme
Xtreme

Reputation: 1601

Bootstrap required validation to select one of the dropdown

I have this fiddle (from my project) https://jsfiddle.net/autofiddle/cap6g9wq/20/

I want to have customer name and the first dropdown required as it is.

Depending on what you choose in the first dropdown, another dropdown with numbers is displayed.

I want to validate errors (display div id = "quantity-zero") when you click the button if all the dropdown is 0. If any dropdown is more than 0, the validation is ok.

I have tested like this (think there is a better way) but its not working and I want to connect it to bootstrap validation and don't just make the div visible in the loop below.

var totalQuantity = 0;

$(".quantity-select").each(function () {
    if(parseInt($(this).val()) === 0) {
        //display the bootstrap error.
        //don't want it like this: $( "#quantity-zero" ).show();
    }
})

Upvotes: 0

Views: 843

Answers (2)

Refilon
Refilon

Reputation: 3499

The select does not have a value. You should get the value from the selected option, probably something like this:

$(".quantity-select option:selected").val();

EDIT:

If you want to check all the visible dropdowns you can use the following code:

$('.quantity-select:visible').each(function(){
    $(this).find('option:selected').val();
});

The $(this).find('option:selected').val(); is the value of the selected dropdown. So you can make a check in the each statement and maybe set a var to true or false depending on the value.

Upvotes: 0

Amine KOUIS
Amine KOUIS

Reputation: 1459

You can validate your form by using jQuery Validation Plugin, you don't need to add required on tag, just by adding some rules like the code below :

$("#order-form").validate({
    rules: {
        customerName: "required",
        caseSelect: "required",
    },
    messages: {
        customerName: "Please enter a customer namn.",
        caseSelect: "You need to select a quantity for your case.",
    }
});

try this fiddle : https://jsfiddle.net/g5y9ho3x/

Upvotes: 2

Related Questions