jQuery get value of selected radio button

前端 未结 27 1875
耶瑟儿~
耶瑟儿~ 2020-11-22 13:55

The problem statement is simple. I need to see if user has selected a radio button from a radio group. Every radio button in the group share same id.

The problem is

27条回答
  •  萌比男神i
    2020-11-22 14:19

    See below for working example with a collection of radio groups each associated with different sections. Your naming scheme is important, but ideally you should try and use a consistent naming scheme for inputs anyway (especially when they're in sections like here).

    $('#submit').click(function(){
      var section = $('input:radio[name="sec_num"]:checked').val();
      var question = $('input:radio[name="qst_num"]:checked').val();
      
      var selectedVal = checkVal(section, question);
      $('#show_val_div').text(selectedVal);
      $('#show_val_div').show();
    });
    
    function checkVal(section, question) {
      var value = $('input:radio[name="sec'+section+'_r'+question+'"]:checked').val() || "Selection Not Made";
      return value;
    }
    * { margin: 0; }
    div { margin-bottom: 20px; padding: 10px; }
    h5, label { display: inline-block; }
    .small { font-size: 12px; }
    .hide { display: none; }
    #formDiv { padding: 10px; border: 1px solid black; }
    .center { display:block; margin: 0 auto; text-align:center; }
    
    
    

    Section 1

    First question text

    Second question text

    Third Question

    Section 2

    First question text

    Second question text

    Third Question

    Section 3

    First question text

    Second question text

    Third Question

    Choose Section Number



    Choose Question Number







提交回复
热议问题