简体   繁体   中英

Dynamically change the HTML <img> src attribute using Java Script or JQuery

I need to change the html img src value dynamically from the value from hidden text field using Jquery or Java script.

<p><img id="yui_img" height="333" width="345"></p>

function onImgChange()
 {
document.getElementById('yui_img').src=document.getElementById('addProductLinksCreateForm:addProductLinkUrlValue').value;

 }

I got the value in the DOM but it is not getting reflected in it. Old image is maintained.

This should work, but you need to ensure that these are the case:

  • Does the textbox tag look like <input type="text" id="addProductLinksCreateForm:addProductLinkUrlValue"> ?

  • Are you calling onImgChange() at all? You could try document.getElementById('addProductLinksCreateForm:addProductLinkUrlValue').onchange = onImgChange; to allow that to happen when the user switches to a different text box.

Using jQuery, it would look like:

function onImgChange() {
     $('#yui_img').attr('src', function(i, src) {
         return $('#addProductLinksCreateForm').attr('src');
     });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM