Switching visual content according to dropdown choice

Hey there! I've been working on my HTML file and ran into a little issue. I'm trying to change the image in the div section based on a dropdown selection that modifies the source of the image from an XML file. However, I keep getting an error that says 'Cannot set property 'src' of null'. Any assistance would be greatly appreciated!

HTML

<!DOCTYPE html>
    <html>
        <head>
            <title>
            </title>
            </head>
    <body>

    <img id="change" src="ecomm.jpg" onload="loadXMLDoc()"/>
      <div id="imagechange" >

          </div>

    </body>
    </html>

Script

function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            myFunction(xmlhttp);
        }
    };
    xmlhttp.open("GET", "bf.xml", true);
    xmlhttp.send();
}

function myFunction(xml) {
    var i;
    var xmlDoc = xml.responseXML;

    var x = xmlDoc.getElementsByTagName("food");

    var str ="<select id='image' onchange='changeFunc(this.value);'>";
    str+= "<option value='select image'> Select Image </image>";

    for(i=0;i<x.length;i++){
        str +='<option value=' + x[i].getElementsByTagName("source")[0].childNodes[0].nodeValue + '>' + x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue + '</option>'; 
    }

    str +='</select>';
    document.write(str);

}

function changeFunc(val) {
    document.getElementById('change').src = val;
}

Answer №1

The reason for this issue is due to document.write(str);. This function completely replaces the entire document with the contents of str, resulting in the removal of 'change'.

To add the element instead, you should use

document.getElementById('change').appendChild(str)
.

Check out more information on this topic at:

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

Determine if a Node.js Express promise holds any data

I'm looking for assistance with my nodejs application that returns a promise. What I need help with is figuring out how to determine if the result of this promise contains data or if it's just an empty array. I attempted using Object.keys(result) ...

A guide to displaying a JSON object in a Jade template and iterating through the data

When I pass a JSON string to a jade file for rendering, I am facing an issue where I can only print the entire string and not its individual elements. How can I print specific elements or iterate through the JSON string? app.js: var http = require(&ap ...

Ajax requests are returning successful responses for GET and POST methods, however, no response is being received for

When I make a POST request within the same domain ( -> ), the responseXML contains the expected data. However, when I make the same request as a PUT, the responseXML is null for a successful request. I have tried using jQuery.ajax and even implemented i ...

Res.redirect() showing unexpected behavior

In my current setup, I am utilizing a modified version of the vhost connect/express middleware. Within this middleware, there is a check for the presence of the www subdomain. If the subdomain is found, it should redirect to the host + path without the www ...

JavaScript event in Chrome extension triggers a browser notification and allows for modification using a specific method

I am currently developing a Chrome extension that is designed to take specific actions when system notifications appear, with the main goal being to close them automatically. One example of such a notification is the "Restore pages?" prompt: https://i.sta ...

The parameter being passed in the JSON request is empty within the WCF Service function

I have been trying to send a list of confirmations to a server using Ajax from jQuery. However, I am facing an issue where the data is being sent but the service on the server side does not receive the list. The web method expects two parameters - a strin ...

JavaScript Page Search - Error in Finding Single Result

I am currently working on implementing a 'find in page' search box and have come across some JavaScript code that is working really well. Everything works great when there are multiple strings, as pressing enter cycles through the results and the ...

What Are the Possible Use Cases for Template Engine in Angular 2?

For the development of a large single page application (SPA) with Angular 2.0, I have decided to utilize a template engine like JADE/PUG in order to enhance clarity and clean up the code. My goal is to achieve optimal performance for the application. Th ...

Can Facebox's settings be adjusted during runtime? If so, how can this be done?

Can Facebox settings be accessed and customized? For instance, I am interested in setting the location of the loading image dynamically as shown on line 4: <script type="text/javascript" src="<?php echo base_url(); ?>media/facebox/facebox.js" > ...

Can you help me transform this javascript code into a JSON format?

Is there a way for me to organize my data so that I have one main question with 5 choices, each associated with a vote? It's like thinking of it as a tree where the question is the root and has 5 leaves, representing the choices, and each choice furth ...

Handling Firebase callbacks once the save operation is completed

Currently using AngularFire with Firebase. Unfortunately, still stuck on Angular 1 :-( I'm curious if there's a method to set up a callback function that triggers every time data is successfully saved in the database. I am aware of the option to ...

Codeigniter unable to fetch data sent via AJAX

I am in need of assistance with my mobile app development project. I am using phonegap/cordova for the app and codeigniter for the web service. The app includes a registration function where data is sent via Ajax to a codeigniter controller and saved in a ...

Struggling to destructure props when using getStaticProps in NextJS?

I have been working on an app using Next JS and typescript. My goal is to fetch data from an api using getStaticProps, and then destructure the returned props. Unfortunately, I am facing some issues with de-structuring the props. Below is my getStaticProp ...

What is the best way to call an Angular component function from a global function, ensuring compatibility with IE11?

Currently, I am facing a challenge while integrating the Mastercard payment gateway api into an Angular-based application. The api requires a callback for success and error handling, which is passed through the data-error and data-success attributes of the ...

What is the process to set a Woocommerce checkout field as optional when a checkbox is marked?

I need assistance with customizing the checkout page on Wordpress Woocommerce. Specifically, I want to make the field 'billing_name' not required if the checkbox 'buy_on_company' is checked. Currently, I have successfully hidden ' ...

Retrieve the highest integer from the server-side for the client

When creating input fields of type number on the client side, I have been setting their max attribute to the maximum integer value in the user's browser using: Number.MAX_SAFE_INTEGER.toString() Now, I need to output an input field on the se ...

Incrementing a variable based on a condition in JavaScript

Currently, I am working on a project where I have a variable called "total" that needs to be assigned a number (or price) and then incremented when certain options are selected or checked. Below is the code that I have developed up to this point. This sni ...

"Auth.currentSession is indicating that there is no user currently logged in

I am currently working on a basic React app with authentication using aws-amplify. My user pool is set up in Cognito and I can successfully redirect the user to the hosted UI for login. However, when trying to retrieve the current session, I am receiving a ...

Leverage the power of Ajax combined with XMPP for real-time communication, or

I created a straightforward AJAX chat application using jQuery. The process is simple: the message is sent to a PHP file via AJAX, then the message is encoded in JSON and saved in a text file for the recipient to retrieve. The JSON format is basic, such as ...

Combine javascript and css sequentially

I have a few tasks that involve combining CSS and JavaScript together. Here is an example of how I accomplish this: gulp.task('javascript', function() { return gulp.src([ libPath + 'jquery-2.1.4.min.js', libPath + '*.js& ...