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

How can URL parameters be connected to context in a React portfolio website?

I have a compact portfolio site created with React that showcases my work as both a graphic designer and an aspiring web developer. Upon arrival, visitors encounter a landing page where they can choose to explore either the "design" or "web" sections, sett ...

Can html-webpack-plugin be configured to create <style> elements from CSS files?

I am managing a static site with Vue and Webpack. In my project, I have a file named style.css containing global CSS rules which I import using import './styles.css' in my index.js file. Additionally, I have some .vue files that generate their o ...

Navigating in CodeIgniter

I am facing a challenge with redirecting to another page in codeigniter, below is my JavaScript code snippet: <script type="text/javascript> $(document).ready(function () { var url = $('#baseurl').val(); var form = $(& ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

Unable to Retrieve Stripe Connect Account Balance

I've been attempting to retrieve the balance for my connected accounts in Stripe, but every time I make an API call, it keeps returning the platform's account balance instead of the connected account balance. This is happening while in test mode. ...

What is the best way to run code once a callback function has completed its task?

I am looking for a way to execute line(s) of code after every callback function has finished processing. Currently, I am utilizing the rcon package to send a rcon command to a Half-Life Dedicated Server (HLDS) hosting Counter Strike 1.6 server and receive ...

Issue with retrieving the value of a JavaScript dynamically generated object property

I'm currently working on a React Material-UI autocomplete component and facing challenges with accessing a Javascript Object property within a handleSelect function. Although I can retrieve the townname value using document.getElementById, I know thi ...

Leveraging the power of async to streamline the serialization of operations with numerous layers of callbacks in Node

I'm relatively new to working with node.js and I'm encountering difficulties in understanding callback functions. The issue arises when I need to execute a series of complex operations that involve a lot of code divided into modules with numerous ...

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...

Is your URL getting cut off in jQuery?

How can I properly display a URL in an HTML table without it getting truncated? I'm attempting to show it within a table using jQuery, but it seems to be cutting off the URL. Here's a snippet of my code. Any suggestions on how to fix this? <! ...

Using Vue to input an array

I'm struggling with how to handle this issue. The task involves taking input which should be a URL, and the user should be able to enter multiple URLs. For instance: <input type="text" v-model="fields.urls" class=&quo ...

Utilizing JavaScript and jQuery libraries in conjunction with periods

I am a bit puzzled about when to include the period before referencing class names. For instance, in this code snippet, why is a period included before the first use of the 'active-slide' class but not for the other two instances? var primary = ...

Utilizing web components in React by solely relying on a CDN for integration

I have a client who has provided us with a vast library of UI elements that they want incorporated into our project. These elements are stored in javascript and css files on a CDN, and unfortunately I do not have access to the source code. All I have at my ...

Problem encountered with PDFKit plugin regarding Arabic text rendering

When it comes to generating dynamic PDF files, I rely on the PDFKit library. The generation process is smooth, but I'm encountering difficulties with displaying Arabic characters even after installing an Arabic font. Additionally, although the Arabic ...

Creating dynamic templates and embellishments in VUE

My VUE components, including Field and Form, are able to dynamically render a form based on the provided data. <template> <form @submit="$emit('submit', $event)" > <template v-for="(item, index) in form.elemen ...

Error message: NGINX combined with Express.js and socket.io, page not found

I currently have a node/express.js/socket.io application set up on an Ubuntu Server running on port 3002. I've made sure to open all ports on the machine for accessibility. When accessing the app directly at 11.111.111.1:3002/, everything runs smooth ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

ajaxform is not providing the correct response

There is a form below that logs into Instagram based on the response it receives. If the login is successful (returns "ok"), then it shows success, otherwise it should display an error state. However, in my case, it always returns a null state for some un ...