JMA
JMA

Reputation: 994

how to check if the radio button are required in jquery

I need to know how to check if the radio button is required. I am using jquery, i tried to use

console.log($("#radio").prop("required"));

But it is not working.

Upvotes: 1

Views: 760

Answers (3)

Manish Joy
Manish Joy

Reputation: 486

You should use attr() in place of prop as used here:

$(document).ready(function() {
  $("input[type='radio']").click(function(){
    if($(this).attr('required')){
      console.log('Required');
    }
    else{
      console.log('Not Required');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="radio" required /> test1
<input type="radio" /> test2

Upvotes: 0

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

$("#radio").attr("required");

Or:

$("#radio").is("[required]");

The first one uses the attribute property (makes a getAttribute call). The second uses a CSS selector. So if you want to select all the inputs that are required you'll need something like: $("input[required]").

Upvotes: 1

Adam Wolski
Adam Wolski

Reputation: 5676

You can use $('input').attr("required") or $('input').get(0).hasAttribute("required")

 

console.log($('input').attr("required"));
console.log($('input').get(0).hasAttribute("required"))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" required> test

Upvotes: 2

Related Questions