开发者

Trying to find selected radio button. What's wrong?

开发者 https://www.devze.com 2023-03-01 21:28 出处:网络
I can read out text field values, but when I try to find the selected radio button, I get nothing. $(document).ready(function(){

I can read out text field values, but when I try to find the selected radio button, I get nothing.

$(document).ready(function(){
开发者_StackOverflow中文版
    $("form#create_form").submit(function() {

    var title      = $('#title').attr('value');
    var owner      = $('#owner').attr('value');
    var users      = $('#users').attr('value');
    var groups     = $('#groups').attr('value');
    var begin_date = $('#begin_date').attr('value');
    var end_date   = $('#end_date').attr('value');

    // get selected radio button 
    var type = '';
    for (i=0; i<document.forms[0].type.length; i++) {
        if (document.forms[0].type[i].checked) {
        type = document.forms[0].type[i].value;
        }
    }

HTML:

<div class="create-new">
  <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>

What am I doing wrong?


I would suggest an alternative method to getting the selected radio button (since you are already using jQuery):

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

This solution is an example on .val().

The above solution is much more succinct, and you avoid any conflicts in the future if other forms are added (i.e you can avoid the potentially hazardous document.forms[0]).

Update

I tested your original function with the following fiddle and it works:

http://jsfiddle.net/nujh2/

The only change I made was adding a var in front of the loop variable i.

0

精彩评论

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