JavaScript function having an undefined value caused by a radio button

I am having trouble passing the value of a radio button to a JavaScript function. I have been testing my code but keep running into an issue where the returned value is always undefined. Here is the snippet of my code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Untitled 1</title>
<SCRIPT TYPE="text/javascript">
 <!--
 function jobWindow(){
  var target;
  for( i = 0; i < document.jobView.sales.length; i++ ){
   if(document.jobView.sales[i].checked == true) {
    target = document.jobView.sales[i].value;
    break;
   }
  }
  alert("val = " + target);
  //var load = window.open('target','','scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,location=no,status=no');  
 }
 // -->
</script>

</head>

<body>

<form name="jobView">
<input name ="sales" value="all" type="radio" />All&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="darell"  type="radio" />Darell&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="kevin" type="radio" />Kevin&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="brad" type="radio" />Brad&nbsp;&nbsp;&nbsp;&nbsp;
<input name="sales" value="chongo" type="radio" />Chongo&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="View Records" onclick="jobWindow()"/>&nbsp;&nbsp;&nbsp;&nbsp;
<input type="button" value="View Calendar" />
</form>

</body>

</html>

Answer №1

The correct way to access the desired path is as follows:

let element = document.forms["jobView"].elements["sales"];

Using the dot chaining method (document.jobView.sales) implicitly calls the "all" collection, which is only functional in IE. Although Firefox may display a similar string in its error console, it cannot be used in your code. Using methods like getElementsByTagName() and getElementsByName() will work properly, but you must verify that the elements retrieved are the ones you intend to use. It's important to anticipate scenarios where multiple forms exist on a page with overlapping field names. While this may not currently be an issue, failing to consider this possibility initially could lead to another developer adding a second form and causing conflicts later on.

Answer №2

Give this code snippet a try using document.getElementsByTagName:

 function getRadioInputValue(){
  var value;
  var elements = document.getElementsByTagName('input');

  for( let i = 0; i < elements.length; i++ ){
   if (document.forms['jobView'].elements[i].type === 'radio' && document.forms['jobView'].elements[i].name === 'sales')
   {
     if(document.forms['jobView'].elements[i].checked == true )
     {
       value = document.forms['jobView'].elements[i].value;
       break;
     }
   }
  }
  alert( "Value = " + value );
 }

Also, please note that the break line in your code was never executed due to missing curly brackets:

if( document.jobView.sales[i].checked == true )
{
   target = document.jobView.sales[i].value;
   break;
}

Answer №3

Replace document.jobView.sales with

document.getElementsByName('sales')

Answer №4

Introduce some debugging into the code. For instance, insert an alert() within the for() loop to confirm that document.jobView.sales.length is being defined.

If the alert does not display, it is likely that document.jobView.sales.length is undefined.

You can then use

try { var length = document.jobView.sales.length; } catch(e) { alert(e); }
to double-check this.

If you determine that document.jobView.sales.length is not defined, you may need to utilize document.getElementsByTagName and iterate through them instead of using document.jobView

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

Object contents shift upon my first gaze

While working on my JavaScript/ReactJS code, I encountered an issue where the Object (Obj) I was printing in the console contained keys as ids and values as true/false statuses, but when I opened the object, the values would automatically change. For exam ...

I am having trouble updating a record in my database table

I am encountering an issue while trying to update a row in a table using a form. The add button works fine, but I am unable to update it using the update (a tag). Just a reminder: the edit button is located in the last column of each row along with the de ...

Embedding JSON data in a GSP page

My goal is to transfer JSON data to a GSP page and present it in a table format. The expected JSON structure: { "data": [ [ "Tiger Nixon", "System Architect", "Edinburgh" ] ]} I attempted to achieve this with the following co ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

Ensuring the corner link remains at the top when expanding or in mobile mode with mdBootstrap's navbar

