DCJones DCJones - 2 months ago 12
jQuery Question

Jquery, validating input before form submission

I am writing a small jquery function that should check the selected input of four items. The selcted itmes are "time" in hours and minutes displayed as dropdown lists.

I have "From" hours and "From" minutes, "To" hours and "To" minutes.

I want to make sure that the "From" hours and minutes are less that the "To" hours and minuets and until this is correct hide the form submission button.

This is what I have:

function getvalHT(sel) {
var selectedFromHours = $('#RoomFromTimeH').val();
selectedFromHours = selectedFromHours.replace(/\b0+/g, '');
var selectedToHours = $('#RoomToTimeH').val();
selectedToHours = selectedToHours.replace(/\b0+/g, '');

var selectedFromMin = $('#RoomFromTimeM').val();
selectedFromMin = selectedFromMin.replace(/\b0+/g, '');
var selectedToMin = $('#RoomToTimeM').val();
selectedToMin = selectedToMin.replace(/\b0+/g, '');

if(selectedFromHours < selectedToHours) {
alert ('The "To" hours must be greater than the "From" hours');
} else if(selectedFromMin > selectedToMin) {
alert ('The "To" minutes must be greater than the "From" minutes');
} else {


<select name="RoomToTimeH" id="RoomToTimeH" class="imaindateselTime" onchange="getvalHT(this);">

<select name="RoomToTimeM" id="RoomToTimeM" class="imaindateselTime" onchange="getvalHT(this);">

I have this part working but the submit button does not appear if the user selects the correct times.

Am I doing this correctly or am I way off.

Many thanks for your time.


Problem : if(selectedFromHours < selectedToHours) { the From hour is lesser than To hour so its valid But you are considering it as invalid. Also you should not check the Minutes unless the Hours are equal.


The if logic must change a bit.

if(selectedFromHours < selectedToHours) {       
    $("#savebutton").show(); // since From hour is smaller don't care about minutes
} else if(selectedFromHours == selectedToHours && selectedFromMin < selectedToMin){
  $("#savebutton").show(); //Hours are same but from minute is smaller - VALID
}else {
  $("#savebutton").hide();  // any other condition hide the button

Explaining the logic

  • if(selectedFromHours < selectedToHours) { : If the From hour is lesser than To then there is no need to check for minutes. This is VALID
  • else if(selectedFromHours == selectedToHours && selectedFromMin < selectedToMin){ : If the From and To Hour are equal then we need to check the Minutes, From minutes must be smaller than To minutes. This is VALID
  • Any other condition is NOT VALID