1

I am using Jquery

This is my HTML Section

<input type="radio" id="admin" value="admin"/>Admin<br>
<input type="radio" id="superadmin" value="superadmin"/>Super Admin<br>


$(document).ready(function() {
    var selecctedtype = '';
    if (document.getElementById('admin').checked) {
        selecctedtype = 'admin';
    }
    if (document.getElementById('superadmin').checked) {
        selecctedtype = 'superadmin';
    }
    alert(selecctedtype);
});

But i am getting empty alert

This is my jsfiddle

http://jsfiddle.net/kua4tfhd/1/

Could anybody please let me know how to capture it ??

3 Answers3

2

Alert is empty because nothing is selected at the moment the script is executed.

1). If you want your radio buttons to act like radio buttons you must give them the same name:

<input type="radio" name="role" id="admin" value="admin" /> Admin
<input type="radio" name="role" id="superadmin" value="superadmin" /> Super Admin

2). Then you would bind onchange event to detect when user changes selection. To select radio buttons you can use for example specific name selector or/and :radio input selector:

$(':radio[name=role]').change(function() {
    alert(this.value);
});

3). Later when you want to get selected value you can do something like this using :checked selector:

var role = $(':radio[name=role]:checked').val();

Demo: http://jsfiddle.net/kua4tfhd/10/

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • Your solution is the only one where the radio button functionality actually works (if one is selected the other is deselected). +1 – Mark C. Oct 17 '14 at 12:46
1

you have to handle it in click event:

HTML:

<input type="radio" id="admin" class="role" value="admin" />Admin
<br>
<input type="radio" id="superadmin" class="role" value="superadmin" />Super Admin
<br>

JQUERY:

$(document).ready(function () {

    $(".role").click(function () {

        alert($(this).val())
    });
});
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
0

Try This....

$('input[name=radioName]:checked', '#myForm').val();

Reference..

Community
  • 1
  • 1
yogesh
  • 23
  • 1
  • 7