BobbyJones BobbyJones - 6 months ago 7
HTML Question

Using jQuery to validate checkboxes and input text values

I need your help,

Is there a way one can possible use the all so powerful jQuery to validate the following conditions before enabling button?


  1. If the user inputs a value in the text box and then checks one of the checkboxes, then enable the button

  2. If the user already has a value present in the text, and then checks one of the checkboxes, then enable the button



How can this be written in jQuery, from my perspective this would some lenghty form field checking no?

Here's the HTML markup:

<!DOCTYPE html>

<html>

<head>

</head>

<body>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">

</body>

</html>

Answer

This might get you started. You can make the field validation as complex or simple as you wish.

$('input[type=checkbox]').click(function(){
   var tmp = $(this).next('input').val();
   //validate tmp, for example:
   if (tmp.length > 1){
     //alert('Text field has a value');
     $('#mybutt').prop('disabled',false);
   }else{ 
     //alert('Please provide a long value in text field');
     $('#mybutt').prop('disabled', true);
     $(this).prop('checked',false);
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <input id="mybutt" type="button" value="Add To Calendar" disabled>
    <br>
    <input type="checkbox" name="dategroup"><input type="text" id="date1">
    <br>
    <input type="checkbox" name="dategroup"><input type="text" id="date2">
    <br>
    <input type="checkbox" name="dategroup"><input type="text" id="date3">