Javascript display innerHTML on the same page

495 Views Asked by At

So I am testing the permute function of D3.js and it works just fine. The issue I am having is to display the results on the same page using innerHTML, it always reloads in order to display. I am probably missing a detail here, can someone help?

permute.html:

<html>
 <head>
 <meta charset="UTF-8">
 <script language="JavaScript">
 function* permute(keys) {
    var size = keys.length,
        c = Array(size).fill(0),
        i = 1;
    yield keys;
    while (i < size) {
        if (c[i] < i) {
            var k = i % 2 && c[i];
            [keys[i], keys[k]] = [keys[k], keys[i]];
            c[i]++;
            i = 1;
      yield keys;
    } else {
      c[i++] = 0;
    }
  }
}

function showPermutations(){
    var input = document.getElementById("keys").value;
    document.getElementById('results').innerHTML=input;
    for (var words of permute(input.split(/\s+/))) {
        document.write(words.join(''));
        document.write("<br>");
    }
}
</script>

<body>
  <form>
    <label><b>Keywords</b></label></br>
    <input type="text" id="keys" name="keys"></br>
  </form>
    </br>
<input type="submit" value="Permute" onclick="showPermutations();"></br>
<p><span id='results'></span></p>
</head>
</body>
</html>

Some of you pointed out the issue is caused by the submit button, but in this other example, using submit, the JS works just fine on the same page:

test.html

<html>
  <head lang="en">
  <meta charset="UTF-8">
  <script language="JavaScript">
    function showInput() {
        document.getElementById('display').innerHTML = 
                    document.getElementById("user_input").value;
    }
  </script>

  </head>
<body>

  <form>
    <label><b>Enter a Message</b></label>
    <input type="text" name="message" id="user_input">
  </form>

  <input type="submit" onclick="showInput();"><br/>
  <label>Your input: </label>
  <p><span id='display'></span></p>
</body>
</html>
1

There are 1 best solutions below

2
Emilio Grisolía On

When you click the submit button, the page will automatically reload. You should prevent that by calling the preventDefault method of the event object that is passed to the event handler, in your case, that handler would be showPermutations.

Make that function receive one argument, called e, ev, or event (as it is normally called) and inside it, execute the preventDefault method before anything else.

function showPermutations(e){
   e.preventDefault();
   ...
}

Or don't use a submit button.