Adam Baser
Adam Baser

Reputation: 115

If radio is checked on submit jQuery

im trying to check if a radio button is checked on submit of a form. Ive researched but i didnt get it to work. It might be a silly mistake or type but ive been trying for hours now. The two different methods i tried are.

  $("#form").submit((e) => {
    e.preventDefault();
    if ($("#radio").attr("checked") == "checked") {
      alert("checked");
    }
    if ($("#radio").is("checked")) {
      alert("checked");
    }
  });

And the html is:

  <form action="" method="POST" id="form">
    {% csrf_token %}
    <label for="radio">
      <input type="radio" name="" id="radio" />
    </label>
    <button type="submit">Submit</button>
  </form>
</div>

Im doing this in django also. Thanks for any replies and sorry if im just making a silly mistake.

Upvotes: 1

Views: 169

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337637

In the first if condition you need to use prop() to check the checked property of the element object. Using attr() reads the checked attribute from the DOM, which is not changed as the user interacts with the radio button.

In the second if condition you need to use the :checked psuedo-selector with the is() method; note the leading : here.

$("#form").submit((e) => {
  e.preventDefault();

  if ($("#radio").prop("checked")) {
    console.log("checked");
  }

  if ($("#radio").is(":checked")) {
    console.log("checked");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" id="form">
  <label for="radio">
    <input type="radio" name="" id="radio" />
  </label>
  <button type="submit">Submit</button>
</form>

Upvotes: 1

Related Questions