Tom
Tom

Reputation: 34356

Checkbox form validation jQuery

I have a form where a user can select a list of events, each event has the start time as a classname. When the form is submitted, I need to check if the user has selected more than one event with the same starttime.

e.g. In Today if the user selected Event A and Event C, it would trigger the validation message.

<form>

<h3>Today</h3>

    <input type="checkbox" name="date" class="starttime-1730" value="A" />Event A
    <input type="checkbox" name="date" class="starttime-1600" value="B" />Event B
    <input type="checkbox" name="date" class="starttime-1730" value="C" />Event C
    <input type="checkbox" name="date" class="starttime-1630" value="D" />Event D


<h3>Tomorrow</h3> 

    <input type="checkbox" name="date" class="starttime-1830" value="A" />Event A
    <input type="checkbox" name="date" class="starttime-1830" value="B" />Event B
    <input type="checkbox" name="date" class="starttime-1930" value="C" />Event C
    <input type="checkbox" name="date" class="starttime-2030" value="D" />Event D

<input type="submit" name="submit" />

</form>

Upvotes: 0

Views: 782

Answers (1)

Marius
Marius

Reputation: 58911

First of all, put the starttime in a data attribute, not a class (that is not what a class is for). For example:

<input type="checkbox" name="date" data-starttime="1730" value="A" />Event A

Next put the two days inside a fieldset, so you can check them with the same function:

<form id="form1">
<fieldset>
<caption>Today</caption>

    <input type="checkbox" name="date" data-starttime="1730" value="A" />Event A
    <input type="checkbox" name="date" data-starttime="1600" value="B" />Event B
    <input type="checkbox" name="date" data-starttime="1730" value="C" />Event C
    <input type="checkbox" name="date" data-starttime="1630" value="D" />Event D
</fieldset>
<fieldset>
<caption>Tomorrow</caption> 

    <input type="checkbox" name="date" data-starttime="1830" value="A" />Event A
    <input type="checkbox" name="date" data-starttime="1830" value="B" />Event B
    <input type="checkbox" name="date" data-starttime="1930" value="C" />Event C
    <input type="checkbox" name="date" data-starttime="2030" value="D" />Event D
</fieldset>
<input type="submit" name="submit" />
</form>

Here is the jQuery function for doing the matching. It has not been tested.

function submit(){
  $("#form1 fieldset").each(function(i){
    var hashmap = {};
    $("input:checked", $(i)).each(function(j){
      var mytime = $(j).data("starttime");
      if(hashmap[mytime] != undefined){
        //Collision, report it or something
      }else{
        hashmap[mytime] = 1;
      }
    });
  });
}

Upvotes: 1

Related Questions