skip to Main Content

This might be a silly question, because I have not found any information on my specific problem anywhere, and this is my first javascript/html project.

I want to pass in the name of a book, and its price, by the id’s associated them (book1 and price1). My thinking is that this way, if the name or price changes later, the function “addToCart(book1,price1)” will automatically pass in the updated name/price. Is it possible to pass strings into a function this way in javascript/html5?

Here is part of the code:

<td>
    <span class="bookName" id="book1">
        <b>Artificial Intelligence: Modern Approach</b>
    </span> <br>
    <b>PRICE: $</b> 
    <span id="price1"> 158.55 </span> 
    <button type="button" onclick="addToCart(book1, price1)">Add to cart!</button>
</td>

Thanks in advance!

2

Answers


  1. HTML

    <button type="button" onclick="addToCart('book1', 'price1')">Add to cart!</button>
    

    JS

    function addToCart(productId, priceId) {
        // ...
    }
    

    Just a few other notes about your code:

    • Use <br /> instead of <br>, otherwise it is not valid HTML
    • Ideally use a <label> tag, this makes it more accessible

    Eg

    <label for="price1">PRICE:</label>
    <span>$</span>
    <span id="price1">158.55</span>
    
    • It’s normally better to hook up events in a separate JavaScript file (or <script> tag) instead of HTML attributes. This provides a more clean separation of your functionality and your markup/UI
    Login or Signup to reply.
  2. assuming you’re using jquery:

    onClick="addToCart($(this).siblings('.bookName').text(), $(this).siblings('.price').text())"
    

    This would require you to put a class onto the price span (<span class="price">158.55</span>).

    Remember… every element in the DOM “knows” where it is, and you can trivially navigate up/down this tree to find related elements nearby.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search