We would like not selected radio buttons to return an empty string

I have the following HTML

<form id="create_form" name="create_form" action="" method="post">
<input name="type" id="type" value="individuel" type="radio" /> Individuel <br/>
<input name="type" id="type" value="course"     type="radio" /> Course <br/>

<button class="n" type="submit">Create</button>
</form>

and when I get the value of the switches, when none were selected, my jQuery / Ajax script returns the first switch.

$(document).ready(function(){
    $("form#create_form").submit(function() {
    var type = $('input:radio[name=type]:checked').val();
        ...

I would like users to be forced to consider which one to choose, and not just the default.

How it's done?

Update

I would have thought that

$(document).ready(function(){
    $("form#create_form").submit(function() {
    var type = $('input:radio[name=type]:checked').val();

it only means getting the values ​​of the switches in the form with id="create_form".

But since I had the forms below (c <form id="something_else") and the radio buttons in these forms, as well as with name="type", he extracted this value.

Changing name=typeup name=cnamein both html and jQuery solved the problem.

Sounds like a bug in jQuery, right?

+3
source share
2

​​ ( ):

var type = $('input:radio[name=type]:checked').val() || '';

, , , ... :

var type = $('input:radio[name=type]:checked').val();
if (typeof type === 'undefined') {
  alert('You must make a choice!'); 
  return false;
}
+3

( ! $("input:radio").is(':checked') )

?

:

var is_checked = true;
$('input:radio').each(function(){
   is_checked = is_checked && $(this).is(':checked');
});
if ( ! is_checked );
+2

All Articles