Coen
Coen

Reputation: 73

Jquery if one of the two checkboxes is checked in list.

I have a form which contains two lists of radio checkboxes.

I need a validation check wether one checkbox is checked in either list. To illustrate:

   <form>
    <input type="radio" name="1">
    <input type="radio" name="1">

    <input type="radio" name="2">
    <input type="radio" name="2">

    <button type="submit"></button>
    </form>

so when the form submits, it needs to check wether a checkbox is checked in 'name1' or in 'name2' or in both. If not,it should not let the request through, and give an error message: "This is required". I tried doing this in Jquery with the following code:

$("#submit").on("click",function(){
      if ($("input[name*='name1']:checked") || $("input[name*='name2']:checked")) {
        $("form").submit(function(e){
                e.preventDefault();
            });

        $('#segmentError').toggle();

        if($("#Error").is(':visible')) {
          $("html, body").animate({scrollTop: $("#scrollHere").offset().top});
        }
      }
      return true;
    });

However, now it won't let the request through whatsoever. I'm not that good with JQuery, so I hope one of you can help me with this problem.

Upvotes: 0

Views: 1974

Answers (6)

Daerik
Daerik

Reputation: 4277

$('button[type="submit"]').on('click', function(event) {
  event.preventDefault();
  if($('input[type="radio"]:checked').val()) {
    $('form').submit();
  } else {
    $('.error-container').text('This is required');
  }
});
<p class="error-container"></p>
<form>
  <input type="radio" name="1">
  <input type="radio" name="1">
  <input type="radio" name="2">
  <input type="radio" name="2">
  <button type="submit">Submit</button>
</form>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

Upvotes: 1

fons
fons

Reputation: 94

After looking at your code I see a couple of issues you need to update in order to make it work:

1. Assign an id to the submit button in order to reference it later in jQuery:

<button id="submit" type="submit"></button>

2. Update the if clause as follows:

if ( $("input[name='1']:checked").val() && $("input[name='2']:checked").val() )


Working snippet

$("#submit").on("click", function() {

  if ($("input[name='1']:checked").val() && $("input[name='2']:checked").val()) {
    alert("input checked in list 1 and input checked in list 2");
  } else {
    alert("some checked radio buttons are missing")
  }

  return true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form>
  <input type="radio" name="1">
  <input type="radio" name="1">

  <input type="radio" name="2">
  <input type="radio" name="2">

  <button id="submit" type="submit"></button>
</form>

Upvotes: 1

p.phresh
p.phresh

Reputation: 36

As said in the other answers...

fixed and put it into a working fiddle

$("input[name='name1']").is(':checked')

use the ".is(':checked') to test if selected

https://jsfiddle.net/zjhtye8c/2/

Upvotes: 1

Adri&#225;n E
Adri&#225;n E

Reputation: 1681

There are many things I see wrong in your snippet.

  1. You are using #submit but the submit button does not have an id set
  2. You are using name = 'name1' in your javascript but the name in the HTML is name="1" (name1 vs 1). So they do not match.

Here is a sample JSFiddle to show you how to check whether each of the pairs of checkboxes is checked.

https://jsfiddle.net/bwahhpnd/

Basically you can use:

$("input[name='1']:checked").length

To see if any of the inputs are checked (if length is 0 none is checked).

Upvotes: 2

silentsod
silentsod

Reputation: 8335

Four things:

Your selector has an error, it's looking for names like "name1" and not names like "1": $("input[name*='1']:checked").length > 0 || $("input[name*='2']:checked")).length > 0 Also, you need to check how many elements were grabbed with the .length check

The other is that your submit button does not have id="submit" on it and so the click event is not bound.

Finally, you need to bind prevent default earlier:

$("form").submit(function(e){
                e.preventDefault();
            });

$("#submit").on("click",function(){
console.log("clicky");
console.log($("input[name*='1']:checked"));
      if ($("input[name*='1']:checked").length > 0 || $("input[name*='2']:checked").length > 0) {
      console.log('found checked');

        $('#segmentError').toggle();

        if($("#Error").is(':visible')) {
          $("html, body").animate({scrollTop: $("#scrollHere").offset().top});
        }
      }
      return true;
    });

Here's a JSFiddle: https://jsfiddle.net/msLrc2dm/1/

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337656

To solve this hook to the submit event of the form and check the length of the :checked radio buttons. You can then call preventDefault() on the event to stop the submission, if needed:

$("form").on('submit', function(e) {
    if (!$('input[name="name1"]:checked').length && !$('input[name="name2"]:checked').length) {
        e.preventDefault();
        $('#segmentError').toggle();
        $("html, body").animate({
            scrollTop: $("#scrollHere").offset().top
        });
    }
});

Upvotes: 3

Related Questions