I have implemented Material Design Bootstrap on my responsive website. When viewing the website on a large screen, the navbar at the top displays: A link to my brand aligned to the left Two page links A profile dropdown aligned to the right Large scree ...

What is the best method for submitting an array of objects using Axios, Formik, and React.js?

Hello, I am facing an issue with posting an array of objects using axios and Formik while also utilizing npm react-select. Here is my initial data: const [initialValues, setInitialValues] = useState( { nom: "",drugs: [{}] ...

Ways to add stylistic elements to variables using JavaScript

I'm currently working on an API and I've managed to get it up and running, but now I'd like to add some style to it. I've been attempting to change the style for variables such as title, country, status, and summary but haven't ha ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

What discrepancies exist between running npm install on Windows versus Linux operating systems?

Just have a quick question to ask. I've been searching online with no luck. If I were to run npm install on a Windows machine to set up my dependencies, would it be viable to transfer the node_modules directory to a Linux machine and execute my nodej ...

Isolating objects within a JSON array based on a single key

I am developing a system using Angular 6, and I need to create over 100 input fields. Since these inputs are used in multiple forms, I want to create a dynamic form. However, I'm trying to figure out the best way to connect the input configurations to ...

Choosing the entire contents of a webpage using jQuery

Is there a way to use jQuery to select all the content on a webpage and copy it to the clipboard for use in another WYSIWYG editor? Here's the scenario: $("#SelectAll").click(function(){ //CODE TO SELECT ALL THE CONTENTS OF THE CURRENT PAGE /* PS: $ ...

Exploring the capabilities of the Contentful JavaScript SDK in conjunction with Native

I'm having some trouble getting the JavaScript Contentful SDK to work in my Nativescript app. As a newcomer to NativeScript, I might be missing something crucial. Hopefully, someone can lend a hand :) The module has been installed in my NativeScript ...

Formulate a Generic Type using an Enum

I'm currently working on a project that involves creating a generic Type using enums. Enum export enum OverviewSections { ALL = 'all', SCORE = 'score_breakdown', PERFORMANCE = 'performance_over_time', ENGAGEMENT ...

HTML content that is produced through JSONP retrieval

Recently, I've been experimenting with the jQuery library and have found it to be quite useful. Lately, I've been delving into AJAX requests to fetch various information like weather updates, current downloads, and more, which has been going smoo ...

Receiving a reply but failing to give a response

My code is causing an ERR_HTTP_HEADERS_SENT error. Can you help me identify what's wrong with it? .then((userDetails: any) => { userDetails.role.forEach((singleRole) => { if (singleRole.name === 'admin&apos ...

Product sketching libraries in JavaScript

Can somebody assist me in locating a suitable JS library that is capable of generating a product sketch similar to this one: Partition sketch? I am currently using Next.js, and I am encountering difficulties with most libraries due to Next.js utilizing SSR ...

Using JavaScript to implement responsive design through media queries

The code seems to be having some issues as it only works when I reload the page. I am looking to display certain code if "size < 700" and other code if "size > 699". I also tried this code from here: <script> function myFunction(x) { if ( ...

Is it possible to test an Angular application using Protractor within an iframe that is hosted by a non-Angular

While trying to migrate a legacy app to Angular, we encountered an issue where the legacy app loads the new app in an iframe. Testing this integration with Protractor has proven challenging due to the fact that the legacy app is not built on Angular. If t ...

Discovering information from a URL through JSON

Can someone help me with loading and displaying this JSON data? I attempted the following code, but unfortunately, it did not work as expected. <script> $(document).ready(function(){ $.getJSON("http://eolis-sante.com/eolis/connexion.php? ...

Tips for displaying specific HTML elements in AngularJS using ng-repeat and ng-if

I am working with some bootstrap HTML code that includes an ng-repeat function. <div class="row"> <div class="col-lg-4" ng-repeat="p in persons"> <img class="img-circle" src="images/{{ p.image }}" width="140" height="140"> < ...