ArticleZip > Bootstrap Radio Button Get Selected Value On Submit Form

Bootstrap Radio Button Get Selected Value On Submit Form

Bootstrap Radio Button Get Selected Value On Submit Form

If you're looking to add radio buttons to your Bootstrap-powered form and need to get the selected value when the form is submitted, you're in the right place! Radio buttons are a great way to present users with multiple options, but retrieving the selected value can sometimes be a bit tricky. Don't worry, though – I've got you covered with a straightforward solution that will have you up and running in no time.

To get the selected value of a radio button in a Bootstrap form when the form is submitted, you'll need to leverage a bit of JavaScript. Here's a step-by-step guide on how to achieve this:

Step 1: HTML Markup
First, let's start by setting up our HTML form with Bootstrap radio buttons. Make sure to include the necessary Bootstrap CSS and JavaScript files in your project before proceeding. Here's an example of how your HTML markup might look:

Html

<div class="form-check">
    
    <label class="form-check-label" for="option1">Option 1</label>
  </div>
  <div class="form-check">
    
    <label class="form-check-label" for="option2">Option 2</label>
  </div>
  <button type="submit">Submit</button>

In this snippet, we have two radio buttons with the values "option1" and "option2" respectively. The `name` attribute helps group the radio buttons together so that only one can be selected at a time.

Step 2: JavaScript Function
Next, let's write a JavaScript function that retrieves the selected value of the radio button when the form is submitted. Add the following script to your HTML file:

Javascript

document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent the form from submitting
  let selectedValue = document.querySelector('input[name="radioOption"]:checked').value;
  console.log(selectedValue); // You can do whatever you want with the selected value here
});

This script listens for the form submission event and prevents the default submission behavior using `event.preventDefault()`. It then selects the checked radio button with the name "radioOption" and retrieves its value.

And that's it! You now have a functioning solution to get the selected value of a Bootstrap radio button when the form is submitted. Feel free to customize the code to suit your specific requirements and enhance the user experience of your forms. Happy coding!