简体   繁体   中英

Datepicker is required in php form with hidden input field

I'm creating a php form to post data. One of the elements is a Datepicker JS element. I pass the input from the datepicker to a hidden input field. Now I want this datepicker to be required. If I make the input field required it doesn't seems to work because it's hidden, and it must stay hidden. Anyone know the best way to do this?

The code:

<div class="col-md-4 col-sm-12 ">
    <div id="date"></div>
    <label>Datum geselecteerd: </label>
    <input type="hidden" id="datefield" name="date" required/>
    <script type="text/javascript">
        var selected;
        $('#date').datepicker({beforeShowDay: function(date){
            return [date.getDay() != 1 & date.getDay() != 2 & date.getDay() != 3 & date.getDay() != 5 & date.getDay() != 0, ''];
        }});
        $(function() {
            $('#date').datepicker({ dateFormat: "dd-mm-yy" });
            $('#date').on("change",function(){
                selected = $(this).val();
                document.getElementById('datefield').value = selected;
            });
        });
    </script>
</div>

you can use .submit() in jquery which is called when form is submitted and you can check if date field is filled. For more info here: https://api.jquery.com/submit/

Also you should check it with php where you process the data the form sent you and if it is not filled you should send user back to fill the form again with a warning that he didnt fill a field

example:

<form id="myform" action="" method="get">
<input type="hidden" id="datefield" name="date" />
<input type="submit" />
</form>
<script>
$( "#myform" ).submit(function( event ) {
   if(  $("#datefield").val().length === 0 ) {
    alert('not filled');
    }
  event.preventDefault();
});
</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