Calling a function on click via JavaScript/jQuery on button clicks - javascript

Here's my JavaScript:
function privacy(current)
{
var $this = $(current),
$scope = $this.closest('.uk-button-group'),
value = $this.val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($this);
alert('A button has been clicked!');
});
});
And here's my HTML:
<div class="uk-button-group">
<button class="uk-button" id="privacy1" value="1">Public</button>
<button class="uk-button" id="privacy2" value="2">Protected</button>
<button class="uk-button" id="privacy3" value="3">Private</button>
</div>
When I click on one of the buttons, it should call the privacy function and alert me that a button has been clicked but it doesn't. Can anyone help me and show me what's wrong with my code? Much appreciated thank you!

You do not have any identifier $this, you probably need to change $this with $(this) or simply this to pass the event source object
privacy(this);
OR
privacy($(this));

Replace this :-
privacy(this);

Try here: http://jsfiddle.net/pqdgT/
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy($(this));
alert('A button has been clicked!');
});
});

Here is your working code
And here is the refined code
function privacy(current)
{
var btn = $(current),
scope = $(btn).closest('.uk-button-group'),
value = $(btn).val();
$.ajax({
type: 'post',
url: '/privacy.php',
data: {key: value },
success: function () {
}
});
}
$(function() {
$("#privacy1, #privacy2, #privacy3").click(function() {
privacy(this);
alert('A button has been clicked!');
});
});
Please avoid reserved keywords while naming variables - Here is the list of reserved words
And be careful with your syntax and feel free to use the browser console.

Related

jQuery Click Event CheckBox Changed Ajax Call

I have three checkboxes that who have checked/unchecked values populated from a model. I'm using an Ajax post on button click event to call controller actions for each checkbox changed event in order to update the DB.
Here is the code for one of the checkboxes (apart from the selector ID, they are all the same):
$(document).ready(function () {
//document.getElementById('UpdateButton').onclick = function () {
$("UpdateButton").click = function () {
$('#NatAm').change(function () {
// if ($('#NatAm').is(':checked')) {
$.ajax({
//url: '#Url.Action("NativeUpdate", "Transactions")',
url: '/Transactions/NativeUpdate',
//data: { isNativeUp: true },
type: 'POST',
dataType: "json"
});
//}
});
Edit (HTML/View Code):
#Html.CheckBox("NatAm", (bool)#ViewBag.NativeAm)
<input name="UpdateButton" id="UpdateButton" type="submit" value="Update" style="margin-left: 15px; margin-top: 3px;" class="btn btn-success" />
I cannot get this to work. Before adding the button, the ajax post was working fine. Thank you for your help!
Your click handler isn't right. You need to pass in the id of the button and use jQuery click handler. You also need not to nest the handlers:
$(document).ready(function() {
$("#UpdateButton").click(update);
$('#NatAm').change(update);
});
function update() {
$.ajax({
url: '/Transactions/NativeUpdate',
type: 'POST',
dataType: 'json'
});
}
JSFiddle Demo: https://jsfiddle.net/vLzwuwdo/
You're telling JQuery to look for 'UpdateButton' tags which in your case does not exist. You're missing the # which indicates an ID in your button.
Try this
$(document).ready(function () {
//document.getElementById('UpdateButton').onclick = function () {
$("#UpdateButton").click(function () {
$('#NatAm').change(function () {
// if ($('#NatAm').is(':checked')) {
$.ajax({
//url: '#Url.Action("NativeUpdate", "Transactions")',
url: '/Transactions/NativeUpdate',
//data: { isNativeUp: true },
type: 'POST',
dataType: "json"
});
//}
}));
id should be unique in same document (NatAm and UpdateButton), replace the duplicate ones by global classes will solve the first problem.
You should not define event inside another since every time you trigger the first it will create new event for the element, in your case every time you click new change event will be created and attached to the first element with NatAm.
Hope this helps.

Passing a variable from onclick event to a fucntion

Been scratching my head all night on this issue. Im still learning Jquery and just starting with ajax. I am trying to implement something similar to this https://codeontime.com/print/learn/rest/jquery/crud-create-read-update-delete.
I have a simple edit button in which i stored the ID in in a data-ID attribute. For example below is what my button would look like.
<button class='edit_button btn btn-info btn-circle btn-xs' type='button' value='Edit' data-ID='1'></button>
What im trying to accomplish is to pass the data-ID value into a variable and pass it into my function. Here the listener I put in place to capture the ID and its working fine:
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails();
});
The problem I have is that I need to pass the button_ID variable onlick to my variable function and dosent seem to be working correctly. I feel like im missing something there.
Below is my full script:
var IncidentManager = {
// Returns the url of the application server of a demo web app.
basePath: function () { return '../../../../_vti_bin/listData.svc'; },
// This function will loadup the data into the modal form,
showIncidentDetails: function (Button_ID) {
if (Button_ID == null) return;
alert(Button_ID);
$.ajax({
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+ID+')',
cache: false,
dataType: 'json',
success: function (data) {
$.each(data, function (index, incident) {
$('#Description').attr('value', incident.Description);
$('#Incident').attr('value', incident.Incident);
$('#état').attr('value', incident.ÉtatValue);
$('#Priorité').attr('value', incident.PrioritéValue);
$('#DateDeDébut').attr('value', incident.DateDeDébut);
$('#DateDeFin').attr('value', incident.DateDeFin);
});
}
});
},
};
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails();
});
});
Any help is appreciated.
You just pass the variable to the function - programming doesn't work by just having variables named similarly, hence what you want is:
$(document).ready(function () {
$(".edit_button").click(function() {
var Button_ID = $(this).attr("data-ID");
IncidentManager.showIncidentDetails(Button_ID);
});
});
also this bit:
....
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+ID+')',
You probably meant
url: '../../../../_vti_bin/listData.svc/GDI_Tableau_de_bord('+Button_ID+')',
as there is no ID variable in your code.
Incidentally, you can use the jQuery .data function instead of .attr:
var Button_ID = $(this).data("id");
However, note that .data will treat your data attribute as lowercase.

