Pujdo P. Pujdo P. - 3 months ago 6
Javascript Question

indexof() not selecting the first instance of string

been trying to figure this out for some time now and I can't seem to do it.

I have this for casperjs

var size = this.evaluate(function () {
var number = 10;

var size;
$('select[name="placeholder"] option[name="plId"]')
.each(function (index, dom) {
var currentsize = $(dom).attr('value');
if (String(currentsize).indexOf(
String(number)) > -1) {
size = currentsize;
}
});
return size;
});


and I'm trying to select 10 from the value

<option name="plId" value="25437456:10" data-label="(10)">10</option>
<option name="plId" value="53467763:10.5" data-label="(10.5)">10.5</option>


but for some reason it selects 10.5 every time, when it should select 10.

Anyone know what's wrong? Appreciate the help

Answer

The .each() loop processes every element. So the size variable will end up being the last item that matched rather than the first.

You can stop the loop as soon as you have a match by returning false from within the function you passed to .each().

var size = this.evaluate(function() {
      var number = 10;

      var size;
      $('select[name="placeholder"] option[name="plId"]')
        .each(function(index, dom) {
          var currentsize = $(dom).attr('value');
          if (String(currentsize).indexOf(
            String(number)) > -1) {
            size = currentsize;
            return false;  // <--- ADD THIS
          }
        });
      return size;
    });
Comments