Detecting Selected Radio Button Value Using Javascript

I am currently working on a project titled: Tennis Club Management utilizing javascript, HTML, CSS, and Bootstrap. In the project, one of the pages is managePlayers.html, which features two buttons - Add Players & Show Players. Clicking on the Add Players button reveals a table with input fields below it. The table includes fields for ID, DOB, Name, Gender, Contact, two radio buttons for gender selection, and a SAVE button.

Note: I am struggling with implementing functionality that checks if either of the radio buttons for gender (Male/Female) has been selected upon clicking the save button. Below are the relevant code files and screenshots for reference.

Jsfiddle link: https://jsfiddle.net/mohitsharma1991/40yz7tv6/1/

index.js


// Code snippet for displaying the table to add player information

function addplayers() {

    // playerIDvalue += 1;
    document.querySelector("#customerregistration").style.display = "block";
    if (istableCreated) {
        document.querySelector("#table-responsive").style.display = "none";
    }
    // document.querySelector(".playerID").value = playerIDvalue;
}

// Code snippet for saving player information on the Manage Players page

function savePlayer() {
    console.log("data saved successfully...");
    var playerBirthday = document.querySelector(".playerbirthday").value;
    var playerName = document.querySelector(".playername").value;
    var playerContact = document.querySelector(".playercontact").value;
    var playerAddress = document.querySelector(".playeraddress").value;
    var playerGender = document.querySelector('input[name="gender"]:checked').value;
    var playerID = document.querySelector(".playerID").value;


    var customerIDProof = document.querySelector(".customeridproof").value;
    var customerIDProofTextBox = document.querySelector(".customeridprooftextbox").value;
    var membershipFor = document.querySelector(".membershipfor").value;
    var membershipType = document.querySelector(".membershiptype").value;

    ...
}

managePlayers.html

<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Meta tags and title -->
    ...

</head>

<!-- Body content -->
<body class="managePlayers">

    <!-- Buttons to show and add players -->
   ...

    <!-- Registration form for adding player information -->
    ...

    <!-- Include Bootstrap JS scripts -->
    ...

    <!-- Additional JavaScript files included -->
    ...

</body>

</html>

Screenshots

https://i.sstatic.net/wAluO.png

https://i.sstatic.net/XGx67.png

https://i.sstatic.net/NZTQI.png

Any help would be appreciated!

Answer №1

To determine which gender was selected and save it for the player, you can simply utilize the checked property of your input. Push the selected gender value to your array.

The checked property will provide either true or false for each radio button, assigning the value to your variable playerGender. If no radio button has been selected, the playerGender variable will be undefined, triggering an error message.

A working demo has been included below. In case no gender is selected, an error message "*Cannot be blanked" will be displayed.

Working Demo:

// --------------TESTING CODE FOR LOGIN PAGE LOGIN BUTTON CLICK----------------
// Add more testing JavaScript code here
/* 
    Add CSS styling rules for different page elements here
*/
<!DOCTYPE html>
<html lang="en">

<head>
  <!-- Include necessary meta tags and external stylesheets -->
</head>

<body>
  <!-- HTML structure for managing players with buttons and form elements -->
  
  <table class="customerregistration" id="customerregistration">
    <!-- Registration form fields for adding player information -->
  </table>


  <!-- Include necessary scripts from Bootstrap and custom JS files -->

</body>

</html>

Answer №2

Here is a potential solution for you to consider:

const genderChecked = document.querySelector('input[name="gender"]').checked;
if(genderChecked){
  return true;
} else {
  return false;
}

Answer №3

Check if a radio button is selected using JavaScript.

    // Get the value of the selected radio button
    let radioInput = $('input[name=gender]:checked').val();

    // Check if a radio button is selected or not
    if(radioInput){
       // Do something with the selected value
    }else{
      alert('No option selected');
    }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The execution time for React is much longer than anticipated

I have tried to integrate the drench game into my project. Below is the code snippet I have used. The logic seems correct and given that it's a 14x14 board, the execution time shouldn't be too long. However, after a few clicks when the state.cove ...

Ways to acquire the reference of the parent component

Within my code, there is a parent component represented as: <Parent> <Child (click)=doSomething()></Child> </Parent> I am looking to establish a reference to the Parent component in order to pass it within a method that will trigg ...

Storing div content in database directly

