In a jQuery application, the action of adding text from an input field to a div is triggered by clicking a

It's possible this is a duplicate question, but none of the answers I found solved my issue. I'm attempting to create a jQuery script where text entered into a text box is appended to a div when a button is clicked. This is part of a game I'm working on, and currently, I just want to ensure the variable correctly stores and displays the input in the div. Below is my HTML code:

<!DOCTYPE html>
<html>
<head>
    <title>Potentially a Game</title>
    <link rel="stylesheet" type="text/css" href="style.css"/>
    <script type="text/javascript" src="script.js"></script>
</head>
<body>
    <h2>Please enter your name.</h2>
    <form name="userInput">
        <input type="text" name="textInput"/>
    </form>
    <button id="confirm">Confirm</button>
    <br/>
    <div class="textOutput"></div>
</body>
</html>

Here is my CSS snippet:

h2 {
font-family:arial;
}
form {
display: inline-block;
}
.list {
font-family:garamond;
color:#cc0000;
}

Now, take a look at my jQuery code:

$(document).ready(function(){
    $('#confirm').click(function() {
        var playerName = $('input[name=textInput]').val();
        $(".textOutput").append("<p>" + playerName + "</p>");
    });
});

The aim here is to store the input from the textInput field in the playerName variable. When the confirm button is clicked, a <p> element holding the playerName value is added to the .textOutput <div>. I followed a Codecademy tutorial for guidance, and the code closely mirrors what was taught. Despite this, the code works flawlessly within the tutorial platform, but not in my standard editor. I even copy-pasted the tutorial code directly into my editor with no success. My current editor is Sublime Text 2. I can't identify the error in my implementation. Any help would be greatly appreciated.

Answer №1

Kindly substitute the following:

<script type="text/javascript" src="script.js"></script>

with

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

and then test your code:

 $(document).ready(function(){
    $('#confirm').click(function() {
       var playerName = $('input[name=textInput]').val();
       $(".textOutput").append("<p>" + playerName + "</p>");
    });
   });

Answer №2

I assume you are planning to save it as a text file.

To properly save the file, make sure to save it with either the extension .html or .htm, then enclose the script in the <script> tag and style in the <style> tag before opening it in a web browser.

Answer №3

In order to utilize jQuery, it is essential to incorporate the jquery-library by inserting the following code snippet inside the head-tag:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

Answer №4

No jQuery libraries are included in the head section of your code.

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

Your code is functioning correctly, as evidenced by this example: http://jsfiddle.net/haxtbh/2gMgQ/

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

Tips for conducting unit tests on navigator.notification.alert

