5

I am new to mvc3 and razor engine and I would like it so at least one checkbox is checked for the submit button to fire.

 <div class="editor-field">
      @Html.Label("item1")
      @Html.CheckBoxFor(Model => Model.item1)
      @Html.Label("item2")
      @Html.CheckBoxFor(Model => Model.item2)
      @Html.Label("item3")
      @Html.CheckBoxFor(Model => Model.item3)
 </div>
 <p>
     <input type="submit" value="Create" />
 </p>

I know that I would need some kind of label to render text if 0 checkboxes are selected and that each checkbox needs an id so I can look at their values but is there anything in mvc3 razor to make this simpler? Thanks

2 Answers 2

10

One way of many would be to

<input type="submit" value="Create" onclick="return submitWith();"/>
<span id="validationMessage" />

and in your javascript (you might have more here but keeping it simple)

function submitWith(){   
    var checkedCount = $("input:checked").length;
    var valid = checkedCount > 0;
    if(!valid){
         $('#validationMessage').html('You must select at least one option');
    }
    return valid ;        
}
Sign up to request clarification or add additional context in comments.

2 Comments

That's perfect, just what I needed. Thanks!
But it will work only for client side.. so better to check on both client and server scripts using custom validation.
0

Give Some valid Name attribute to check boxes.Name of each Check Box Should Be same.Lets Say: Name="CheckBoxForItems"

On button Click event of Create Button:(In js)
Declare array and use each function to check if any check box is checked:

var arr = new Array();
$('input[name="CheckBoxForItems"]:checked').each(function (i) {
                arr.push($(this).attr("id"));
            });

 if(arr.length > 0)
$("#ButtonId").submit();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.