Always get the wrong switch value. What's wrong?

Here is a living example of my problem

http://jsfiddle.net/littlesandra88/xksB9/

I would expect the Create button to return an empty string when its radio buttons are not selected. Instead, it reads the value from the switches from the form below.

The bottom "Save" button always returns the value from the form above. Very strange!

Here is the code

$(document).ready(function(){

   $('form').live('submit', function(){

      var title      = this.elements.title.value;
      var owner      = this.elements.owner.value;

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

      alert(type);

    });
});

The idea is that I will automatically generate forms of the type below, and therefore I don’t know the identifier before hand, so I just give them random numbers to make them unique.

How to solve this problem?

+3
source share
3 answers

You can simply change this line:

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

to

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

, jQuery , DOM.

, , , .

, , :

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

, HTML, , . , ( , ):

<form action="" method="post">
  <input name="anchor" value="54" type="hidden">
  <table class="alerts" cellspacing="0">
    <tbody>
      <tr>                                
        <td class="activity-data">54</td>
        <td class="activity-data"> <input name="title" id="54_title" value="" type="text" /> </td>
        <td class="activity-data"> <input name="owner" id="54_owner" value="" type="text" /> </td>          
        <td class="activity-data"> <input name="ctype" value="individuel" type="radio" checked/> Individuel <br> <input name="ctype" value="course" type="radio" /> Course </td>
        <td> <input value="Save" type="submit" /></td>
      </tr>
    </tbody>
  </table>
</form>

, , jQuery .

+4

, , , , . , foo:

<input name="foo" id="ctype" value="individuel" type="radio" /> Individuel <br/>
<input name="foo" id="ctypee" value="course"    type="radio" /> Course <br/>

, ( ). foo:

$(document).ready(function(){

   $('form').live('submit', function(){

      var title      = this.elements.title.value;
      var owner      = this.elements.owner.value;

      // looking for 'foo' radio button group selection
      var type = $('input:radio[name=foo]:checked').val() || '';

      alert(type); // alerts the correct selection from the top form
    });
});
+2

:

<input name="ctype" value="individuel" type="radio" checked/> 

, 'checked'. , , "", .

, ,

<input name="ctype" value="individuel" type="radio" checked="checked" /> 

: , .

+1

All Articles