Search code examples
javascriptjquerydomdhtmlcommand-line-interface

Javascript function results in HTML page reload: why?


Newbie question...

The objective:

  • I intend to have an HTML text input field as a kind of command line input.

  • An unordered HTML list shows the 5 most recent commands. Clicking on one of the last commands in this list should populate the command line input text field with the respective command (in order to re-execute or modify it).

  • An unordered HTML list contains a result set. Clicking on an ID in this list should bring the respective ID into the command line input text field.

In HTML (DHTML): Works as expected: when clicking on the the link the command line input text field is populated with a recent command.

<li><a href="#" id="last_cmd_01" onclick="document.getElementById('cli_input').value = document.getElementById('last_cmd_01').firstChild.nodeValue;document.getElementById('cli_input').focus()">here would be one of the recent commands</a></li>

In Javascript file: Doesn't work as expected: when clicking on the the link the command-line-input-text-field gets populated with the respective value (as it should), BUT then it seems like the full HTML page is being reloaded, the text input field and all dynamically populated lists become empty.

    function exec_cmd(cli_input_str) {
// a lot of code ...
// the code that should provide similar behavior as onclick=... in the DHTML example
$('.spa_id_href').click(function(){document.getElementById('cli_input').value = document.getElementById('cli_input').value + this.firstChild.nodeValue;});
}

Now the Question: Besides a potential Javascript (syntax) error, what could cause the browser to reload the page?


Solution

  • Change

    $('.spa_id_href').click(function(){...
    

    to

    $('.spa_id_href').click(function(evt){...//notice the evt param
    

    and in the function, call

    evt.preventDefault();