1

I'm trying to clean the URLs of elements and every thing is working, but the onclick event fired directly on the page load but not when I click. How can I fix this?

HTML:

<a class="button" href="http://192.168.1.99:8888/propertyturkey/admin/clients/index/today_calls/?status=3&amp;sales=70&amp;tagged=1&amp;clientName=turkey&amp;nextCall=turkey&amp;clientEmail=sdfgsdfg">Today call list</a>
<input type="reset" class="reset" id="reset" value="Reset">

JS:

var buttons = document.querySelectorAll('.button');
var reset = document.querySelector('.reset');

function forEach(array, action) {
  for (var i = 0; i < array.length; i++) {
    action(array[i])
  };
}

function clear_url_parameters(element) {

  if (!element)
    return false;
  var element_url = element.getAttribute('href');

  var split_url = element_url.split("?");

  var queries = split_url[1].split("&");

  var new_queries = [];

  for (var i = 0; i < queries.length; i++) {
    query = queries[i].split("=");
    new_queries.push(query[0] + "=");
  }

  cleared_url = split_url[0] + new_queries.join('');

  element.setAttribute('href', cleared_url);

}

reset.addEventListener('click', forEach(buttons, clear_url_parameters));

Demo on jsfiddle

2 Answers 2

1

You are passing the result of executing the function forEach to your event listener.

Try this:

reset.addEventListener('click', function () { forEach(buttons, clear_url_parameters); } );
Sign up to request clarification or add additional context in comments.

Comments

0

change

reset.addEventListener('click', forEach(buttons, clear_url_parameters));

to

reset.addEventListener('click', function(){
    forEach(buttons, clear_url_parameters)
});

Because the parameter you passed to addEventListener has already been called.

1 Comment

Thanks to your help and explanation, I really appreciate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.