What is the best way to retrieve the value of a chosen option utilizing Javascript or Jquery?

I have been working on a custom select box and I am trying to retrieve the value of the selected label. When I click the "check" button, an alert pops up showing the code inside the div, which makes sense. However, I am wondering how I can extract the value or text of the selected option.

.selectbox_newpost {
  padding:0;
  margin:0;
  height:100vh;
  width:100vw;
  font-family: sans-serif;
  color:#FFF;
}

.selectbox_newpost {
  display:flex;
  flex-direction: column;
  position:relative;
  width:250px;
  height:40px;
}

.option_newpost {
  padding:0 30px 0 10px;
  min-height:40px;
  display:flex;
  align-items:center;
  background:#333;
  border-top:#222 solid 1px;
  position:absolute;
  top:0;
  width: 100%;
  pointer-events:none;
  order:2;
  z-index:1;
  transition:background .4s ease-in-out;
  box-sizing:border-box;
  overflow:hidden;
  white-space:nowrap;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link rel="stylesheet" href="stylesss.css">
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

    <meta charset="utf-8">
    <title>test</title>
  </head>
  <body>

 <script type="text/javascript">
  function getValue(){
  var option = document.getElementById("selectedOptionNewpost");
  alert(option.innerHTML);
}
</script>

  <div class="selectbox_container_newpost">
    <div id="selectedOptionNewpost" class="selectbox_newpost" tabindex="1">
    <input class="selectopt" name="test" type="radio" id="opt1" checked>
    <label for="opt1" class="option_newpost">Objects</label>
    <input class="selectopt" name="test" type="radio" id="opt2">
    <label for="opt2" class="option_newpost">Vehicles</label>
    <input class="selectopt" name="test" type="radio" id="opt3">
    <label for="opt3" class="option_newpost">Technology</label>
    <input class="selectopt" name="test" type="radio" id="opt4">
    <label for="opt4" class="option_newpost">Books</label>
    <input class="selectopt" name="test" type="radio" id="opt5">
    <label for="opt5" class="option_newpost">Furniture</label>
    <input class="selectopt" name="test" type="radio" id="opt6">
    <label for="opt6" class="option_newpost">Others...</label>
  </div>
</div>
<button onclick="getValue()">Check</button>

  </body>
</html>

Answer №1

To retrieve the textContent of the selected radio button along with its associated label, follow these steps.

Refer to the code snippet below for implementation:

If this meets your requirements, kindly confirm.

.selectbox_newpost {
  padding:0;
  margin:0;
  height:100vh;
  width:100vw;
  font-family: sans-serif;
  color:#FFF;
}

.selectbox_newpost {
  display:flex;
  flex-direction: column;
  position:relative;
  width:250px;
  height:40px;
}

.option_newpost {
  padding:0 30px 0 10px;
  min-height:40px;
  display:flex;
  align-items:center;
  background:#333;
  border-top:#222 solid 1px;
  position:absolute;
  top:0;
  width: 100%;
  pointer-events:none;
  order:2;
  z-index:1;
  transition:background .4s ease-in-out;
  box-sizing:border-box;
  overflow:hidden;
  white-space:nowrap;
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <link rel="stylesheet" href="stylesss.css">
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>

    <meta charset="utf-8">
    <title>test</title>
  </head>
  <body>

 <script type="text/javascript">
  function clicked(){
  var option = document.getElementById("selectedOptionNewpost");
  const radioSelected = option.querySelector("input[type='radio']:checked")

  const labelForSelectedRadio = option.querySelector(`label[for=${radioSelected.getAttribute('id')}]`)
  console.log(labelForSelectedRadio.textContent)
}
</script>

  <div class="selectbox_container_newpost">
    <div id="selectedOptionNewpost" class="selectbox_newpost" tabindex="1">
    <input class="selectopt" name="test" type="radio" id="opt1" checked>
    <label for="opt1" class="option_newpost">Objects</label>
    <input class="selectopt" name="test" type="radio" id="opt2">
    <label for="opt2" class="option_newpost">Vehicules</label>
    <input class="selectopt" name="test" type="radio" id="opt3">
    <label for="opt3" class="option_newpost">Technology</label>
    <input class="selectopt" name="test" type="radio" id="opt4">
    <label for="opt4" class="option_newpost">Books</label>
    <input class="selectopt" name="test" type="radio" id="opt5">
    <label for="opt5" class="option_newpost">Furniture</label>
    <input class="selectopt" name="test" type="radio" id="opt6">
    <label for="opt6" class="option_newpost">Others...</label>
  </div>
</div>
<button onclick="clicked()">Check</button>

  </body>
</html>

Answer №2

If you prefer using jQuery:

function radioClick(){
    alert($("input[type=radio][name=option]:checked").attr('id'));
    alert($("input[type=radio][name=option]:checked").attr('value'));
}

Remember to include a value attribute in the radio button:

<input class="select-option" name="option" type="radio" id="choice3" value="3">

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

How can I prevent receiving redundant data and effectively manage my data?

I am currently working on adding offline support to my app. The logic I am following is to first check if there is cached feed data available. If the data is present, it will set the feeds to that cached data and display it from the cache. However, it will ...

What is the correct way to implement Axios interceptor in TypeScript?

I have implemented an axios interceptor: instance.interceptors.response.use(async (response) => { return response.data; }, (err) => { return Promise.reject(err); }); This interceptor retrieves the data property from the response. The re ...

Connecting node.js to a MySQL database on a WAMP/XAMPP server: A step-by-step guide

As a PHP programmer, I am experienced with WP, CI, and OC. However, I am a complete beginner when it comes to node.js and how to connect MySql with WAMP/XAMPP in a step-by-step method. If I were to set up a live server for this project, what would be the ...

The oversized image is refusing to scale down to fit within the confines of the CSS grid container

I am currently facing a challenge with creating a responsive image within a grid layout using CSS. The image is not resizing properly when the browser window changes size and is extending beyond its container borders. I have experimented with various techn ...

Retrieve file using Ajax (kind of)

I have implemented an AJAX call in my GSP: $.ajax({ url: '${request.contextPath + '/Ticket/passAll'}', type: 'POST', data: data, success: function() { alert("Success"); } }); Below is a code snipp ...

Struggling with integrating PHP within a JavaScript AJAX function

Here's a button I have: <button id= $id onClick="popup($id)">button</button> I am attempting to use it with an ajax function <script> function popup(id){ alert(" "); document.write(" "); } </script> My goal is to execute P ...

Using JavaScript to Detect Asynchronous Postbacks in ASP.NET AJAX

Seeking advice on the JavaScript code required to determine if an asynchronous postback is in progress. Can anyone help with this? Appreciate any assistance. ...

The functionality of using variables in conjunction with the .insertAfter method appears to be

As a novice coder with limited English skills, I apologize in advance. Here is the CSS code snippet I am working with: #wrapper{ width: 200px; height: 300px; border: solid 1px #000; overflow: visible; white-space: nowrap; } .page{ ...

Strategies for Sorting Nested Arrays in JavaScript

Here is the JSON data I have: { "list": [ { "deviceId": "2a-d539-4031-9bfc-4a42f2f765cf", "versions": [ { "id": "764c20-a213-9235f4b553b3", "createdTime": 1590361208034, "files": [ { ...

Transferring information and storing it in a textbox

I have a homepage that features a popup window. <textarea class="form-control item"></textarea> <button type="button" class="btn btn-primary" name="name">Send</button> Additionally, there is a secondary page at (/conclusion/main) ...

Unraveling and interpreting all incoming requests to my Node.js application

Looking for a simple method to identify and decipher all encoded characters in every URL received by my Node.js application? Is it possible to achieve this using a middleware that can retrieve and decode symbols such as & ? ...

What methods can I use to compare a React Component across multiple pages with Cypress?

One task I am trying to tackle is comparing a component on one page with the same component on another page using Cypress. For example, let's say I have a Pricing Component on the Home page, and I want to verify if the values on the Pricing Page are i ...

What could be causing my ajax file uploader to malfunction?

I am currently working on building an AJAX file upload module. Below is a snippet of the code I have been using: //creating a form for uploading files via AJAX FileUploader.prototype.createForm = function() { // creating a new form var form = docu ...

How can I ensure that my style.scss file effectively interacts with my stylesheet by including imports for "variables", "globals", and "header"?

Currently, I am in the process of learning how to utilize Sass and JavaScript through VS Code. Within my project structure, I have an "app" folder where my js folder resides containing script.js, as well as a scss folder holding _globals.scss, _header.scss ...

Looking for consistent vertical and horizontal scrolling behavior in a React project

I am in need of assistance as I lack the necessary expertise in ReactJs to transform this design. Currently, it is written in Jquery but I would like guidance on how to recreate it in ReactJs. Specifically, I want the left div with the topic for each row t ...

Is it necessary to use callbacks when using mongoose's findbyid with express to retrieve an object from the database? Are callbacks still important in modern JavaScript frameworks?

I'm currently exploring the express local library tutorial on MDN docs and wanted to try out returning an object without relying on a callback method. When I provide the request object parameter for the id to the findById mongoose method like this va ...

Is there a way in CSS to apply multiple colors to individual letters within a word?

Is it possible to add random colors to every pixel of a letter or multiple colors to a letter using CSS? Check out this example. ...

Combining arrays to append to an array already in place

I have implemented the rss2json service to fetch an rss feed without pagination support. Instead of a page parameter, I can utilize the count parameter in my request. With this setup, I am successfully able to retrieve and display the feed using a service ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

Create a submit button using Vue.js for text input

Can anyone help with a beginner question? I have a form that includes a text field. When I type something in and press enter, no result shows up. However, when I type something in and click the button, I get the desired result. Could someone guide me on ...