G.Dauria February 2016

Javascript string - search substring if else replace

I'd like to have on an ecommerce product page the simple "in stock" or "out of stock" message, but the ERP solution that I've to use only permit to retrive from its db the number of items currentrly in stock. I can only use JS, so I'm thinking to a small function that will search for the string I have, extract only the number, do an if/else in order to replace a trigger id with the proper content.

here the content of the 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 that I've into the html is:

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

where "329" is an example - this number is variable from 1 to 4 digits [ 0 - 12 - 329 - 2654 ]

There's something wrong, but I don't know what. I'm learning JS, so I'm really new to it. Thanks to all.

Answers


naomik February 2016

Instead of adding

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

Use a data-* attribute like this

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

Here's a 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>

Post Status

Asked in February 2016
Viewed 1,118 times
Voted 13
Answered 1 times

Search




Leave an answer