1

I want to get the titles and loop them to get the innerHTML.

My code is not working. Why? Please, explain because this happens very often and I dont know the solution

function createInputsForWebAppRemotes() {
  var titles = $('.collapseTitle');
  for (var title in titles) {
    console.log(title.html());
    if (title.html().indexOf("(CSR)" || "(ADMIN)")) {
      $('#remoteWebAppDiv').append('<input class="form-control" name="remoteWebAppUrl" type="url"/>');
    }
  }
}
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135

1 Answers1

0

The for...in statement iterates over the enumerable properties of an object

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

In this case jQuery element (the output of $ function) is not enumerable properties but a jQuery object. So the right way is to use $().each

Iterate over a jQuery object, executing a function for each matched element.

Suppose your html is partial similar to the code below:

function createInputsForWebAppRemotes() {
  var titles = $('.collapseTitle');
  titles.each(function() {
    var title = $(this).html();
    console.log(title);
    if (title.indexOf("(CSR)") > -1 || title.indexOf("(ADMIN)") > -1) {
      $('#remoteWebAppDiv').append('<input class="form-control" name="remoteWebAppUrl" type="url"/>');
    }
  });
}

createInputsForWebAppRemotes();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="collapseTitle">Title 1</div>
<div class="collapseTitle">(CSR)</div>
<div class="collapseTitle">Title 3</div>
<div class="collapseTitle">(ADMIN)</div>

<div id="remoteWebAppDiv"></div>

Also as @Mihai T mention, you have problems with the usage of indexOf:

  1. You need to check of the index is greater than -1 because this is the output of this function for string which no included in another string.
  2. The || need to be between sentences but not as argument in indexOf function.
Mosh Feu
  • 28,354
  • 16
  • 88
  • 135
  • i guess that `if` should append an input only if the title contains those strings in the `if` condition. Your answer adds 4 inputs even if you don't have those strings in the title. Plus i guess you should use `text()` instead of `html()` when looking for ...well...text :) – Mihai T May 02 '18 at 11:09
  • You are right. I didn't write code for copy / paste, just to explain the point. OP need to understand it and implement it in his code. Also, `html()` vs `text()` the first is winning - https://stackoverflow.com/a/18418270/863110 but thanks for your comment :) – Mosh Feu May 02 '18 at 11:12