"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

Mastering universal code creation with the composition API in Quasar

The Quasar website explains that for writing universal code, the created and beforeCreate lifecycle hooks in Vue components are executed in Server Side Rendering (SSR). This raises a question: What about setup? How can I achieve SSR functionality with th ...

The use of Ajax in jQuery can sometimes result in the PHP isset function being unable to detect

I'm seeking assistance with my code. I am attempting to retrieve values and then send them to a PHP script via AJAX using jQuery. While I can extract the values, there appears to be an issue that I can't identify. Any help you can offer would be ...

Is it possible to receive a unique value error even when providing the correct key value in a map?

I encountered an issue while using a map function with an array in my application. Even though I have provided a unique key, Google Chrome console is still showing an error related to the unique key. Error Each child in a list should have a unique "ke ...

Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between var maxResult = window.max(maxValInt1, maxValInt2); which functions properly, and var maxResult = max(maxValInt1, maxValInt2); which gives an error "object is not a function". Why do I have to inclu ...

If either the form is invalid or has been submitted, disable the button

Is there a way to either disable the button when the form is invalid or after the user clicks it, but not both at the same time? How can I incorporate two statements inside the quotes for this purpose? I attempted the following code, but it didn't w ...

Maximizing the width of an absolute div element inside a container

Looking at this demo, you'll notice that the header remains fixed. However, my issue lies in getting the absolute <div> inside the <th> to occupy 100% of the width of the <th> When I set width: 100% for the <div>, it expands t ...

What could be the reason behind React's decision to not convert JSX to an HTML component and instead return [object Object]?

Please locate the specified console log within the code snippet provided below. This particular console log outputs a string value, indicating that an object is not being passed in this instance. However, despite this, React fails to recognize the JSX an ...

Jest came across a surprising token that it wasn't expecting while working with React and TypeScript in conjunction with Jest and React-testing-L

An unexpected token was encountered by Jest while using React and TypeScript along with Jest and React-testing-Library. Error occurred at: E:\Git\node_modules@mui\x-date-pickers\internals\demo\index.js:1 ({"Object." ...

Adding dynamic metadata to a specific page in a next.js app using the router

I was unable to find the necessary information in the documentation, so I decided to seek help here. My goal is to include metadata for my blog posts, but I am struggling to figure out how to do that. Below is a shortened version of my articles/[slug]/page ...

What is the best way to create a continuous loop of images on a never-ending

Many discussions cover similar topics, but I have not yet found a solution to my specific question. Currently, I am working on creating a model for a website and I am interested in incorporating an infinite rotating gallery with a limited number of images ...

Error in refreshing JWPlayer page: Plugin loading failure - File not located

I'm implementing JWPlayer on my Localhost environment. Here's the code snippet I'm using: <div id="Player">loading...</div> <script type="text/javascript"> jwplayer("Player").setup({ file: "<?php echo $video[' ...

The user values in jQuery alert function are correct, but the saveorupdate function fails to save null values in the database table

While using the alert function in jQuery, the user input values are alerted correctly, but for some reason they are being stored as null in the database table. Can anyone help me identify what might be causing this issue or what I might be doing wrong? I& ...

Unable to trigger submission in jQuery validate function after validation check

I'm currently facing an issue with my form validation using the jQuery validate plugin. Although I have successfully implemented validation for the desired areas of the form, I am unable to submit the form even after filling in all the required input ...

Ways to create a full-window image cover starting from the center point and extending to the right by 50

Seeking assistance from anyone who can help me with my current issue. I am currently utilizing bootsrap 4 and I need to come up with a solution for the following scenario: I have one element that is situated within the standard six columns, while the secon ...

An anchor-shaped name tag with a touch of flair

I stumbled upon this unique anchor name design on the website Does anyone here know how to create something similar? What is that style called? ...

Explore JSON data and populate dropdown and select elements with corresponding details

Looking for advice on how to separate bank details into a select box and employee details into a table using the JSON provided. Unsure of how to iterate through each section to place them in their required sections. If anyone has suggestions on how to acc ...

What is the best way to redirect to a specific page when logging out of a website?

To begin, let me outline the situation at hand. We have two distinct websites - website-A and website-B. Each of these websites is hosted on separate domains. A user has the ability to log in to website-B's homepage through the login page of webs ...

Steps to designing an Arrow with styled-components

I am currently working on customizing my orange arrow to resemble the pink arrow, but I want to achieve this without relying on an external CSS library like bulma. The reason the pink arrow looks different is because it utilizes the bulma library in its st ...

Reveal/Conceal footer upon vertical scrolling

I am attempting to achieve the following goals: Display the div element when the scrolling position is greater than 20 Apply a fadeOut effect after a certain delay Prevent the fadeOut effect when hovering over the sticky footer This is my implementation ...

"Having the same meaning as $(this) in jQuery, the CSS

Is there a CSS equivalent to the Jquery selector $(this)? For example: .widget h4 { background: black } .widget:hover h4 { background: white } In this scenario, when any element with the .widget class is hovered over, the child h4 changes its background ...