Pancreatico Pancreatico - 1 month ago 8
HTML Question

Count how much similar id's exists

Well, I have an html document containing particular id elements on a table, this ids are composed like this: "word + a number starting by 1 + word", and has a class, that could be "enabled" or "disabled".

It's something like this:

<table>
<tr>
<td class="enabled" id="Bart1sim"></td>
<td class="enabled" id="john1doe"></td>
</tr>
<tr>
<td class="enabled" id="Bart2sim"></td>
<td class="enabled" id="john2doe"></td>
</tr>
<tr>
<td class="disabled" id="Bart3sim"></td>
<td class="enabled" id="john3doe"></td>
</tr>
<tr>
<td class="disabled" id="Bart4sim"></td>
<td class="disabled" id="john4doe"></td>
</tr>
</table>


And when click on whatever "enabled" td, the last "enabled" td (let's think that all similar ids are grouping the tds) class must changes to "disabled".
When click on whatever "disabled" td, the last "disabled" td class must changes to "enabled".

I think if I could check by the id's what's the last "enabled" td class of each group, this should works.

This is what I already have but doesn't works:

$(document).ready(Principal);

function Principal() {
$(document).on("click touchend", ".enabled, .disabled", function() {
LetsDoThis(this.className)
});
}

function LetsDoThis(clas) {
if (clas == "enabled")
$("." + clas + "").removeClass("enabled").addClass("disabled");
else
$("." + clas + "").removeClass("disabled").addClass("enabled");
}


Thanks for your time.

Edit

var num = $('[id^="Bart"]').length gives number of all ids starts with "Bart", but I could have ids like Bart1Fla, Bart2Fla, Bart3Fla.. Bart1Ned, Bart2Ned, Bart3Ned.. which are different id groups, so I still need to check the last word after the number to count the ids.

Answer

You can use combination of Attribute Starts With[name^=”value”] and Attribute Ends With [name$=”value”] Selector.

You can also use .filter() method to add additional checks

//Get elements which starts with "Bart" and ends with "sim"
var elements = $('[id^="Bart"][id$="sim"]');

//Additional check
elements.filter(function() {
    return /^Bart[0-9]+sim$/.test(this.id);
});

var num = elements.length;

jQuery(function() {
  //Get elements which starts with "Bart" and ends with "sim"
  var elements = $('[id^="Bart"][id$="sim"]');
  
  //Additional check
  elements.filter(function() {
    return /^Bart[0-9]+sim$/.test(this.id);
  });
  
  var num = elements.length
  console.log(num);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="enabled" id="Bart1sim"></td>
    <td class="enabled" id="john1doe"></td>
  </tr>
  <tr>
    <td class="enabled" id="Bart2sim"></td>
    <td class="enabled" id="john2doe"></td>
  </tr>
  <tr>
    <td class="disabled" id="Bart3sim"></td>
    <td class="enabled" id="john3doe"></td>
  </tr>
  <tr>
    <td class="disabled" id="Bart4sim"></td>
    <td class="disabled" id="john4doe"></td>
  </tr>
</table>

Comments