I am relatively new to Javascript/Ajax.
When the user clicks on certain urls, I wish to handle the click entirely with Javascript/jquery.
<a class="row_edit" href="/sales_item/edit/{{ item.id }}"></a>
What I have done is to add a javascript to this html file:
$(document).ready(function () {
$(".row_edit").click(row_edit);
});
function row_edit() {
var url = $(this).attr("href") + "/";
...
}
This works pretty well, every time I click on row_edit, the javascript is firing and doing the partial site loading for me. But there are cases that it seems the actual link would fire instead (I see the partial site loaded as the entire screen). It seems there is a race condition.
I think the best way to make sure only the javascript is firing would be to change the content of the href
to #
. That way I make sure the url by itself won't go anyway and only my javascript is firing. However how would I get my url
value in the row_edit()
then?
Maybe I am taking a wrong approach here though. How do you guys solve this problem?
I am not sure about the intent of performing the redirection using javascript instead of href. Anyways, one of the approaches is here...
If you are implementing for modern browsers which support "data-" (HTML5) then you can use such attributes
<a class="row_edit" data-url="/sales_item/edit/{{ item.id }}" href="#"></a>
and modify the javascript to get the appropriate attribute value
var url = $(this).attr("data-url") + "/";
<a href="#"> click me </a>
'#' for blocking clcik
through jquery block the default event.
add your new event handler.
Refer Link(jquery):-
To make sure only the javascript is firing (Cancel the default action (navigation) of the click), you have to call the preventDefault();
in the click handler.
Ex:
$(document).ready(function () {
$(".row_edit").click(row_edit);
});
function row_edit(event) {
var url = $(this).attr("href") + "/";
...
event.preventDefault();
}