What is the most effective way to use Javascript to update an image depending on the selected value in a dropdown

My JavaScript skills are limited, but I have successfully created a form with 4 drop-down selection boxes on the left side for users to choose from (State, Car, Year, Condition).

After making their selections, users can click a 'calculate' button below, which triggers some simple functions based on their input and displays 4 different values on the right side of the form.

In the center of the form is an image named car1.png that I want to change depending on the value returned to Result 3. For example, if the result is 0.07 then show "car2.png", or if it's 0.06 show "car3.png". Despite reading tutorials on 'if' statements, I'm struggling to implement this feature.

I would greatly appreciate any suggestions on how to achieve this in a straightforward manner given my lack of expertise in this domain.

Here is what I have managed to create so far:

<HTML>
<body>

<script type="text/javascript"> 
function calcform() 
{ 
with (document.form1) 

{ result1.value = +number1.value * .75 * 50}
{ result2.value = +number2.value * 1}
{ result3.value = +number3.value * 1}
{ result4.value = +number2.value * +number1.value}
} 
</script> 

</div>
<div class="span17">
<table><form name="form1" action=""> 

<h4>State :<br/>
<select name="number" id="number1">
        <option value="15">SA</option>
        <option value="16">VIC</option>
                <option value="17">NSW</option>
        <option value="10">QLD</option>
                <option value="19">NT</option>
        <option value="14">WA</option>
    </select></h4><br/> 

<h4>Car :<br/>

<select name="number" id="number4">
        <option value="1">Ford</option>
        <option value="2">Nissan</option>
                <option value="3">Toyota</option>
        <option value="4">Holden</option>
    </select></h4><br/> 

<h4>Year :<br/>
<select name="number" id="number2">
        <option value="0.1">1980</option>
        <option value="0.2">1981</option>
                <option value="0.3">1982</option>
        <option value="0.4">1983</option>
                <option value="0.5">1984</option>
        <option value="0.6">1985</option>
    </select></h4><br/> 

<h4>Condition :<br/>
<select name="number3" id="number3">
        <option value="0.08">New</option>
        <option value="0.07">Used</option>
                <option value="0.06">Defect</option>
        <option value="0.05">Scrap</option>
    </select></h4><br/> 


<input type="button" id="Calculate" value="Calculate" 
onclick="calcform()" /><input type="reset" id="reset" value=" Clear "/></tr>

</span>

<div class="span20">

<br>
<br>
<img src="car1.png">

  </div>

<div class="span15">

<br/><tr><td><h4><strong></strong></h4><br/>
<h4>Result 1:<br /> 
<div class="span15">
<input type="text" id="result1" value="" size="40" /></h4><br/> 
</div>
<h4>Result 2:<br /> 
<input type="text" id="result2" value="" size="40" /></h4><br/> 

<h4>Result 3:<br /> 
<input type="text" id="result3" value="" size="40" /></h4><br/>

<h4>Result 4:<br /> 
<input type="text" id="result4" value="" size="40" /></h4><br/>
</form> </table>    </div>
                    </div>                
               </div>                
         </div>
     </div>        
       
</body>
</html>

Answer №1

If you want to update the image using JavaScript, follow these steps:

