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
HTML
JS
Just a few other notes about your code:
<br />
instead of<br>
, otherwise it is not valid HTML<label>
tag, this makes it more accessibleEg
<script>
tag) instead of HTML attributes. This provides a more clean separation of your functionality and your markup/UIassuming you’re using jquery:
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.