"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. Any assistance would be greatly appreciated!

Commenting out the code allows the prompt to work fine, but as soon as I add any additional code to my hw4.js file, the prompt stops working. The project also involves AJAX and Cookies, although I've decided to tackle those complexities only after resolving this issue. I have even tried downloading JQuery and referencing it through different online links to no avail.

In HTML:

<head>
    <title>Greeting Page </title>
    <link href="style.css" rel="stylesheet" type="text/css">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script>
    <script src="hw4.js" defer></script>
    <meta charset="UTF-8">

</head> 
<body> 
    <h1>A Greeting Page for Important People</h1>

    <section id= forms>
        <form id = "speedForm" class="forms">
            <p id = "speeds">
                Speed 0 <input type="radio" name=choice value="0" id= "speed0" checked> Speed 1 <input type="radio" name=choice value="1" id= "1" > Speed 2 <input type="radio" name=choice value="2" id= "2" > Speed 3 <input type="radio" name=choice value="3" id= "3" > Speed 4 <input type="radio" name=choice value="4" id= "4" > Speed 5 <input type="radio" name=choice value="5" id= "5" > Speed 6 <input type="radio" name=choice value="6" id= "6" > Speed 7 <input type="radio" name=choice value="7" id= "7" > Speed 8 <input type="radio" name=choice value="8" id= "8" > Speed 9 <input type="radio" name=choice value="9" id= "9" > Speed 10 <input type="radio" name=choice value="10" id= "10" > <br>
                Speed 11 <input type="radio" name=choice value="11" id= "11" > Speed 12 <input type="radio" name=choice value="12" id= "12" > Speed 13 <input type="radio" name=choice value="13" id= "13" > Speed 14 <input type="radio" name=choice value="14" id= "14" > Speed 15 <input type="radio" name=choice value="15" id= "15" > Speed 16 <input type="radio" name=choice value="16" id= "16" > Speed 17 <input type="radio" name=choice value="17" id= "17" > Speed 18 <input type="radio" name=choice value="18" id= "18" > Speed 19 <input type="radio" name=choice value="19" id= "19" > Speed 20 <input type="radio" name=choice value="20" id= "20" > <br>
            </p>
        </form>

        <form id= "colorForm" class= "forms">
            <p>
                red <input type="radio" name= "option" value="red" id= "red" checked> yellow <input type="radio" name=option value="yellow" id= "yellow" > blue <input type="radio" name=option value="blue" id= "blue" > 
            </p>

        </form>
    </section>

    <section>
        <div class= "box">
            Welcome
        </div>
    </section>

</body>

IN JS:

var userName = prompt("What's your name?", " ");

$(document).ready(function() {      


$radios.change(function() {
  let $checked = $radios.filter(function() {.   // when radio buttons are changed for speed, check which was pressed 
    return $(this).prop('checked');
    });

    let speed = $checked.val()* 100;            // set value of checked button (0-50) * 100 to the speed
    $( ".boxes" ).effect( "shake", {times: 100}, speed);    //creat a shake effect on the box div at the corresponding speed
});


});

//event listener for color 

$(document).ready(function() {      


$radios.change(function() {
  let $checked = $radios.filter(function() {.   // when radio buttons are changed for speed, check which was pressed and return that object as $checked var
    return $(this).prop('checked');
    });

    let color = $checked.val();             // set value of checked button (0-50) * 100 to the speed
    $( ".boxes" ).css("backgroundColor", color); //change color of box to corresponding radio button value (red, yellow, blue)


});

});

Answer №1

Upon reviewing the code, I have identified a few errors: 1) There are excessive '.' after { in the code. 2) The variables $radios are not loaded or defined, which may not be visible to the console due to the lack of "use strict". 3) Incomplete id name handling for .

To simplify and make it work, here is a sample solution for radios using event delegation. Rather than selecting all radios individually, you can attach a listener to a parent element and check if the target is an input type and get its value.

If you need further assistance, consider sharing your code on platforms like GitHub for easy collaboration and feedback. Meanwhile, give the following solution a try:

"use strcit";

function addRadios(amount){
   
    radios =  document.body.querySelector('.forms');

    for(var i=0; i < amount; i++){
        var label = document.createElement("label");
        var radio = document.createElement('input');
        radio.type = 'radio';
        radio.classList.add('choice');
        radio.setAttribute('name','choice');
        radio.setAttribute('value',i);
        radio.setAttribute('id',i);
        radios.appendChild(document.createTextNode('Speed '+i));
        radios.appendChild(radio);
    }
    radios.children[0].id = 'speed0';
    radios.children[0].checked = true;
};

$("#speedForm").click( function(e){
    
    if($(e.target).prev().is("input")){
        let speed = $(e.target).val() * 100;  
        alert(speed);
    }
});

addRadios(10);
<head>
  <title>Greeting Page </title>
  <meta charset="UTF-8">