function calculateForm() 
{ 
with (document.form1) 
{ 
    result1.value = +number1.value * .75 * 50;
    result2.value = +number2.value * 1;
    result3.value = +number3.value * 1;
    result4.value = +number2.value * +number1.value;

    if(result1.value > 0)
        document.getElementById("myImage").src = "new_image_1.png";
    
    if(result2.value == 1)
        document.getElementById("myImage").src = "new_image_2.png";
} 

Note: The "if() statement should contain the condition for each image change." Make sure to replace "new_image_1.png" and "new_image_2.png" with the file paths of your desired images based on the conditions. You can add more conditions as needed.

Note 2: Using the with statement is acceptable in JavaScript. It specifies that the following blocks {} will use the prefix "document.form1.", e.g.:

document.form1.result1.value =  ...
document.form1.result2.value = ...
document.form1.result3.value = ...
document.form1.result4.value = ...

Remember to include this ID in your img tag:

<img id="myImage" src="car1.png">

Answer №2

If you're looking for a simple script to demonstrate how everything should function, check out this little example.

Check it out on Fiddle: http://jsfiddle.net/8axe4nu2/1/

Breakdown of the Code:

This script contains a function that executes when you click a button. The function currently alerts the selected car, but you can modify it to display an image in a specific div instead.

function carPicker(carValue){
    alert(carValue);
}

The section of the script where you utilize the click function to generate the desired output - in this case, extracting the selected value from a dropdown menu and displaying it through the previously defined function.

$("#carButton").on("click",function(){
    var carValue = $("#carPicker").val();
    carPicker(carValue);
});

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

Sorting and dividing an Array using Angular

Forgive me in advance if this sounds like a naive question, as Angular and Typescript are not my strong suits. I am assisting a friend with an issue that I can't seem to overcome. I have an array of players that includes details such as first name an ...

Organize rows in the table while maintaining reactivity

A challenge I'm facing with a web app (Angular SPA) is that it displays a large table without the ability to sort. To work around this issue, I've managed to implement sorting via the console. However, re-inserting the rows after sorting causes t ...

Tips for customizing the appearance of a functional stateless component in Reactjs using class objects

I am looking to create a functional stateless component in ReactJs following the guidelines outlined here. const MyBlueButton = props => { const styles = { background: 'blue', color: 'white' }; return <button {...props} sty ...

Browser unresponsiveness triggered by excessive Ajax setInterval functionality

Here is the test code I am currently using: <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>Ajax - one variable test</title> <style> body{ font-size: 12px; font-family: Arial;} </styl ...

Calculate the total number of vacation days not including holidays and weekend days

Looking for help with a program I've created to calculate total vacation days, excluding weekends and national holidays. Successfully excluded weekends, but struggling with how to ignore national holidays in the calculation. The program is built usin ...

After implementing two hooks with null properties, the code fails to execute

Recently, I encountered an issue with this section of the code after upgrading react scripts from version 2.0 to 5.0. const { user, dispatch } = useContext(AuthContext); const { data } = useFetch(`/contracts/${user.contractType}`); if (!user) { ...

The 'log' property cannot be found on the type '{ new (): Console; prototype: Console; }' - error code TS2339

class welcome { constructor(public msg: string){} } var greeting = new welcome('hello Vishal'); Console.log(greeting.msg); I encountered an error at the Console.log statement. The details of the error can be seen in the image attached below. ...

Avoiding the repetition of CSS animations during Gatsby page hydration

I am facing an issue in Gatsby where I have an element with an initial CSS animation. It works perfectly when the static site loads, but after hydration, it keeps repeating. Is there a way to prevent this from happening? Below is my styled components code ...

The Ajax call is successful, however, there is no update made to the database

I am currently working on a JavaScript script to allow for profile editing without having to reload the page, similar to how it was done on Facebook. However, I am facing an issue where the AJAX function returns success but does not make any changes in the ...

Using Javascript to extract a custom attribute from a button element

In my HTML, there is a button that has a custom property called data-filter-params: <button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button&g ...

"Utilize jQuery to prevent the default action, perform a specific task, and

I am currently working on a Rails application where I want to enable users to tag blog posts with categories by typing the tags into a text field and separating them with a space (which is functional!). However, I am facing an issue when trying to submit ...

Ways to adjust the div height to match the span height

.headerDesc { width: 100% + 1px; height: 70px; background-color: #4d2765; margin: 0 -8px; } .headerDesc span { padding: 5px; position: absolute; color: white; font-family: 'Arial', sans-serif; text-al ...

Dynamic content alongside a stationary sidebar that adjusts in width

Attempting to create a switchable sidebar (toggling between short and long form) using bootstrap, multiple examples, and online resources. The width of the sidebar changes when toggled, and I want the content to appear next to it regardless of its length. ...

employing jQuery for invoking webMethod results in receiving HTML... webMethod doesn't get invoked

Trying to invoke a method on an ASPX page from VisualStudio 2008 using javascript and jQuery, but only getting back the HTML of the page. Even changing the method name in the javascript does not result in an error message indicating that the method cannot ...

The selected custom button color is not appearing as intended when viewed in the

I'm currently in the process of creating a small webpage dedicated to showcasing my top favorite Zelda bosses using HTML, CSS, and Bootstrap 5. To make it more personalized, I decided to veer away from the standard Bootstrap button colors and create m ...

Changing the look of your website with PHP and a drop-down selection bar

Recently, I implemented a drop-down menu that allows users to choose a theme for the website. While this feature works fine, I'm facing difficulty in loading the selected theme upon pressing the "Apply" button as I am fairly new to PHP. I am aware tha ...

Struggling with aligning an image and text side by side in CSS

Struggling to get my text and image perfectly aligned horizontally? Despite being aligned, the image makes it seem otherwise. https://i.stack.imgur.com/u1QOh.png CSS Code: /* Copyright © 2016 Dynavio Cooperative */ .navbar { width: 100%; border ...

Tips for preventing the use of eval when invoking various functions

Here's a snippet of code I've been using that involves the use of eval. I opted for this approach as it seemed like the most straightforward way to trigger various factory functions, each responsible for different web service calls. I'm awa ...

After implementing ajax jQuery with Laravel 10, this page is experiencing technical difficulties

Seeking assistance from experienced individuals in dealing with Ajax jQuery within the context of Laravel. I have encountered a problem that has proven difficult for me to resolve on my own. Sample html code: <li> <a href="" onclick ...

Tips for verifying blank form fields

Is there a way to validate empty form fields before submission and show an alert? This validation is important as some fields are hidden using v-show. Here is an example: <!DOCTYPE html> <header> <script src="https://unpkg.com/vue@n ...