Guide on how to send a variable from JavaScript to an HTML string

I am encountering an issue in passing a variable to the inline JavaScript.

var namealert = key;

     $("#alerta").append("<div class='alert_item clearfix'><a href='#' id='delete_alert' onclick='localStorage.removeItem('" +namealert+ "'');'><img width='15px' style='margin-right:10px;opacity: 0.5;' src='img/error.png'></a><div class='date'>"+obj['0']+"</div><br><div class='title'>"+obj['1']+"</div><br><div class='msg'>"+obj['2']+"</div><br><a href='#' id='candidatar' onclick='candidatar()'><img width='100px' style='margin-right:10px;opacity: 0.8;' src='img/disponivel.png'></a></div>");

The current output shows:

<a href="#" id="delete_alert" onclick="localStorage.removeItem(" alerts_1481117090'');'>...</a>

I require it to display as

localStorage.removeItem('alerts_1481117090')
;

Answer №1

Many people have disagreed with your approach, but few have provided a clear example of what we mean by "adding event handlers". The onclick method you are using is technically an event handler, although not the best way to achieve your goal.

var $newElement = $("#alert")
.append("<div class='alert_item clearfix'>Click me!</div>");
    
// $newElement is a jQuery object returned by .append()

// set a click event handler. this is much better than doing the html
// onClick method you had in your question, because it requires no
// stringified javascript code evaluation.

$newElement.on("click", function (ev) {
alert("Hey, I was clicked! " + ev.target);
    // your local storage code here instead
});

  
.alert_item {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="alert">
<!-- elements to append here -->
</div>

It appears that you are just starting to learn javascript, so keep at it. While it may seem daunting at first, there is a helpful resource called "JavaScript, the Good Parts" that explains how to use the language effectively and safely.

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

Adjust the minimum and maximum values of the Y-axis based on the scale of the X-axis

Currently, I am faced with the challenge of adjusting the Y-axis to scale with changes in X-scale. I have a long unixtime value Array for initializing a flot chart, along with buttons to modify the scale. However, I am struggling to synchronize the Y-axis ...

JavaScript threw a SyntaxError: Unexpected character in line 1 while trying to parse JSON

I have a situation in Python where I load a variable with data and then convert it to JSON using the following code. jsVar = (json.dumps(jsPass)) This code produces the following output: {"TT1004": [[1004, 45.296109039999997, -75.926546579999993, 66.9966 ...

Trouble with Bootstrap 5 hidden elements and jQuery fading in and out smoothly

Utilizing Bootstrap 5, I want to implement a fade in/out effect on a specific div element. jQuery offers a handy function called fadeToggle() for achieving this, so I decided to give it a try. The desired functionality is as follows: The div element star ...

Executing a search and obtaining XML data from an external source

Currently, I am faced with the challenge of using Ajax to submit a query to an external database located at http://foreignserver:1234/database?query="SELECT FROM WHERE". The goal is to execute the query, generate an XML file, and have it returned to me. Th ...

Issues with Twitter-Bootstrap Modal Functionality

After creating a modal dialogue: <a href="#myModal" role="button" class="btn" data-toggle="modal" id="LaunchDemo">Click here to launch the demo modal</a> <!-- Modal --> <div id="myModal" class="modal hide fade" tabindex="-1" role="di ...

Guide to effortlessly loading files with designated decorators in a node.js application

Within the realm of Project A, I have constructed a decorator and am seeking a method to automatically load all these decorators upon initializing the application in Project B, which is the project utilizing Project A. Is there a way to accomplish this tas ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Tips for preserving textarea content upon clicking outside the area with the help of ajax

I am new to using the Froala editor and I am currently working on a feature where I need to save text in the textarea of the editor when the user clicks outside of it using Ajax. The ID of the content editor is #id_content. Here is a snippet of my form in ...

Having trouble with the postcss-import grunt plugin?

Here is the layout of my project: my_project |-- css | -- main.css |-- css-dev | -- main.css |-- node_modules | -- bootstrap | -- dist | -- css | -- bootstrap.css |-- package.json `-- Gruntfile.js The contents of my Gr ...

What is the best way to toggle between different sections of a webpage using HTML, CSS, and Javascript?

I am looking to display unique content based on the user's selection of different month/year options on the same page. For example, if the user chooses March 2021, I would like to show them events specific to that month. Here is a screenshot for refer ...

Failure in importing a custom CommonJS module

I developed a CommonJS module in project A using the following structure: const { WebElement } = require('selenium-webdriver'); const { By } = require('selenium-webdriver'); class VlElement extends WebElement { constructor(driver, ...

I'm having trouble applying CSS stylings to my components in my React project. What could be the issue causing this?

As a React beginner, I am facing issues with getting my CSS to work properly in my project. I know that CSS is not used directly in React, but rather interpreted as JavaScript using webpack and babel. What have I tried? I attempted to make changes to my w ...

Extract JSON data from Python API

Currently, I am delving into web programming and have created a Python API that queries an SQL database to return a JSON. The functionality of the API is as expected. In parallel, I've developed a controller where I execute a GET request to utilize t ...

Click event triggers dynamic function call

Is it possible to have different functions for ng-click depending on the loaded controller page? <a ng-click="removeEvent(event)" class="top_menu_link"> REMOVE</a> For instance, if I want the same button to trigger a remove action but on diff ...

"Converting Text from a Streamed XML-Like File into CSV: A Step-by-Step Guide

I have log files that contain C++ namespace artifacts (indicated by the double colons ::) and XML content embedded within them. After loading and displaying the logs in a browser application, the content has been separated from the Unix timestamps like so: ...

What is the process for adding an event listener in React?

Currently, I am working on a chat application that involves both users and agents. I am facing an issue where I need to retrieve messages when the agent responds using a separate Rainbow UI. According to the documentation, this can only be achieved using a ...

What is the best way to change a double-quoted integer into an integer?

Can anyone help me convert this to an integer? "'10'" Appreciate any assistance. ...

Utilizing the progress or meter tag in combination with a reactive value

Within my Vue class-based component, I am aiming to utilize a reactive value to showcase real-time progress changes using either a <progress> or <meter> tag. To achieve this, I have defined a variable that contains an initial base value: perce ...

Enhancing live query functionality and providing a substitute for DOMNodeInserted specifically tailored for

I have searched multiple times on various platforms for a solution to my specific issue, but have not found one that fits my unique circumstances. My goal is to replace outdated code such as livequery and DOMNodeInserted. See examples below. I am current ...

Change the color of a specific object in three.js using the dat.GUI color picker

Is there a way to assign a color using dat.gui in a single object within Three.js? I want to be able to select the color through a dialog box, similar to Box 3 in this example. Any suggestions on how to achieve this? ...