JavaScript: Struggling to access radio button value within a variable

My goal is to perform arithmetic operations based on the selected radio button value.

<html>
  <body>
    <br>Please enter the first number:
    <input type="text" id="txt1" name="text1">Enter the second number:
    <input type="text" id="txt2" name="text2">
    
    <form>
      <input type="radio" name="oper" value="1" checked>Add
      <br>
      <input type="radio" name="oper" value="2">Multiply
      <br>
      <input type="radio" name="oper" value="3">Subtract
    </form> 

    <p id="demo"></p>
    <script>
      function myFunction() {
        var y = document.getElementById("txt1").value;
        var z = document.getElementById("txt2").value;
var o = getCheckedRadioValue("oper");
if(+o == 1)
        var x = +y + +z;

if(+o == 2)
var x = +y * +z;

if(+o == 3)
var x = +y - +z;

        document.getElementById("demo").innerHTML = x;
      
    </script>
    <button onclick="myFunction()">Calculate</button>
    <br/>
  </body>
</html>

Answer №1

It appears that there may be an issue with the getCheckedRadioValue function.

If you need to retrieve the values of checked radio buttons using jQuery, use the following code:

var o = $("input:radio[name='oper']:checked").val();

Here is a sample script to demonstrate how to handle this:

<script>
      function calculateResult() {
        var y = document.getElementById("txt1").value;
        var z = document.getElementById("txt2").value;
    var o = $("input:radio[name='oper']:checked").val();
    if(+o == 1)
            var x = +y + +z;

    if(+o == 2)
        var x = +y * +z;

    if(+o == 3)
        var x = +y - +z;

      //  alert(x);

        document.getElementById("demo").innerHTML = x;
      }
    </script>

    <br/>
  </body>
</html>

Thank you for your time and consideration.

Answer №2

Here is an example of how to do it:


Input the first number:
Input the second number:

<form>
    <input type="radio" name="oper" value= 1 checked />Add
<br>
    <input type="radio" name="oper" value=2 />Multiply
<br>
   <input type="radio" name="oper" value=3 />Subtract
</form> 
<p id="result"></p>
<button id="calculate">Calculate</button>

$( "#calculate" ).click(function() {
   var num1 = $("#num1").val();
   var num2 = $("#num2").val();
   var operation = $("input[type='radio']:checked").val();

   if(operation == 1)
      var result = +num1 + +num2;

   if(operation == 2)
      var result = +num1 * +num2;

   if(operation == 3)
      var result = +num1 - +num2;

   $("#result").html(result);
});

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

Moving Iframe Data to a div

Is there a way to easily copy content from a specific iframe on my index.aspx page, open a new window, and paste it into a div? I currently have this code (not mine) but I would like a cleaner solution: $('#ifContent').clone().appendTo(w.docume ...

css background is repeating after the height of the div is reset

I'm working on a project where I want to resize an image while maintaining its aspect ratio to fit the height/width of the browser window. However, every time the code for resizing is implemented, the div height continues to increase with each resize ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...

Image uploads are being interrupted by redirection

After submitting a form, I want the user to be redirected to another page. However, I am facing an issue with the redirection logic in my code. Although I am using window.location.href for redirection, it seems to interfere with the image uploading process ...

Repeatedly iterates through the JSON properties that have been grouped together

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF Upon examining a JSON object, the structure is as follows: var values = [ {"aname":"account1", "pname":"pname1", "vname":"vname1& ...

Ways to prevent a div from loading an HTML page

When an external button is clicked, the remove() function on id main is triggered. The issue arises when a user quickly clicks on btn1 and then presses the external button, causing the removal to occur before the event handler for btn1. This results in the ...

JavaScript failing to load following PHP header() redirect

I've set up a page that allows users to sign in by filling out a basic form, which then sends the data to a separate PHP script for validation. After the validation process is complete, the PHP script uses the header() function to redirect the user to ...

Comparing object variables within Javascript's HTMLCollection

let var1, var2; // Obtaining elements from the HTMLCollection var1 = document.forms[0]; var2 = document.forms.item(0); alert(var1 === var2); // Output: "true" var1 = document.forms["myForm"]; var2 = document.forms.namedItem("myForm"); alert(var1 === v ...

What is the reason for the JavaScript TypeError (undefined) being triggered when this object is used within a function?

I have defined a new object like this: function node(){ this.tag = null; this.Tdata = []; this.Tchilds = []; } Now, I am trying to use this object in a function: function Validate(root /*Ass ...

Troubleshooting issue: Incompatibility between NODE.JS Passport and mongoose

Currently, I am diving into the world of Node.js and exploring all its features with the help of Scotch's tutorial (https://scotch.io/tutorials/easy-node-authentication-setup-and-local). Following the tutorial, I implemented what was suggested, which ...

Exploring the Uses of SystemJS with TypeScript Loader

Can someone help clarify something about this TypeScript plugin for SystemJS? https://github.com/frankwallis/plugin-typescript/ Here is what the plugin does: This SystemJS plugin allows you to import TypeScript files directly and have them compiled in ...

What is the best method for transmitting server errors to the client?

When using passport.js, I have all the required code in place. However, I am facing an issue with displaying errors on the client-side. Despite having the successRedirect set up correctly, nothing happens when a wrong password is entered, and no error mess ...

The issue of Basic Bootstrap 5 Modal triggering twice is causing a frustrating experience

My modal is almost working perfectly - it changes content based on the clicked image, but it is triggering twice in the backend and I can't figure out why! I followed Bootstrap's documentation for this, so I'm unsure where the issue lies. Al ...

Having trouble establishing a connection between MongoDB and a Node.js Express server on my local machine

While attempting to establish a connection between mongoDB and nodejs express using the post method, I added a logger that should display a message confirming that the database is connected once nodejs listens to mongoDB. However, I encountered an issue wh ...

"Integrate envMap into the materials section of the model.json file

I successfully exported an object from Blender to .json format for use with three.js. I manually added all the maps to the exported file, which were not included by the exporter but could easily be manually added after mapping correctly in Blender. model. ...

How to connect an external module to NuxtJS using Vue.js

Attempting to incorporate a widget/plugin/extension system into my existing web UI built with NuxtJS. Within the pages/view.vue single-file component, I aim to establish the extension system by dynamically loading components indicated through query paramet ...

Exploring click event beyond React Component: Jest + Enzyme Testing

I am looking to create a Jest and Enzyme test for a component that includes an event listener. The purpose of the test is to ensure that when a mousedown event occurs outside of a specific HTML element, a change is triggered (for example, toggling a state ...

What is the process for converting a file to base64 encoding, and then uploading it as a multipart file to a backend API using JavaScript

I am working on a project to create a micro-service that can receive base64 encoded data. However, when attempting to send more than 6 MB of data, I encountered the following error message: The multi-part request contains parameterized data (excluding ...

What is the best way to extract the value from a resolved Promise?

Currently, I am attempting to read a file uploaded by the user and convert it into a String using two functions. The first function is handleFileInput: handleFileInput(event){ setTimeOut(async()=>{ let abcd= await this.convertFileToString(this.fi ...

NodeJS threw an error: The call stack size has exceeded the maximum limit

My tool of choice is socket.io Error Encountered: We are facing a RangeError while calling `socket.disconnect()`; Please help resolve this issue. Thank you! ...