Javascript string - search substring if else replace -


i'd have on ecommerce product page simple "in stock" or "out of stock" message, erp solution i've use permit retrive db number of items currentrly in stock. can use js, i'm thinking small function search string have, extract number, if/else in order replace trigger id proper content.

here content of function:

var straval = straval.search (/\<div id\=\"\#avail\" class\=\"hidden\"\>/ + /\d+/ + /<\/div>/); var straval2 = straval.substring (32,-6); if (straval2 > 0) {     var str = document.getelementbyid("#in-stock").innerhtml;      var res = str.replace("#in-stock","in stock");      document.getelementbyid("#in-stock").innerhtml = res;     } else {     var str = document.getelementbyid("#in-stock").innerhtml;      var res = str.replace("#in-stock","out of stock");      document.getelementbyid("#in-stock").innerhtml = res;     } 

the string i've html is:

<div id="#avail" class="hidden">329</div> 

where "329" example - number variable 1 4 digits [ 0 - 12 - 329 - 2654 ]

there's wrong, don't know what. i'm learning js, i'm new it. all.

instead of adding

<div id="#avail" class="hidden">329</div> 

use data-* attribute this

<div class="product" data-stock="329"> 

here's little demo.


function displaystock(elem) {    // out of stock    if (parseint(elem.dataset.stock, 10) === 0) {      elem.queryselector('.stock').textcontent = 'out of stock';    }    // in stock    else {      elem.queryselector('.stock').textcontent = 'in stock';    }  }    displaystock(document.queryselectorall('div')[0]);  displaystock(document.queryselectorall('div')[1]);
<div class="product" data-stock="0">    <h2>some product</h2>    <p class="stock"></p>  </div>  <div class="product" data-stock="5">    <h2>some product</h2>    <p class="stock"></p>  </div>


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -