I have a form that has these buttons in footer
<button type="button" class="btn btn-warning redirect store-submit">Add and redirect</button>
<button type="submit" class="btn btn-success store-submit">Just add</button>
Although form is not submitted by these. They are used to trigger jQuery event
$("button").click(function(e){
if($(this).hasClass('store-submit')){
e.preventDefault();
var form_action = $("#add-modal").find("form").attr("action");
var data = $("#add-modal").find("textarea[name='data']").val();
var token = $('meta[name="csrf-token"]').attr('content');
var type = {{$user->type}};
$.ajax({
dataType: 'json',
type:'POST',
url: form_action,
data:{data:data, _token:token}
}).done(function(data){
$("#add-modal").modal('hide');
update(data.id); //calling out another function
if($(this).hasClass('redirect')){ //DOESNT WORK
//some action
}
}).error(function(data){
//error
});
}
});
The weird thing is that first class-check is working. Altough whatever button i click it never triggers part when class "redirect" is checked. I am kinda struggling to resolve this issue and i have no idea what could've I possibly did wrong. Any help would be greately appreciated.
Have a nice day.
Your $(this) is not pointing to the button anymore. In order to fix this, you can use .bind() as suggested by #dfsq or you can assign the $(this) to a variable and then use it. Like
var btn = $(this);
And later use the above as
.done(function(data) {
$("#add-modal").modal('hide');
update(data.id);
if(btn.hasClass('redirect')) {
//some action
}
Also, the good part over here is that you don't have to call $(this) everywhere, as you are holding a reference of $(this) in a variable. So you can also change
if($(this).hasClass('store-submit')) {
TO
if(btn.hasClass('store-submit')) {
//and practically everywhere you can use btn instead of $(this)
You need to bind callback function to correct context. One way to do it is using Function.prototype.bind:
.done(function(data) {
$("#add-modal").modal('hide');
update(data.id); // calling out another function
if ($(this).hasClass('redirect')) {
//some action
}
}.bind(this)) // note: bind(this) call
Related
I have an MVC application and one of the views contains a button with a condition.
<i class="fa fa-sticky-note-o"></i>Did Not Eat
<button type="button" id="btnRemoveDidNotEat" class="btn btnRemoveDidNotEat">Remove Did Not Eat</button>
On click of btnRemoveDidNotEat,btnRemoveDidNotEat is hidden.
If btnDidNotEat is clicked,btnRemoveDidNotEat is shown.
Here is my JS code.
$('.btnDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').show();
});
});
$('#btnRemoveDidNotEat').on('click', function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
});
The functionality works for the first time. On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. On click of '#btnRemoveDidNotEat', it is hidden as required.
However the second time,On click of ".btnDidNotEat", the other button '#btnRemoveDidNotEat' is shown. But the button click function for '#btnRemoveDidNotEat' is not called.
I have tried doing the same with style="display:none;", but that gives me the same issue. I have also tried using toggle.
Am I missing something?
EDIT : Simplified the question to make it more clear.
I am not sure I understand your question right, but it looks like your AJAX response seems to have a partial view result. If you are trying to access the button click event of that partial view of AJAX, it will not hit the click event because it will not be attached to the DOM. So instead of your code, you should use something like this.
$("body").on("click", ".btnRemoveDidNotEat", function() {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').hide();
});
}
I'm not sure if I understood your question correctly, but here is what I got fiddle
Here is some improvements of your script:
$('.btnDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
$('#btnRemoveDidNotEat').click(function () {
$.ajax({
}).done(function (partialViewResult) {
$('#btnRemoveDidNotEat').toggle();
});
});
You can use toggle() function instead of adding and deleting class.
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.
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>
A very interesting problem I am facing these days is regarding one of my JavaScript function. My JavaScript function with some specific name is not working but if I change its name to anything else then it is working. Have a look -
// function to retain the jquery ui css for toolbar
function retain_css() {
alert('hi');
$( "#new_sort_options" ).buttonset();
}
// new sort
$(document).on("click", ".new_sort_button", function() {
var order = $(this).val();
var make_id = $('#new_make_id').val();
$.ajax({
beforeSend : start_loader(),
type : 'POST',
url : '/ajax/new-sort.php',
data : 'order='+order+'&make_id='+make_id,
dataType : 'json',
success : function(data) {
$("#new_results_toolbar").html(data.toolbar);
$("#new_results").html(data.models);
retain_css();
end_loader();
}
});
});
But retain_css() is not working at all. Even alert() is not firing. But if i change its name to anything such as my_fun() then the code works. I don't understand why it is happening so? Any idea? Don't worry about end_loader() function as it has nothing to deal with my problem. I also changed the order of code when retain_css() was being used but didn't work.
Try not to create global functions because it may collide with other frameworks or libraries.
//define private namespace
window.user3779493Functions = {};
//define method
user3779493Functions.retain_css = function() { ... }
//call method
user3779493Functions.retain_css();
Some functions are already programmed like 'alert('hi');', that is a function called alert:
function alert() {
/* do something */
}
That function also doesn't work.
I have a blockUI plugin for jquery through which i call another php file in a overlaid box. I want to activate the function through more than one button of same id(here it is pageDemo1). But when i do so, only one button works while all other don't.Can anyone explain why is it so? and what should i do to make it work?
$(document).ready(function() {
$('#pageDemo1').click(function() {
$.blockUI({ message: $('#domMessage') });
test();
});
$('#submit').click(function() {
var action = $("#form1").attr('action');
var form_data = {
message: $("#message").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == 'success')
$("#form1").slideUp('slow', function() {
$("#message").html("<p class='success'>message</p>");
});
else
$("#message").html("<p class='error'>message</p>");
}
});
return false;
});
});
On first look dont use html elements with the same id. you can attach your events on elements with the same class, name etc.
Are you saying that you have two elements (buttons) with the same ID? If so, this is not valid HTML (See W3C standards). You could try using a class instead. Also remember you can use multiple classes to still keep the buttons unique in some way. E.g.
<input type="button" class="pageDemo pageDemo1" value="My Click does this"/>
<input type="button" class="pageDemo pageDemo2" value="My Click also does this/>
Then to access these in your JS:
$('.pageDemo').click(function() {
// Put code here which should happen when either of your elements with class 'pageDemo' get clicked
});
$('.pageDemo.pageDemo1').click(function() {
// Put code here which should only happen when elements with 'pageDemo1' class get clicked
});