How to get href value, in such situation?
I'm using jQuery and pure JS on my page;
ololoText
<script type="text/javascript">
function asAjaxCall(elem) {
var link = elem.getThatLinkSomehow(); //how to get "href"??
$.ajax({
type: "Get",
url: link,
success: function (response) {
$("#controlsContainer").empty();
$("#controlsContainer").append(response);
},
error: function (e) {
alert('Error: ' + e);
}
});
}
</script>
It is stored in elem.href.
But you should not use <a> in this case - after your callback is done or if user tries middle-button click new page with useless address will be opened. Use simple <div> instead. Or at least stop event propagation.
In Jquery you can use .attr() like so:
$(elem).attr("href");
or in plain javascript you can use .getAttribute():
elem.getAttribute('href')
FIDDLE
Related
I'm using below code. This is bootstrap 3 delete conformation message.
$(document).ready(function(){
$('a.btnDelete').on('click', function (e) {
e.preventDefault();
var id = $(this).closest('div').data('id');
$('#myModal').data('id', id).modal('show');
});
$('#btnDelteYes').click(function () {
var id = $('#myModal').data('id');
var dataString = 'id='+ id ;
$('[data-id=' + id + ']').parent().remove();
$('#myModal').modal('hide');
//ajax
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html)
{
//$(".fav-count").html(html);
$("#output").html(html);
}
});
//ajax ends
});
});
This is the trigger element that I'm using
<div data-id="MYID"><a class="btnDelete" href="#">Delete</a></div>
And I'm using the same HTML element dynamically to trigger delete and it doesn't work.
Can someone point me the correct way to do it?
You have to use event delegation
$(document).on("click" , '#btnDelteYes' ,function () {
Pretty much: bind the click higher up to something that exists when the script is run, and when that something is clicked, tell it to pass the click event to the #btnDelteYes element instead
I cant understand what exactly you are doing on your code due to missing information, but the answer is: you should use event delegation on the dynamically inserted content
you can try
$('[data-id=MYID]').on('click','.btnDelteYes',function({
e.preventDefault();
var id = $(this).closest('div').data('id');
$('#myModal').data('id', id).modal('show');
});
here <div data-id="MYID"> should be a hard coded html content and The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.
I have a list in HTML which looks like
<a onclick="open_file()" id="3.txt">3.txt</a>
My open_file() function is looking this
function open_file() {
$("a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
}
The problem is function finally loads data into all fields(text_form and f_name) only after two clicks on such link. It works even if I at first click on one file, then click on another and it loads. Is there any way to fix this?
What you're currently doing is adding an onclick event to a link that calls a function that adds another onclick event via jQuery.
Remove the onclick property and the open_file() function wrapper so that jQuery adds the event as you intended.
You do not need onclick="open_file()" this:
<div id='linkstofiles'>
<a id="3.txt">3.txt</a>
//other links go here
</div>
$("#linkstofiles a").click(function (event) {
var file_name = event.target.id;
$("#f_name").val(file_name);
$.ajax({
url: "docs/" + file_name,
dataType: "text",
success: function (data) {
$("#text_form").val(data);
$('#text_form').removeAttr('readonly');
$('#delete_button').removeAttr('disabled');
$('#save_button').removeAttr('disabled');
}
})
});
You don't need to bind a click event again in the function when you have onclick in your html.
Also for $ is not defined, you need to put jquery library in the head.
I have list of tables,
<table id="<%#DataBinder.Eval(Container.DataItem, "Certificate")%>" class="tbl_evenSearchResultRow" onmouseover="this.className='ResultGridRowSeleted'" onmouseout="this.className='tbl_evenSearchResultRow'" onclick="return SynopsisWindowOpen(this)">
onclick of each i use next function:
function SynopsisWindowOpen(obj) {
var title = $(obj).find("strong[name='title']").html();
var isParentools = 0;
if (window.location.href.indexOf('recent_releases.aspx') > -1)
isParentools = 1;
var url = "/ratings/Synopsis.aspx?logoonly=1&Certificate=" + obj.id + "&Title=" + encodeURIComponent(title) + "&parentools=" + isParentools;
$("#ratingModal").on("show.bs.modal", function (e) {
$.ajax({
url: url,
cache: false,
dataType: "html",
success: function (data) {
$("#ratingModal").find(".modal-body").html(data);
}
});
});
$("#ratingModal").on("hide.bs.modal", function (e) {
$(this).find(".modal-body").html('');
});
$("#ratingModal").modal('show');
return false;
}
By url i render body of modal : i get certificate from request.query and according to it render body
LoadSynopsisContent(Request.QueryString["Certificate"], Request.QueryString["parentools"]);
Problem : when i click at first - everything seems to be good, on second click in modal body firstly rendered body of first click and then of second click. And so on.
I don't know where is problem.
Firstly i use jquery load function, but then i change to simple ajax call with disabled caching.
Move the all event bindings to outside of the function and everything should work fine.
Thus, these parts should not be inside the function:
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
Here is one way you could organize your code:
var url; //a global variable ... not a good idea though
function SynopsisWindowOpen(obj) {
....
url = .....
}
$(function() {
$("#ratingModal").on("show.bs.modal", ....);
$("#ratingModal").on("hide.bs.modal", ....);
});
However, the way would be to not use inline JavaScript but to take advantage of the power of jQuery to separate structure from behavior.
UPDATE
Instead of using a global variable url you can store the new url in a data attribute of the modal. Then you can get it from there when the modal opens.
In the function:
//calculate the url
var url = .....
//store the url in the modal
$('#ratingModal").data('table-url', url);
In the modal event handler:
$("#ratingModal").on("show.bs.modal", function(e) {
//retrieve the url from the modal
var url = $(this).data('table-url');
//use the url
$.ajax({ url: url, .... }):
});
I'm making an Android Web Application, and I'm using JQuery Mobile. My question is:
Is it possible to change the onClick event's parameter using Javascript?
I will be using Ajax post request to get the primary key attribute of my row from the database. And after getting the primary key, I want to set the parameter of the input button's onClick event.
Here's the structure of my program:
<script>
$.ajax({
type:"POST",
url:"url.php",
dataType:"json",
data:{input:input},
success: function (result)
{
//Set my input button's onclick
}
});
</script>
success: function (result)
{
$("#" + result).click(function () {
// do something
});
}
use this
yourelement.addEventListener('click', yourfunction);
or this
yourelement.addEventListener('click', function() {
//your code here
});
or in jquery
$('yourelement').click(yourfunction)
You can do like this instead:
$('#element').click({id: id}, handleClick);
If, for example, the click handler is somewhere outside the scope:
function clickHandler(ev) {
var id = ev.data.id;
// use id
}
Hi I asked before on how to load a div's content (A url) by clicking a button and not on page load before and I got this code as an answer:
<script type="text/javascript">
function toggleDiv(id){
if ($('#' + id).html() == '') {
$.ajax({
url: 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success: function(data) {
$('#' + id).html(data);
},
error: function() {
$('#' + id).html('The resource could not be loaded');
}
});
}
$('#' + id).toggle(); // Toggle div visibility
}
</script>
Show/Hide Value
<div id="a" style="display:none"></div>
First of all it doesn't work correctly and always show "The resource could not be loaded" if you put a txt link like (http://knowpersia.com/a.txt) it doesn't work either.
Secondly the Show/Hide Value link uses a href=# and onclick system to work. When I use it on my website it gets back to the homepage when I click it. Is there a way to change it to something like:
Show/Hide Value
Thanks
You have to pass an id to the toggleDiv() function, and you're passing a collection of objects -> toggleDiv('a') // Nop.
Also, if you're using jQuery, I suggest you get rid of that ugly inline code. Then, you can pass jQuery objects into your function:
Show/Hide Value
<div id="content"></div>
.
var toggleDiv = function($el) {
if ($el.empty()) { // You can just use `empty()`
$.ajax({
url : 'api.microsofttranslator.com/V2/Ajax.svc/Translate?appId=SOMETHING&from=en&to=de&text=Hello', // your url to microsoft translator
success : function (data) {
$el.html(data);
},
error : function () {
$el.html('The resource could not be loaded');
}
});
}
$el.toggle(); // Toggle div visibility
};
$('#link').click(function(){ toggleDiv($('#content')); });