How to execute javascript after after ajax call inside a on() method

I am trying to execute a $.ajax() inside a function called by a .on() method, so that in the newlly attached data, it would be possible to execute a script on a .click() event - I know this is probably something similar to other requests, but i have tryed and tryed, and can't find what is wrong withthe code...
The ajax function is called by a change in a select, and 'this' is passed as a variable to the function.
The data is correctly inserted inside the targeted div, but it seems that there is no bubbling, because no javascript runs from it (but runs outside of targeted div).
I used .on() so it would bubble up, and update the DOM, and I dont see wath I am doing wrong with it...
The ajax is called with:
$("body").on("change", "[data-project-ajaxSelect='true']", {select: this},Select_AjaxCall);
function Select_AjaxCall(event) {
$select = event.data.select;
if (typeof $select.data === "undefined" || $select.data === null) {
var $select = $(this);
}
var options = {
url: $select.attr("data-project-action"),
type: $select.attr("data-project-method"),
target: $select.attr("data-target"),
data: { guid: $select.val() }
}
$.ajax({
type: options.type,
url: options.url,
data: options.data,
dataType: "html",
success: function (data) {
console.log(data)
$(options.target).html(data);
}
});
return false;
};
From that code, a button is added with the following View code:
<button id=#Model.Guid
class="button default cycle-button"
data-toggle="modal"
data-target="#modalDiv"
data-backdrop="static"
data-keyboard="true"
data-modal-modal="true"
data-modal-controller="Fin_Movement_Type"
data-modal-action="Create"
data-modal-var-guid=#Model.Guid
data-modal-var-modal=#ViewBag._modal>
<span class="icon mif-plus"></span>
</button>
And by cicking on this button, the following .click() event should be fired...
$("[data-modal-modal='true']").click(function () { ... }
But it isn't.
Please Help me find where is the bug with my code... thank you.
Edit
It seems you need live functionality that has been removed from jQuery, but you can use on instead of that, this way:
$(function () {
$(document).on("click","[data-modal-modal='true']", function () {
alert('clicked');
});
});
Original
You can add your code at the end of your success method:
success: function (data) {
console.log(data);
$(options.target).html(data);
$("[data-modal-modal='true']").on("click", function() {
alert('clicked!');
});
}
Also you can load the button with suitable script in onclick attribute, for example:
<button id="#Model.Guid"
...
onclick="alert('clicked!');">
<span class="icon mif-plus"></span>
</button>

Javascript onclick change button text for a few seconds

Trying to change the text on a button to processing for a few seconds when it is click
<div id="send"></div>
<button id="button">Send</button>
<script>
$(document).on("click", "#button", function() {
var Path = $('#send').html();
var success = function() { alert("Successful"); };
var error = function(message) { alert("Oopsie! " + message); };
</script>
You're close, you just need to do this $('#button').html("Processing");
Then in the success and error functions, you'll probably want to modify the button text to something else so that it no longer displays "Processing".
This is what you are probably looking for:
$(document).on("click", "#button", function() {
var defaultBtnValue = $('#send').html();
$('#send').html("Processing...");
$.ajax({
url: your_url,
type: "GET",
success: function() {
alert("Successful");
},
error: function(message) {
alert("Oopsie! " + message);
},
complete: function() {
$('#send').html(defaultBtnValue);
}
});
});
I'm assuming you wan't this "Processing" to show while something is.. well, processing, like doing an ajax call (this may be a setTimeout function as well). Good practice is to first save the default value of the button and make sure to reset it once an action is complete (succes or not) in case something goes wrong.

jQuery methods in $.ajax success handler don't work

I have a function:
$(".delete").click(function() {
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$(this).parent().parent().remove();
alert("hi");
}
});
});​
I have a problem when I delete the parent object. It just does not disappear. I tried to hide - did not help.
Alert is called normal.
How to solve?
Sorry for bad English.
You're inside another function with another this value by default. Pass the this value from the outer function with the $.ajax function as follows:
$.ajax({
context: this,
...
Because the this in the ajax success callback function is different from the click callback function. You could cache it to a local variable or use the $.ajax()'s context option.
$(".delete").click(function () {
var $this = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $this.attr("title"),
success: function () {
$this.parent().parent().remove();
alert("hi");
}
});
});
Have you tried setting the context: this, parameter in the ajax function.
When the success handler fires, the value of this won't be the same as it was before hand.
See here fore more: http://api.jquery.com/jQuery.ajax/
Try this:
$(".delete").click(function() {
$object = $(this);
$.ajax({
url: "ServerHandler.ashx",
data: "mode=delete&item=" + $(this).attr("title"),
success: function() {
$object.parent().parent().remove();
alert("hi");
}
});
});​

Categories