1

I have a simply question but I try many things but they not working as I expect.

Problem: 1. A few checkboxes with class like "a" ,"b" ,"c" but with different id's. 2. On button click I try to validate that only one of checkboxes is checked. 3. I know only checkbox classes(The common element)

My code:

$('#submit').click(function() {
    var matches = [];
    var items = document.getElementsByClassName('1'); //??? if the items is null?

    for (var i = 0; i < items.length; i++){
        matches.push({id:items[i].id, value:items[i].value});
    }

    if((matches[0].id != matches[1].id) &&(matches[0].value == matches[1].value))
        alert("ERROR!!!");
});

Please show me the best way to resolve that problem

Adamo
  • 586
  • 1
  • 9
  • 28

2 Answers2

2

You're using jQuery. You want to use checkboxes with classname "1" almost as if they were radio buttons, and alert an error if more than one is checked. Your classname is invalid, and most likely you should be checking this on form submit instead, but here's the code you're looking for.

$('#submit').click(function() {
    if ($('.1:checked').length > 1) alert('error');
});

...And I imagine you would also want to stop the button from submitting the form in that case:

$('#submit').click(function(e) {
    if ($('.1:checked').length > 1) {
        e.preventDefault();
        alert('error');
    }
});
Community
  • 1
  • 1
Popnoodles
  • 28,090
  • 2
  • 45
  • 53
1
See this code it may be help you!
<input type = "checkbox" class = "a ownClass" id = "one"></input>
<input type = "checkbox" class = "b ownClass" id = "two"></input>
<input type = "checkbox" class = "c ownClass" id = "three"></input>
<input type = "button" id = "submit" value = "submit"></input>


  (function(){
        $("#submit").click(function(){
        var checked = [];
        $(".ownClass").each(function(currIndex, val){
        if($(this).is(':checked')){
            checked.push(this.id);
        }

     })
    console.log(checked);
  });
}());