Attempted to retrieve attirbutes of an element using the .attr function. I dynamically create an input element using and assign the value to the class attribute.
$('.item-selection-amount').click(function(){
console.log($(this).attr('class'));
});
This will return:
item-selection-amount ui-corner-all price
item-selection-amount ui-corner-all 66.00
price is always different, but is it possible to pull the third value of the class attribute such as attr('class[2]')
etc?
You are using class
attribute incorrectly.
It is intended to be used for visual presentation.
What you want to do is to attach data to an element.
For that purpose you can use HTML5 data-
attributes:
$('.item-selection-amount').data('price', 66.00);
// ... later
$('.item-selection-amount').click(function(){
console.log( $(this).data('price') );
});
If you want to add price to the element just render the HTML similar to one below on the server:
<li class='item-selection-item' data-price='66.00'>Something</li>
Do you have prices included in HTML as CSS classes? You can't really rely on the order of CSS class names, unless you set them up in HTML and never change in JavaScript. You should generally manipulate and test CSS classes in jQuery using .addClass(), .removeClass(), .toggleClass() and .hasClass().
For storing data consider using data- attributes:
<span class="item-selection-amount" data-price="66.00">...</span>
and it would be easy to use with jQuery:
$('.item-selection-amount').click(function(){
console.log($(this).data('price'));
});
See DEMO. Instead of span you can use whatever tag you are using right now.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With