</head> 
<body> 
  <h1>A Greeting Page for Important People</h1>

  <section id= forms>
      <div id = "speedForm" class="forms">
      </div>
  </section>

  <section>
      <div class= "box">
          Welcome
      </div>
  </section>
  
  <script
  src="http://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
  <script src="scripts/index.js"></script>
</body>

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

Interacting with Selenium API using a jQuery event handler

I am working on a Java Selenium application that needs to respond to specific events occurring in an open browser window. One such event is when a user interacts with elements on the page, and I need my Java application to be aware of it so that it can tak ...

Disabling comments is creating problems with the appearance of Wordpress pages

Visit handheldtesting.com Whenever the option "disable comments" is selected in the backend, or if 'display:none:' is added <div id="respond" class="comment-respond" style="display:none;"> to the code, half of the content on the page dis ...

Are there any known browser compatibility issues with using "./" (dot slash) before HTML files?

Within the realm of shells, using ./ to indicate the current directory is quite common and generally not perceived as risky when specifying a path. On the other hand, in HTML coding, it's typical to omit ./ and instead directly specify the file name. ...

When hovering over the sidebar, it smoothly slides out. (ideally using only CSS)

I've been spending my free time working on a website, but I'm struggling to figure out how to create a navigation similar to the one featured on FontShop's site: . I want it so that when you hover over their logo (or in my case, a blank rect ...

Uploading Files within Angular FormArray

I am facing an issue with my formArray which contains file upload inputs in each element. Whenever I upload an image in one input, it changes the values of other file inputs in different rows. https://i.stack.imgur.com/3haZW.png Current Behavior: Uploadi ...

StyledTab element unable to receive To or component attributes

Is there a way to use tabs as links within a styled tab component? I've tried using the Tab component syntax with links, but it doesn't seem to work in this scenario: <Tab value="..." component={Link} to="/"> If I have ...

Showcasing form validation errors using django and ajax

I have set up a contact form using Django and AJAX for users to reach out to me. The current setup works smoothly if no errors occur, but I want to enhance it further by displaying any errors above the input fields along with the inputs themselves. While i ...

Supplying information to my ejs template while redirecting

I am currently working on a feature that involves sending data from the login page to the home page when the user is redirected. This data will then be used in the home EJS file. Below is the code snippet I have implemented: module.exports = functio ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

Creating a comparison display using ng-repeat

I have a JSON file that contains revision and history information about a modified entity, including its old and new values. The diff is generated using the jsondiffpatch library and I have parsed it further to create the final JSON format for rendering. ...

Dealing with Vue's performance problems when using input type color and v-model

I am encountering a problem with setting the v-model on an input of type color. Whenever I change the color, there is a noticeable drop in frame rate and the application's FPS spikes from 60 to 3. You can see it reflected in the Vue performance graph ...

Maintain the link's functionality even after it's been clicked by utilizing the same

I have a fixed navbar with same-page anchors and I want to keep the link active after it has been clicked and taken to that section of the page. While this is simple for links to another page, I'm struggling to figure out how to do it here. Here&apos ...

Is the default animation duration of Compass being ignored?

After recently updating to Compass version 1.0.16, I started setting up basic usage of the new animation features. However, I encountered an issue where setting default values for different animation settings did not take effect. This led me to hard-code t ...

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

Testing the NestJS service with a real database comparison

I'm looking to test my Nest service using a real database, rather than just a mock object. While I understand that most unit tests should use mocks, there are times when testing against the actual database is more appropriate. After scouring through ...

Jekyll is not beginning line numbers from the first line as they should be

My website was put together using Jekyll, specifically with the Beatiful-Jekyll theme. To make syntax highlighting possible, I utilized Rouge. The issue arises when displaying line numbers alongside the code - sometimes they don't align properly or ar ...

Input field that adjusts its width based on screen size, accompanied by two buttons displayed side

I need a solution to display a text input and two buttons side by side. The buttons should take up only the space they require, while the text input should expand to fill the remaining space. It's important to have small margins between these elements ...

Update the href attribute with values from the form fields

My current project involves creating a form with 5 input fields: Service type Number of days Number of children Number of adults I want to dynamically change the value of a button based on these variables using JavaScript. Here is my code so far: JS ...

Adjustable width columns in Flexbox design

I need assistance with creating a responsive three-column grid layout using Flex in CSS. I have achieved a fairly responsive design by following the CSS provided in the fiddle link below. However, I am facing an issue where the second column (the blue one) ...

Leveraging JSON data to dynamically create HTML elements with multiple class names and unique IDs, all achieved without relying on

Recently, I've been working on creating a virtual Rubik's cube using only JS and CSS on CodePen. Despite my limited experience of coding for less than 3 months, with just under a month focusing on JS, I have managed to develop two versions so far ...