I am currently facing a challenge in writing a unit test for a JavaScript function where I need to fake the navigator.notification.alert method. Can anyone provide suggestions or solutions? Below is the code snippet that I have attempted: navigator = { ...

Sharing the input value with a service in Angular 4

I am a beginner when it comes to Angular 4. I currently have a variable named "md_id" which is connected to the view in the following way. HTML: <tr *ngFor="let item of driverData"> <td class="align-ri ...

Is there a way to preserve all the downloaded node modules in the package.json file?

Is there a way to keep track of all the node modules installed in package.json without the need for reinstalling them? I've heard about running npm init --yes, but I'm not entirely convinced if that will do the trick. Any assistance on this mat ...

"Exploring the power of Vue3's composition API in managing the

Trying to implement an accordion component in Vue 3, but encountering a strange comparison issue. I'm attempting to execute a function within the accordionitem - specifically the toggle operation. However, despite numerous attempts, I am unable to mo ...

Issue with Safari not displaying properly when using float:left and float:right (works fine in Firefox and Chrome)

My website has a left side column and a right side column, which display correctly in Firefox and Chrome. However, I am experiencing issues with Safari. Any insights on what could be causing this problem and why it only occurs in Safari? View the code on ...

Horizontal rule located within a table but spanning the entire width

I wrote the following code: <table> {item.awards.map((obj,i) => <tbody> <tr> <td>Name</td> <td>:</td> <td>{obj.title}</td> </tr> ...

Utilize Javascript to input text into a webform

I am working on creating a bot that simulates user input for the WattsApp web website. When I manually type a message into the website, it enables a button that allows me to send the message. However, when my script runs, it finds the input box, changes t ...

What is the process for uploading files with just node.js?

My dilemma involves a webpage featuring a form with a file input field. Upon submitting the form, I wish for the server to write the file on the server side. Despite numerous attempts to upload various test images using this form, each results in a plain ...

Adjusting content within a div using a loop with a pause interval

I am working on a project where I need to manipulate the content of a div. Here is the initial code snippet: <div class="mytext">first</div> My goal is to dynamically change this text from 'first' to 'second' after 5 s ...

Using useCallback with an arrow function as a prop argument

I'm having trouble understanding the code snippet below <Signup onClick={() => {}} /> Upon inspecting the Signup component, I noticed the implementation of useCallback as follows const Signup = ({onClick}) => { const handleClick = us ...

Issue with jQuery connected sortable: clicking to move items is not functioning properly

I am currently working on a project that involves two connected sortable lists using jQuery UI. I have successfully implemented the functionality where clicking on an element in one list will add it to the other list and vice-versa. However, I have encount ...

There was an issue stating that valLists is not defined when paginating table rows with AngularJS and AJAX

I found a helpful code snippet on this website for implementing pagination in AngularJS. I'm trying to adapt it to work with data from a MySQL DB table called 'user', but I keep running into an issue where the valLists variable is undefined, ...

"Enhance your website with a dynamic Jssor slider featuring nested slides and vertical

Exploring the idea of merging the nested slider feature with a vertical thumbnail display. Reviewing the source code for examples image-gallery-with-vertical-thumbnail.source.html and nested-slider.source.html, I am wondering how to effectively combine t ...

Using javascript to overlay and position many images over another image

I've searched extensively but haven't been able to find any relevant answers here. Currently, I am developing a hockey scoring chance tracker. My goal is to display an image of the hockey ice where users can click to mark their input. Each click ...

What is the best way to send a List in the model as a parameter for an AJAX request?

I'm currently using MVC 4 ASP.net with Razor views and I have an issue with refining my search results using AJAX calls. The current approach involves creating methods in the controller that include all the search filters, which has resulted in a meth ...

`json: Alert not displaying response data`

Currently, I am utilizing the following Ajax code to retrieve data from the server. $.get("http://***/umbraco/Api/SomeApi/SignIn",{apiVersion : 1,email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ee0efe3ebcee9e3efe7e2a0ed ...

Angular version 7.2.1 encounters an ES6 class ReferenceError when attempting to access 'X' before it has been initialized

I have encountered an issue with my TypeScript class: export class Vehicule extends TrackableEntity { vehiculeId: number; constructor() { super(); return super.proxify(this); } } The target for my TypeScript in tsconfig.json is set to es6: ...

Steps to quickly display the Badge after switching routes on the page

This is my initial post, so please bear with me if I haven't provided enough details or if I've made a foolish mistake For my semester project, I am constructing a shop using basic ReactJS (without Redux or any database). Just to clarify, I have ...

Embracing the power of dynamic imports in Next.js 10 with SDK integration for

I attempted to dynamically import the TRTC SDK using Next.js 10: const TRTC = dynamic(() => import('trtc-js-sdk').then((module) => module.NamedExport), { ssr: false }); However, I encountered an error stating "TRTC.createClient is not a co ...

Tips for adjusting the size of grid tiles according to the dimensions of the window within a specific range

I am currently exploring how to replicate the effect found on this webpage: When the window size is adjusted, javascript dynamically resizes the grid tiles between 200 and 240px based on the optimal fit for the screen. Is there a ready-made JavaScript/jQ ...