Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery confusing code

I am learning Jquery and Javascript from web examples. I have a good working knowledge but some code still trips me up. The following code is used for a shopping cart to hide the check out button and replace with a div displaying a message about minimum cart requirements. There is a part of the code throwing me off though.

function getCollectionCount() {
  var totalCollectionCount = 0;    
  var collection = $('td[alt*="Collection"]');
  for (var i = 0; i < collection.length; i++) {
    var curVal = $(collection[i]).find("select").val();
    if (curVal != undefined){
      totalCollectionCount += parseInt(curVal);
    }
  }

What does this part mean?

var collection = $('td[alt*="Collection"]');
like image 711
Jason Johnson Avatar asked Jul 15 '26 00:07

Jason Johnson


2 Answers

td[alt*="Collection"] selects all <td> elements whose alt attribute contains Collection, such as:

<td alt="Collection"></td>
<td alt="CollectionFoo"></td>
<td alt="BarCollection12324343"></td>

but not

<td></td>
<td alt=""></td>
<td alt="Foo"></td>

Side note: this is a pretty basic question that could easily be answered by read the jQuery selectors API documentation:

  • element selector
  • attribute-contains selector

Please do try to research before you ask!

like image 70
Matt Ball Avatar answered Jul 16 '26 12:07

Matt Ball


This is a jQuery attribute selector clause. It's selecting any td element which has an atrtibute named alt whose string contains the value Collection.

Contains Selector: http://api.jquery.com/attribute-contains-selector/

jQuery has a number of useful attribute selectors. Here is the main reference page for them. Very much worth the read if you're just getting started with jQuery

  • http://api.jquery.com/category/selectors/attribute-selectors/
like image 20
JaredPar Avatar answered Jul 16 '26 12:07

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!