Is the radio functionality and dropdown menu experiencing technical difficulties?

I'm having issues with my code, specifically in the JS function when I try to retrieve values from radio buttons and dropdown menus.

Can someone help me figure out what's going wrong?

CSS:

#mytable {
    width:400px;
    border: 1pt solid black;
}
#mytable tr {
    height:50px;
}
#mytable td {
    width:20%;
    border: 1px solid black;
}

Javascript:

function colorit(){
    var letter;
    if(document.getElementsByName("plusSign").checked) letter = "+";
    else if(document.getElementsByName("letterX").checked) letter = "X";
    else if(document.getElementsByName("letterH").checked) letter = "H";

    var colorList = document.getElementsByName("color");

   var x = document.getElementById('mytable').getElementsByTagName('td');
   for(i=0;i<x.length;i++) {
     x[i].style.backgroundColor = colorList.options[colorList.selectedIndex].text;
     x[i].innerHTML = letter;
   }
}

function clearit(){
   var x = document.getElementById('mytable').getElementsByTagName('td');
   for(i=0;i<x.length;i++) {
     x[i].style.backgroundColor = "";
     x[i].innerHTML = "";
   }
}

HTML:

<form name="frm1">
    <table>
        <tr>
            <td>Pattern Choice:</td>
            <input type="radio" name="plusSign" value="PlusSign" />Plus Sign</td>
            <input type="radio" name="letterX" value="LetterX" />Letter X</td>
            <input type="radio" name="letterH" value="LetterH" />Letter H</td>
        </tr>
        <tr>
            <td>Color Choice:</td>
            <select name="color">
                <option>Red</option>
                <option>Blue</option>
                <option>Yellow</option>
                <option>Green</option>
                <option>Orange</option>
            </select>
        </tr>
        <table id="mytable">
            <TR>
                <TD></TD>
               ...
               // Truncated for brevity
               ...
                <TD></TD>
            </TR>
        </TABLE>
        <tr> 
            <input type="button" value="Color It" onclick="colorit()" />
            <input type="button" value="Clear"    onclick="clearit()" />        
        </tr>    
          </table>
</Form>

Answer №1

There are several issues that need to be addressed in your code:

  • getElementByName should actually be getElementsByName
  • All radio buttons must have the same name attribute for proper functionality
  • The method
    document.getElementsByName("letterX").checked
    will not work as expected because it returns multiple elements
  • Instead of using
    document.getElementsByName("color")
    , you should utilize document.getElementById("color"). Don't forget to update your <select> element with id="color"

I have made corrections to your code in this updated jsFiddle.

Changes made to your HTML:

1. <input type="radio" id="plus" name="radioButton" value="PlusSign" />
2. <input type="radio" id="letterx" name="radioButton" value="LetterX" />
3. <input type="radio" id="letterh" name="radioButton" value="LetterH" />
4. <select id="color">

JavaScript alterations:

function colorit(){
   var letter;
   if(document.getElementById("plus").checked) letter = "+";
   else if(document.getElementById("letterx").checked) letter = "X";
   else if(document.getElementById("letterh").checked) letter = "H";   
   var colorList = document.getElementById("color");
   var x = document.getElementById('mytable').getElementsByTagName('td');
   for(i=0;i<x.length;i++) {
     x[i].style.backgroundColor = colorList.options[colorList.selectedIndex].text;     
     x[i].innerHTML = letter;
   }
}

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

Listen for an event on a button to show a specific div

Looking to have a div appear when the user clicks on a button. //html-code <div class="col-md-4"> <h4 class="service-heading">Social Media</h4> <p class="text-muted">This is the first line of text.</p& ...

Tips and tricks for storing and retrieving form state using local storage with jQuery in JavaScript

I'm trying to save the form state in localstorage, I am able to save it successfully but I'm encountering an issue where I am unable to save the input typed data Desired outcome: If I type doggy inside the input box, I want that value to be ret ...

including a close button when in use and excluding it when not in use

