简体   繁体   中英

Javascript onclick image display alt-tag in inputbox

I got a basic question about an onclick event with an image. I have four images that are products with a price. The price is in the Alt-tag (for simplicity all 100 now). See the HTML below:

<img src="product1.png" alt="100" onclick="pricecheck();" id="product1" />
<img src="product2.png" alt="100" onclick="pricecheck();" id="product2" />
<img src="product3.png" alt="100" onclick="pricecheck();" id="product3" />
<img src="product4.png" alt="100" onclick="pricecheck();" id="product4" /> <br />

<label for="Price" >Price:</label><input type="text" name="price"/><br />            
<label for="totaal">Total:</label><input type="text" name="total"/>

I just don't know how to make a function that will show the alt-tag in the input "price" when you click on the image. the input "total" should be able to show the total price of all the images(products) that were clicked on.

I hope you guys could help me out with this.

Greetings

Use jQuery , edit your html become(adding an 'id' parameter) :

<img src="product1.png" alt="100" onclick="pricecheck(1);" id="product1" />
<img src="product2.png" alt="100" onclick="pricecheck(2);" id="product2" />

your jQuery function :

function pricecheck(id){
   $('input[name="price"]').val($('img#product' + id).attr('alt'));
}

using pure javascript.

edit first your input tag : <input type="text" name="price" id="price" />

function pricecheck(id){
   var img = document.getElementById('product' + id);
   document.getElementById('price').value = img.getAttribute("alt");
}

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