user982124 user982124 - 26 days ago 12
HTML Question

Check Hidden Form Input has Value on Form Submit

I have a form with a hidden input:

<input type="hidden" name="productID" id="productID" value="">


I have a hidden Alert (using Bootstrap for this):



<div id="alert_ajax_error" class="alert alert-danger text-center" role="alert" style="display:none">
You have not made a selection. Please select an Item and try again
</div>

<div class="text-center">
<button type="submit" name="buttonType" value="saveSelected" class="btn btn-success">Submit</button>
</div>





The hidden form input is populated via another script when users select from a table - it adds the productID as the value of the input.

I would now like to add some client side validation (have server side validation in place) so that if the user clicks Submit it checks to see if they have made a selection by checking for the presence of the hidden input to see if it has a value - if it is empty it will then show the hidden alert:

$("#alert_ajax_error").show();


I'm not sure if it's possible to check a hidden input with Javascript/JQuery and how to go about this if it is possible.

Answer

Basically you will want to check the value on submit using an if statement

$("form").submit(function(event) {

     event.preventDefault();

     if($('#productID').val() == '') {

          $("#alert_ajax_error").show();

          return false;

     }

     //.... more form actions if good ....

});
Comments