Seeking assistance with removing the "close" icon if it is not active. Here is the code I currently have $("#mason2 li div").click(function() { $(this).parent().hide().appendTo("#mason2").fadeIn(200); $(this).append('<p class="close"& ...

The absence of CORS headers detected in XMLHttpRequest

I am currently trying to execute an ajax call to a remote server, only for developmental purposes. I have configured CORS on my server, which is why when I request the resource through the browser, it shows that the CORS headers are present. https://i.sta ...

What is the best way to adjust the height of a dropdown box in an angular application?

Is there a way to change the height of the scroll view? It seems too long for my liking, any advice? I attempted to adjust it using css but unfortunately, it didn't work out. The scroll view appears excessively lengthy as shown in the image below. h ...

Next.js version 13 is causing the page to refresh each time the router is pushed

I am currently developing a search application using NextJs 13, and I have encountered an issue where the page refreshes every time I click the search button. Strangely, this only happens when the application is deployed on Vercel. When running the app l ...

What is the best way to incorporate PHP code within a JavaScript function?

Is it possible to dynamically append the uploaded file name to the list displayed in ('.list')? The challenge lies in passing $_FILES["fileImage"]["name"] as an argument to a separate JavaScript function for appending, especially since the PHP sc ...

Adjust the dimensions of the Twitter Bootstrap Modal to match the maximum resolution of the user's screen

When the "Launch demo modal" button is clicked: I would like the modal to adjust its width and height based on the user's screen resolution, maximizing the available space. Additionally, I want the modal to appear in the top left corner of the docume ...

A versatile multi-select jQuery widget featuring the ability to choose options within a specific opt

I am on the hunt for a cool jQuery tool that has the following characteristics: It enables you to create multiple groups, such as: Group 1 - Sub 1 1 - Sub 1 2 - Sub 1 3 Group 2 - Sub 2 1 Group 3 - Sub 3 1 - Sub 3 2 By clicking on Group 1, for instance, ...

How to center an image within a div without it moving

I have set up a JSFiddle for reference: http://jsfiddle.net/AsHW6/ My task involves centering the down_arrow.png images within their respective div containers. I have successfully centered the up_arrow.png images using auto margins. These images are posit ...

Webpack 2.7.0 throws an error: "Unexpected parameter: theme"

At the moment, I am on webpack 1.16.0 and using --theme as an argument to set the output path and plugin paths. The command appears as: rimraf dist && webpack --bail --progress --profile --theme=<name of theme> However, as I try to upgrade ...

Encountering a 404 error while using THREE.ImageUtils.loadTexture in three.js

My first attempt at using three.js involves loading a 3D model, but I'm encountering an issue with texture loading. loader.load('models/asteroid_OBJ/asteroid OBJ.js', function (geometry, materials) { var material = new THREE.MeshLambertM ...

Show or hide the legend on a highchart dynamically

I am currently utilizing highchart in my application and I am interested in learning how to toggle the visibility of the legend within the highchart. Here is what I have attempted: var options = { chart: { type: 'column&a ...

Facebook is failing to detect any meta tags in the header of my React web application

After checking my code on https://validator.w3.org/, everything seems fine. However, I noticed that Facebook is not reading most of the content from the head section - not even a single meta tag. On the other hand, Google is able to read all the content fr ...

Maintaining scope integrity in an Angular application with components, including a dialog that utilizes a custom directive

I'm struggling with passing scope to a template rendered from a directive. It seems like it should be simple, but I can't seem to get it to work properly. Here is a simplified version of my HTML: <div ng-app="myApp"> <md-content> ...

Ways to ensure Vue retrieves data from the database whenever a specific event occurs

I have individual buttons next to each row, with unique data entries in the database. When clicking on a button, I want specific information to appear in a Bootstrap Modal. However, I am facing challenges ensuring that Vue updates correctly with each click ...

How to attach keypress event to an input with type 'number' using Jquery and attribute value

I'm trying to figure out how to validate an input field only when it is of type number and has the validate attribute set to checkit. I'm not sure what to use in place of the asterisks to bind this to the keypress event $('*** input[type=num ...

Unable to interpret encoded json information

I'm currently developing a basic chat system using PHP and jQuery with Ajax, but I've encountered an issue when trying to display a JSON encoded string through the ajax callback function. Below is the code for the ajax request: $.ajax({ url: ...

Preventing Javascript Pop Up from automatically jumping to the top of the page

Upon clicking a button (refer to image below and take note of the scroll bar position), a div pop up is triggered through Javascript. View image: https://docs.google.com/file/d/0B1O3Ee_1Z5cRTko0anExazBBQkU/preview However, when the button is clicked, the ...

Rendering content conditionally using react technology

There is a functional component that receives two items as props. The properties can have values like `undefined`, `""`, `null`, `"null"`, or a valid string (e.g. `"test"`). The goal is to conditionally render these props based on their values. If both ` ...