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){...}
Related
I got this javascript code to solve in a manner to use inner function but not able to use it. Please try to help me to use inner functions or do i need to modify this. I want to use inner functions on click on html element such as view and remove respectively;
var App = function(){
var url = 'api';
function view(event) {
var id = '??'; //here i have to receive id of the element(data-id)
$.ajax({
url: url + '/view/' +id,
data: data
}).done( function (data){
});
}
function remove(event) {
var id = '??'; //please determine the id
$.ajax({
url: url + '/remove/' + id ,
data: data
}).done( function (data){
});
}
function initialize() {
//
}
return {
//
}
}();
Try doing this:
For id you can do one thing, Save the id in data-id attribute of the element on which you want onClick listener and access it using Event-Delegation in javascript.
To use the inner method you don't need to return anything. Just do it this way :
var App = function(){
var url = 'api';
function view(event) {
//access the id attribute of event.target
}
function remove(event) {
//same
}
function initialize() {
//
}
App.view = view;
App.remove = remove;
};
//EDIT : instead of making it self-invoking, call the app function
App();
//to access it outside:
App.view("your_parameter");
App.remove("your_parameter");
EDIT : Instead of making it self-invoking, call the app function
Well it's pretty simple, use the $("#caller").click() function of our beloved
jQuery
Then inside the .click() function you can easily retrieve your id
Here you can find more on the .click() function
It will be something like this
$( "#view" ).click(function() {
id = document.getElementById("id").id;
//Here paste the code of your view function
});
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 am having some trouble trying to store the url parameters of some dynamic links that I created with an ajax post response. The ajax post is working correctly and the name and subgenre vars are being properly filled from the ajax response. Now what I would like to happen is that a user clicks on one of the generated urls, the parameters inside of the urls, i.e. subgenre="blah", are going to be sent to a database and stored. The problem I am having is that a standard event click function will not work inside or outside of the document ready function.
$(document).ready(function() {
$.each(data, function() {
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
});
I then created an onclick function, as below, but I can not use the "this" query because it is outside of the document scope. I had to put the onclick function outside of the document ready function or else it would not work.
function artistGen(){
alert('dfdsf');
};
What am I missing here or what am I doing wrong?
You can pass these in the onclick function when you make each element.
$(document).ready(function() {
$.each(data, function() {
artist = this.name;
$('#artist-suggestions').append('<li>' + this.name + this.new + '</li>');
});
})
;
function artistGen(Blah1, Blah2){
saveData(Blah1, Blah2);
alert('dfdsf');
};
In jQuery for dynamic elements you can use the click event in this way
$('#artist-suggestions li').on('click', 'a', function() {
// do something
});
or you can continue with the way you did, by using a function but just add a parameter to that function
like
function artistGen(Artist){
// do something
};
You need to remove the artistGen() function from the scope of the .load()
$(window).load(function(){
$('#artist-suggestions').append('<li>jim new</li>');
});
function artistGen(){
alert('dfdsf');
}
JSFIDDLE DEMO
That's just how it is a function called in those event attributes have to be defined globally(or defined right there) not in any wrapper function. A better solution would be to attach event handlers.
$(document).ready(function() {
function artistGen(){
alert(this.href);
};
$.each(data, function() {
var $li = $('<li>' + this.name + this.new + '</li>');
$li.find('a').on('click', artistGen);
$('#artist-suggestions').append($li)
});
});
I'm getting this error and it is originating from jquery framework.
When i try to load a select list on document ready i get this error.
I can't seem to find why i'm getting this error.
It works for the change event, but i'm getting the error when trying to execute the function manually.
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined -> jquery-2.1.1.js:7300
Here is the code
$(document).ready(function() {
$("#CourseSelect").change(loadTeachers);
loadTeachers();
});
function loadTeachers() {
$.ajax({
type: 'GET',
url: '/Manage/getTeachers/' + $(this).val(),
dataType: 'json',
cache: false,
success:function(data) {
$('#TeacherSelect').get(0).options.length = 0;
$.each(data, function(i, teacher) {
var option = $('<option />');
option.val(teacher.employeeId);
option.text(teacher.name);
$('#TeacherSelect').append(option);
});
},
error: function() {
alert("Error while getting results");
}
});
}
When you call loadTeachers() on DOMReady the context of this will not be the #CourseSelect element.
You can fix this by triggering a change() event on the #CourseSelect element on load of the DOM:
$("#CourseSelect").change(loadTeachers).change(); // or .trigger('change');
Alternatively can use $.proxy to change the context the function runs under:
$("#CourseSelect").change(loadTeachers);
$.proxy(loadTeachers, $('#CourseSelect'))();
Or the vanilla JS equivalent of the above, bind():
$("#CourseSelect").change(loadTeachers);
loadTeachers.bind($('#CourseSelect'));
I had the same problem, I was trying to listen the change on some select and actually the problem was I was using the event instead of the event.target which is the select object.
INCORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el).val());
});
CORRECT :
$(document).on('change', $("select"), function(el) {
console.log($(el.target).val());
});
This Works For me !!!
Call a Function without Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers();
});
Call a Function with Parameter
$("#CourseSelect").change(function(e1) {
loadTeachers($(e1.target).val());
});
It causes the error when you access $(this).val() when it called by change event this points to the invoker i.e. CourseSelect so it is working and and will get the value of CourseSelect. but when you manually call it this points to document. so either you will have to pass the CourseSelect object or access directly like $("#CourseSelect").val() instead of $(this).val().
It fails "when trying to execute the function manually" because you have a different 'this'. This will refer not to the thing you have in mind when invoking the method manually, but something else, probably the window object, or whatever context object you have when invoking manually.
your $(this).val() has no scope in your ajax call, because its not in change event function scope
May be you implemented that ajax call in your change event itself first, in that case it works fine.
but when u created a function and calling that funciton in change event, scope for $(this).val() is not valid.
simply get the value using id selector instead of
$(#CourseSelect).val()
whole code should be like this:
$(document).ready(function ()
{
$("#CourseSelect").change(loadTeachers);
loadTeachers();
});
function loadTeachers()
{
$.ajax({ type:'GET', url:'/Manage/getTeachers/' + $(#CourseSelect).val(), dataType:'json', cache:false,
success:function(data)
{
$('#TeacherSelect').get(0).options.length = 0;
$.each(data, function(i, teacher)
{
var option = $('<option />');
option.val(teacher.employeeId);
option.text(teacher.name);
$('#TeacherSelect').append(option);
});
}, error:function(){ alert("Error while getting results"); }
});
}
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
}