-1

in reference to

Is an empty href valid?

in my case i was using an empty href and it was causing documents.ready to fire again. Here is my html:

<li><a onclick="numberOfmonthsToloadInDatabase(this)" href="" id="12Monat">12 Monat</a></li>

and when i removed it then it did not fire document.ready. I don't understand this behaviour, any explanation would be very helpful. i couldn't post it in the comments as i do not have enough points to add a comment on any post. Thanks.

Community
  • 1
  • 1
Ahmad Karim
  • 459
  • 1
  • 6
  • 17
  • 6
    Clicking a link with an empty href attribute will reload the page. – j08691 Mar 17 '17 at 15:00
  • You can use `e.preventDefault()` (inside the `numberOfmonthsToloadInDatabase` function), to prevent the page reload. – Ramiz Wachtler Mar 17 '17 at 15:02
  • change your href="" to href="javascript:void(0);" if you don't want page reload – gaetanoM Mar 17 '17 at 15:07
  • related: http://stackoverflow.com/questions/134845/which-href-value-should-i-use-for-javascript-links-or-javascriptvoid0 – Kevin B Mar 17 '17 at 15:30
  • may i ask why is this question downvoted? as i mentioned the source location and the reason for posting the question was that i couldn't ask anything in the comments(don't have that privilege). is there any thing i could do so that the post is no longer downvoted ? – Ahmad Karim Apr 04 '17 at 14:25

2 Answers2

1

From your example I have to question, why are you using a link tag? Since you only want the onclick event to fire you should use a span and eventually use css cursor:pointer; to give indication that it is clicable.

function numberOfmonthsToloadInDatabase(evt) {
  alert("your clicked");
}
li span {
  cursor:pointer;
}
<li><span onclick="numberOfmonthsToloadInDatabase(this)" id="12Monat">12 Monat</span></li>

This way you prevent the default link behavior for when there is no URL specified. You have less work this way instead of using javascript preventDefault() to prevent the link from executing it's default behavior.

Mario Andrade
  • 505
  • 3
  • 21
1

As other people have told you href causes page to reload, so you got the option to use href="javascript:void(0);" or href="#" in order to avoid the page to reload, if you want to keep the underlined link style you get when using href tag.

e.preventDefault() in the method won't work, because the parameter passed to the function isn't an event. It's the link element itself.

AFAIU you're trying to create some months option for your users. A more modern aproach would be to use data-something attributes. You could use them like this:

function numberOfmonthsToloadInDatabase(link) {
    console.log(link.dataset.months);
}
<li>
    <a onclick='numberOfmonthsToloadInDatabase(this)' href='#' data-months='12'>
       12 Monat
    </a>
</li>
<li>
    <a onclick='numberOfmonthsToloadInDatabase(this)' href='#' data-months='10'>
       10 Monat
    </a>
</li>
Nelson Teixeira
  • 6,297
  • 5
  • 36
  • 73