4

In bootstrap, active class is used to get selected radio button value. When a radio button is clicked, active class is added to label of that button. After submitting the form value of radio button with active label is sent for further processing.

However when the active class is added from jquery and form is submitted, it doesn't post/get value of that button. To make this work I have to simulate the click on radio button with active class.

  • Am I doing something wrong ?
  • Is there any other way to achieve this ?

    <?php
        $value = 1;
        ?>
        <html>
        <head lang="en">
      <meta charset="UTF-8">
    <title></title>
    <script src="js/jquery-2.1.4.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/bootstrap-theme.min.css">
    <script>
    
     function showOption() {
        $(document).ready(function () {
    
       $('#option_grp input[value=<?php echo "$value"?>]').parent('label').addClass('active').click();
    
            });
        }
    </script>
    </head>
     <body onload="showOption()">
     <div class="container">
    
    <form method="post" action="getValue.php">
    
    
            <div id="option_grp" class="btn-group" data-toggle="buttons">
                <label class="btn btn-primary">
                <input type="radio" name="pr_type" value="1">Option 1
                </label>
                <label class="btn btn-primary">
                <input type="radio" name="pr_type" value="2">Option 2
                </label>
    
              </div>
    
            <input type="submit" name="submit" value="Submit">
    
     </form>
    </div>
    </body>
    </html>
    

getValue.php

    $pr_type=$_POST['pr_type'];
    echo "pr_type : ".$pr_type;
Pradip Shenolkar
  • 818
  • 1
  • 14
  • 34

1 Answers1

1

In order for a radio button value to be sent to the server during a POST request, it must be marked as "checked". You can do this more than one way.

For example:

  1. You can simulate a user clicking on the radio button which will cause the radio button to be selected.
  2. You can mark the radio button checked by setting the "checked" attribute to "checked". See this answer for reference.

Either way should work, but the second method would be preferable. Once the radio button is checked, it can be styled however you like. Use can use the Bootstrap class 'active' or any other that you like, but the styling will have no bearing on what is sent back to the server.

Community
  • 1
  • 1
Kent Anderson
  • 486
  • 2
  • 16