I have a straightforward div that allows users to edit content on the page. I need to save this content in a database, but without including any HTML tags while still preserving line breaks. Currently, I am using the innerText property for this purpose. N ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

Tips for building a responsive website with JavaScript and media queries:

Looking to ensure my website is responsive, but with specific requirements: Need the navigation bar to transition into a vertical hamburger drop-down menu when screen size is reduced, and it must be coded in JavaScript Planning to implement a mobile-firs ...

Tips for aligning a text box in the center using Bootstrap

Is it possible to easily center the input text box of bootstrap? <form action="#" method="post" class="akame-contact-form border-0 p-0"> <div class="row justify-content-center"> <div class= ...

Tips for invoking a reduce mechanism within a separate function

I need assistance with implementing a reduce function: users.reduce(function (acc, obj) { return acc + obj.age/3; }, 0); within the following function structure: function calculateUserAverageAge(users) {}; To analyze this array of objects and calculate ...

Correcting Typing Errors in TypeScript

My current challenge involves a method that is consuming data from an external API: public async getStatus(id: string): Promise<APIRes | undefined> { try { const result = await getRequest(`${this.URL}/endpoint/${id}`) const respo ...

Unexpected behavior observed in the Python minifier Slimit

Attempting to decrease the size of some JavaScript code using the 'slimit' package in Python. import slimit slimit.minify('[1,2,3,4,5,6,7,8]') The above snippet executes without issue and outputs '[1,2,3,4,5,6,7,8]' import ...

The link in the HTML code has been prevented from opening in a new

echo "<tr><th align='left'><a href=\"$email\">$name</a></th> I recently transformed a PHP Email App into a saving app. However, I am encountering an issue with opening links within the application. You ca ...

Tips on modifying anchor tag attributes in cross-domain iframe source URLs to open in a new tab

Is there a way to change the target attribute of an iframe child anchor tag from "_blank" to "_parent" or completely remove it? I'm looking for a script that can help me achieve this. How can I modify or delete properties of an anchor tag within an i ...

Ways to stop flask from automatically opening links in a new tab

I created a header that contains different links to various sections of my web application: <div class="collapse navbar-collapse" id="navbarSupportedContent"> <!-- Left --> <ul class="navbar-nav mr-auto"> <li ...

Switch out the view div element with ui-router

Currently, I am utilizing Angular ui-router to manage various views in the following manner: <div ui-view="header"></div> <div ui-view="nav"></div> <div ui-view></div> Upon Angular loading, the divs are automatically p ...

Vue.js numerical input module

My approach involves utilizing Numeral.js: Vue.filter('formatNumber', function (value) { return numeral(value).format('0,0.[000]') }) Vue.component('input-number', { templa ...

Transform a string into an array using JavaScript

Currently, I am dealing with an array: itemSku = ["MY_SERVICE","SKU_A","SKU_B"]; When passing this value to a component in Angular, the type of itemSku is being identified as a string. This prevents me from performing array operations on it. console.log ...

When square brackets are utilized in a JSON AJAX request, it may result in the

I'm encountering issues with an AJAX request that involves JSON data enclosed in square brackets, resulting in a return value of undefined. A different JSON file without square brackets is working fine, indicating that the problem lies specifically w ...

Converting a buffer to a string in Python 3, similar to Node.js 6.0.0

I am currently in the process of translating an old node.js library into Python and I am facing difficulties trying to replicate the behavior of Buffer.toString() in Python. The library is used in a node 6.0.0 environment. While researching, I came acros ...

What is the best way to prevent a page from refreshing every second when the Bootstrap modal is being displayed or active?

I am working on a project that involves two PHP pages. In the first page, I have set up a system to display data from a MySQL database using Ajax, with the content refreshing every second. The second page contains the PHP code responsible for fetching the ...

"Error: Unable to calculate the sum because s.sum is not recognized as a valid function. This occurred while trying to sum the property values of

I have a JavaScript object with JSON data var info = [ { "MONTH":" 2018-01", "DEPARTMENT":"Legals", "EMPLOYEE":"Smith A.", "AMOUNT":"14289.66" }, { "MONTH":" 2018-01", "DEPARTMENT":"Legals", "EMPL ...

An issue with the animation script in Ionic

I'm having trouble converting this to an Ionic application. Here's my code sample. Can anyone help me with putting this code correctly in Ionic? I'm trying to achieve something like this example <script src="https://cdnjs.cloudflare.com ...