"Trouble with jQuery: Selecting an image to change isn't

Can someone help me figure out why my simple image change on a dropdown isn't working correctly?

You can find the code on this Jsfiddle.

Thank you for any assistance!

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $("option").attr("imagePath"));
    event.preventDefault();
});

<img src="http://placehold.it/100/0000FF/000000" name="preview" /><br /><br />

<select class="form-control" name="display_avatar" id="display_avatar">
    <option value="1" imagePath="http://placehold.it/100/cccccc/000000">First</option>
    <option value="2"imagePath="http://placehold.it/100/ghghgh/000000">Second</option>
    <option value="3"imagePath="http://placehold.it/100/5fgrty/000000">Third</option>
    <option value="4"imagePath="http://placehold.it/100/ff0000/000000">Fourth</option>
</select>

Answer №1

If you want to retrieve the value from the first option only, use this code:

$("option").attr("imagePath")

For an alternative method, try the following code snippet instead:

this.selectedOptions[0].getAttribute("imagePath")

You can view the updated demonstration here: http://jsfiddle.net/979vbv0j/2/

Answer №2

$("option") retrieves all option elements on the current page. In order to achieve your desired outcome, you should implement the following code:

$("#display_avatar").change(function(){
    $("img[name=preview]").attr("src", $(this).find("option:selected").attr("imagePath"));
    event.preventDefault();
});

For further reference, visit: jQuery Get Selected Option From Dropdown

Update: View a working example here - http://jsfiddle.net/vm6zjobj/1/

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 contents of an HTTP POST request body (post parameter) upon activation of the specified POST request

Is there a way to intercept and modify an HTTP Post Request using jQuery or JavaScript before sending it? If so, how can this be achieved? Thank you. ...

What is the correct method for formatting text spacing?

A few months ago, I dabbled in web design and created a basic website. Now, I'm revisiting it to clean up the layout and make it more visually appealing. I initially used non-breaking spaces to separate paragraphs, but I know that's not optimal. ...

How come my image is not aligned to the right of the header in my HTML code?

My attempt to align an image to the right side of my heading using code was unsuccessful. Here is the HTML snippet I used: /* Aligning with CSS */ #colorlib-logo img { display: flex; align-items: center; width: 30px; height: 30px; } #colorli ...

"Exploring the possibilities of Ajax in conjunction with Sol

I recently completed a tutorial on Ajax Solr and followed the instructions in step one. Below is the code I wrote: header.php: <script type="text/javascript" src="static/js/ajax-solr/core/Core.js"></script> <script type="text/javascript" s ...

Tips on invoking a method from a JavaScript object within an AJAX request

Considering the following code snippet: var submit = { send:function (form_id) { var url = $(form_id).attr("action"); $.ajax({ type: "POST", url: url, data: $(form_id).serialize(), dataType: 'json', succes ...

The downside Div is being displaced by a Paragraph with an overflow-y:scroll property

In my Div, I have set the width and height of a paragraph along with the property overflow-y:scroll. It's working fine as the paragraph is displaying with a vertical scroll. However, it is causing displacement in the div below. Below is the HTML code ...

I'm attempting to store this HTML code in local storage in order to utilize it on a new cart page, but I keep encountering an error

Here is the HTML snippet: <div class="cofefe"> <img src="photos/Shop%20-%20French%2Roast.png"> <p>Somecoffee</p> <p>15</p> <p>French ...

Image flipping effect malfunctioning in Safari and Internet Explorer

My image flipping effect is not functioning properly in Safari and IE browsers. Here is the code I am using: .flipcard { position: relative; width: 220px; height: 220px; perspective: 500px; margin: auto; text-align: center; } .flipcard.v:hove ...

Google Chrome is unable to render a .eps file

Is there a way to include the "Download on the App Store" badge on my website? I downloaded the file as a .eps and it shows up correctly in Safari but not in Chrome. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> ...

Creating a handshake process for hybi-17

I am currently in the process of creating the handshake for the websocket hybi-17 protocol. I have been referencing the draft available at . Based on the guidelines provided in the draft, I have developed the following code snippets for both the client (us ...

Having trouble with the :first-of-type Pseudo Class in CSS?

I have been attempting to style the first link in an li element with a specific font color. When the li element is clicked, it gains the "open" class. I've tried using both li a:first-of-type and li a:first-child pseudo-classes to achieve this, but ...

Incorporate a vibrant red circle within a tab of the navigation bar

I'm looking to incorporate a red dot with a number into a messaging tab to indicate new messages. Below is the HTML code: <ul class="nav pw-nav pw-nav--horizontal"> <li class="nav-item"> <a class="nav ...

Utilizing JavaScript to trigger an alert message upon selecting various options and blocking the onclick event

Setting up a simpleCart(js) with selectable options presents a challenge. The task at hand is to display an alert if not all drop-downs meet specific requirements and to prevent the "Add to cart" button from adding items to the cart when these conditions a ...

What steps should I follow to ensure that the content for the back page is printed on the back page of a booklet when using paged.js?

In the case of a booklet printed from folded sheets, it is interesting to note that the number on the back page will always be divisible by 4. If the content does not have a multiple of 4 pages, then the back page will end up inside the booklet. For my cu ...

What are the steps for applying a Bootstrap class to an element?

I keep encountering this error in the console: Uncaught DOMException: Failed to execute 'add' on 'DOMTokenList': The token provided ('si col-md-4') contains HTML space characters, which are not valid in tokens. Below is a ...

Having trouble getting the hover effect to change the colors of CSS borders

I am experiencing difficulty in changing the background color of the 'About' button to yellow and the border color to blue when it is hovered over. Currently, only a small rectangle around the text changes to yellow on hover and I cannot figure o ...

What is the reason that preventDefault fails but return false succeeds in stopping the default behavior

I'm having trouble with my preventDefault code not working as expected. While using return false seems to work fine, I've heard that it's not the best practice. Any ideas why this might be happening? if ($('.signup').length == 0) ...

Tips for displaying an image using the image tag in jQuery

I am looking to dynamically append a share button image after every image tag that meets certain criteria. For the code snippet and demonstration, you can visit this fiddler link here. $(document).ready(function() { $("img").each(function() ...

Having trouble passing data between view controllers

In my AngularJS application, I have a table column in main.html that is clickable. When clicked, it should redirect to a new customer page with the value of the column cell as the customer's name. There is a corresponding service defined for the app m ...

Is it possible to absolutely position an element using its own bottom edge as a reference point?

Looking to achieve precise positioning of an element just off the top of the screen, specifically a sliding menu. Utilizing position: absolute and top: 0px is straightforward, but this aligns the element based on its top edge. Is there a way to achieve th ...