javascript update HTML content

Hello, I am trying to call a function called changeDivHTML which passes an image.

   <a href="javascript:void(0)" onclick="changeDivHTML(<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'>)">

This function adds the images to a specific ID's div.

The function looks like this:

 <script language="javascript" type="text/javascript">
                    function changeDivHTML(item)
                    {
                    alert(item);
                        previousInnerHTML = 'item';
                        alert(previousInnerHTML);
                        document.getElementById('image').innerHTML = previousInnerHTML;
                     }
</script>

But when I click on the images, the browser shows a JavaScript error.

Error: invalid XML attribute value
Source File: http://xxx.xxx.xxx.xxx:xxx/product_info.php?products_id=31
Line: 1, Column: 23
Source Code:
changeDivHTML(<img src=images/products/top/product_big1.jpg>)

Please help me figure out how to resolve this error.

Answer №1

changeDivHTML needs to be passed a string, but you have missed out the delimiters which is leading to the errors.

<a href="javascript:void(0)" onclick="changeDivHTML('<img src=\''.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'\'>')">

Answer №2

Make sure to pass the code as a string, not as a tag. Also, remember to close it properly at the end.

<a href="javascript:void(0)" onclick="changeDivHTML(\"<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'/>\")">

Additionally, modify the script in this way to ensure that you receive the image tag in the desired location:

<script language="javascript" type="text/javascript">
                    function changeDivHTML(item)
                    {                        
                        previousInnerHTML = item;
                        document.getElementById('image').innerHTML = previousInnerHTML;
                     }
</script>

Hopefully this information proves to be helpful for you. =)

Answer №3

One way to approach this is by sending the parameter as a string, like shown in the example below:

<a href="javascript:void(0)" onclick="updateContent('<img src='.BASE_IMAGE_PATH .$gallery_images[$index]['image_name'].'>')">

Remember to properly handle escape characters for security purposes.

Answer №4

To utilize this function, input a string (such as text enclosed in quotation marks) instead of using an invalid E4X

Answer №5

If you're looking to update the content of a DIV with new content when clicking a link, it's best to reference existing HTML within the document (which may be hidden initially using style="display:none"). Here's an illustration:

<div id="div1">This is div1 <img src="1.png"/></div>
<div id="div2">This is div2.</div>
<a href="#" onclick="swapContent('div1', 'div2')">Click to Swap</a>
<script language="javascript">
  function swapContent(source, target) {
    var elSource = document.getElementById(source)
      , elTarget = document.getElementById(target);
    elTarget.innerHTML = elSource.innerHTML;
  }
</script>

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

Navigating through complex immutable entities

I am having trouble working with multidimensional immutable arrays. I would like to make my array immutable, but I'm not sure how to do so. Consider the following data structure: // data { // item { name: someName, todos: [ ...

Mastering card sliding and spacing in React NativeLearn how to effortlessly slide cards horizontally in your React

My aim with the following code snippet is to achieve two objectives: Apply a margin of 20 units to each card Display all four cards in a single row, allowing users to swipe horizontally Unfortunately, I have not been successful in achieving either of th ...

Changing the image's flex-grow property will take precedence over the flex settings of other child

This is the error code I am encountering, where "text1" seems to be overridden <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <!--mobile friendly--> <meta name="view ...

Searching for a specific match in JSON data using React streaming technology: encountering issues with the .find method as

Having experience with functional programming in Java, I recently ventured into JavaScript. My current task involves streaming through a JSON output structured like this: { "originatingRequest": { "clientId": 1, "simulationName": "Sea ...

Is it possible to display two separate pieces of content in two separate divs simultaneously?

import React from "react"; import ReactDOM from "react-dom"; ReactDOM.render( <span>Is React a JavaScript library for creating user interfaces?</span>, document.getElementById("question1") ) ReactDOM.render( <form class="options"> ...

Using optional arguments in my AngularJS controller.js

In my controller.js file for AngularJS, I have the following code snippet: app.controller('MetaDetailGroupList', ['$scope', '$http', function($scope, $http) { $http.get(Routing.generate('meta-detail-group-list&ap ...

Tips for refreshing a webpage after switching screens

// I have implemented the code below to navigate from one screen to another, specifically the Home page. However, I am facing issues with the page refreshing or reloading when navigating to the home screen. None of the lifecycle methods are being called, e ...

Techniques for capturing Django's output from an Ajax request

I've been trying to utilize Ajax for converting my form data to JSON and sending it to my Django view. However, I'm encountering an issue where after successful processing in the view, I am returning a template response with some context data tha ...

providing text responses rather than numerical values

I am currently working on developing a function called onlyOddNumbers that takes an array of numbers as input and outputs a new array with only the odd numbers. The function is operational, but I have encountered an issue where strings are being included i ...

Add a plethora of images to the canvas

Just starting out with Fabric.js and trying to figure out how to draw a picture on the canvas after a drop event. I managed to do it once, but am struggling with inserting more pictures onto the canvas (each new drop event replaces the previous picture). ...

Creating aliases for a getter/setter function within a JavaScript class

Is there a way to assign multiple names to the same getter/setter function within a JS class without duplicating the code? Currently, I can achieve this by defining separate functions like: class Example { static #privateVar = 0; static get name() ...

I have a json file that I need to convert to a csv format

I am currently working with a json file, but I need to switch it out for a csv file. Do I have to use a specific library to accomplish this task, or can I simply modify the jQuery 'get' request from json to csv? I attempted the latter approach, b ...

The Discord.js collector seems to have no intention of ending, completely disregarding its keys in order

Help Needed with Discord Message Collector Issue I encountered a problem with my code that assigns ranks on Discord. It seems that the message collector is not responding to keys that should stop it from collecting messages. Can anyone offer assistance in ...

Steps to display content post authentication using JWT

Utilizing Nodejs and Express for application development. Utilizing JWT for authentication. I have successfully implemented the JWT-based authentication system and tested it with Postman. However, I am facing an issue when passing the request through the ...

Adjust the TextArea content according to the quantity of selections made in the listbox

If I have a listbox alongside a textarea: <textarea id="MyTextArea"></textarea> <select id="SelectList" multiple> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="me ...

calls to res.send and res.render

I'm currently trying to determine if it's possible to use res.send(data) and res.render('reports') simultaneously in my code. To provide more details, when I navigate to '/reports', on the server side I am executing a REST ca ...

Executing php class method through ajax with jQuery without requiring a php handler file

How can I trigger a PHP class method using AJAX with jQuery without the need for a separate PHP handler file? Here is my PHP Class animal.php:- <?php class animal { function getName() { return "lion"; } } ?> jQuery code snippet:- ...

Hacking through external script injections into the browser

Curious about how certain software or programs are able to inject html,css,js into a web browser without the need for installing any extensions. Every time I open Chrome or Firefox, I'm bombarded with ads on popular sites like Google homepage, Faceboo ...

Facing issue with local redis session not functioning as intended

I'm encountering an issue with my redis session not functioning properly when testing locally. EDIT: Additionally, I realized that it's failing to save a cookie when trying to set req.session[somekey] as undefined like so: req.session.user = u ...

Positioning of Cloned Element in jQuery

When a user presses enter while in one of the text input fields provided, I want to add a new empty text input field directly below it - and before the other existing ones. The code snippet below currently adds the new field at the end of the container, bu ...