开发者

Would like not selected radio buttons should return empty string

开发者 https://www.devze.com 2023-03-02 03:44 出处:网络
I have the following HTML <form id=\"create_form\" name=\"create_form\" action=\"\" method=\"post\">

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 radio buttons, when none have been selected, my JQuery/Ajax script returns the first radio button.

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

I would like that the users is forced to consider which to select, and not just the default.

How is that done?

Update:

I would think that

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

means to only get the values of the radio buttons in the form with id="create_form".

But because I had forms below (with <form id="something_else") and radio buttons in those forms also with name="type" it extracted that value.

Changing name=type to name=cname in both html and JQuery solved the problem.

Sounds like a bug in JQuery, doesn't it?


Try defining the variable like this (to get an empty string):

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

Hmmm, ok to answer the question about making a user choose... try this instead:

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


if

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

Doesn't work?

You might also try like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消