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
}
Related
I've got a while loop to build a table of data and onclick I want to call a function but when I the function is called it's not getting the info from the onclick being passed.
HTML:
echo "<td width='25%' align='center'><a href='javascript:void(0)' id='{$row['id']}' class='{$row['status']}' onclick='hello()'> {$row['status']} </a></td>";
JS:
//onclick function
function hello()
{
// Get the ID of the button that was clicked on
var id_of_status_to_update = $(this).attr("id");
var status_to_be_updated = $(this).attr("class");
var varData = 'id=' + id_of_status_to_update + '&UserStatus=' +
status_to_be_updated;
console.log(varData);
// Make an AJAX request
$.ajax({
url: "php/processor.php", //This is the page where you will handle your SQL insert
type: "POST",
data: varData, //The data your sending to processor.php
async: false,
success: function(){
// location.reload();
alert("Hello Function");
},
error: function(){
alert("There was a problem, please try again or contact the admin for assistance.");
}
});
};
but when I check the console log I'm seeing the id and userstatus are undefined instead of what should be the passed attributes of id and class. Any help? I know the function is being called properly because I'm getting the success alert.
To fix your undefined issue, remove the ancient onclick method, and use a proper jquery .click event handler, and then your use of $(this) will work properly.
First adjust your html build to this:
echo "<td width='25%' align='center'><a href='#' id='{$row['id']}' class='clicker {$row['status']}'> {$row['status']} </a></td>";
Then adjust the javascript a bit to this:
$(document).ready(function() {
$(".clicker").click(function(e){
e.preventDefault(); // new line to stop the anchor click default behavior
var id_of_status_to_update = $(this).attr("id");
var status_to_be_updated = $(this).attr("class");
// ... the rest you had is fine as is ...
});
});
This attaches a click event handler to the class if "clicker", so it applies to all buttons with that class.
Use this instead:
$('#id').on('click', function(){
//Do something
//console.log(this)
})
Of course you would need to pass the element a fixed id, alternatively you can use $('.class') and pass it a class instead!
because the this inside function hello points to the window object. you can pass an event parameter to the hello function like onclick="hello(event)" and inside this function, you can use event.target.getAttribute('id') to access this element's id, don't forget to change the function definition function hello(){...} to function hello(event){...}
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.
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
I have some jquery that looks like this,
$('.career_select .selectitems').click(function(){
var selectedCareer = $(this).attr('title');
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
}
});
});
My problem is that if the user keeps clicking then the .hfeed keeps getting data appended to it. How can I limit it so that it can only be clicked once?
Use the one function:
Attach a handler to an event for the elements. The handler is executed at most once per element
If you wanted the element to only be clicked once and then be re-enabled once the request finishes, you could:
A) Keep a state variable that updates if a request is currently in progress and exits at the top of the event if it is.
B) Use one, put your code inside a function, and rebind upon completion of request.
The second option would look like this:
function myClickEvent() {
var selectedCareer = $(this).attr('title');
var that = this;
$.ajax({
type: 'POST',
url: '/roadmap/step_two',
data: 'career_choice='+selectedCareer+"&ajax=true&submit_career=Next",
success: function(html){
$('.hfeed').append(html);
$('#grade_choice').SelectCustomizer();
},
complete: function() {
$(that).one('click', myClickEvent);
}
});
}
$('.career_select .selectitems').one('click', myClickEvent);
You can either use a global variable like
var added = false;
$('.career_select .selectitems').click(function(){
if(!added) {
// previous code here
added = true;
}
});
or use .one("click", function () { ... }) instead of the previous click function to execute the handler at most once per element. See http://api.jquery.com/one/ for more details.