Change class and text of button based on post result - javascript

I'm trying to change the class and text of the button that was clicked based on the result from an ajax post. The page has many buttons, none have IDs (although I could add them if it's for sure needed). I have the following javascript:
$('.ph-button').click(function () {
var selected = [];
$(this).closest('tr').each(function () {
$(this).find('td').each(function() {
selected.push($(this).html));
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
//need the if statements here I think
console.log(data);
}
});
});
It works and gives me a 0 or 1 as data. I need to change the class to class='ph-button ph-btn-blue and the text to Watched if data is 0 and change the class to class='ph-button ph-btn-grey and the text to Watch if data is 1.
I tried using $(".ph-button").toggleClass("ph-button ph-btn-blue"); but it changed the class of all the buttons on the page and didn't seem to do it like I need.
I'm guessing toggleClass isn't what I need and i'm not sure how to address the button that was clicked instead of all of them. Here are the two possible buttons:
<td><button class='ph-button ph-btn-blue'>Watched</button></td>
<td><button class='ph-button ph-btn-grey'>Watch</button></td>
SOLUTION:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
console.log(selected);
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
console.log(data);
if (data == 1) {
btn.toggleClass("ph-btn-grey ph-btn-blue").text('Watched');
}
if (data == 0) {
btn.toggleClass("ph-btn-blue ph-btn-grey").text('Watch');
}
}
});
});

set a temporary variable referencing the button, so you can use it later on in your AJAX success callback:
$('.ph-button').click(function () {
var selected = [];
var btn = $(this);
$(this).closest('tr').each(function () {
$(this).find('td').each(function(){
selected.push($(this).html());
})
})
$.ajax({
type: "POST",
url: "/ClassSearch/watchClasses",
data: { arrayOfClasses: selected },
traditional: true,
success: function (data) {
if(data == "0"){
btn.toggleClass("ph-button ph-btn-blue").text('Watched');
}
}
});
});

Related

How the dependency drop will work during onload with JQuery

There is some data inside a table
When I press the edit button, I can edit all the data for that row.Menu Category and Menu These two data came from Dependent dropdown.
with this code the dropdown in the menu was supposed to show when the menu categories were selected.
modal.find('.modal-body #menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
This code goes through the menu category ID and selects Fastfood Dropdown.
$(document).ready(function () {
$(document).on('change','#menu_category_update',function(){
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate($(this).val());
$("menu_update").empty();
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
});
});
function GetLoadApptUpdate(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/"+id,
success: function (response) {
b = response;
},
error: function (response) {
b = { id: 0, text: "No Data" }
}
});
return b;
};
#menu_category_update The function that is being called with this ID is working properly. But my problem is that when I click on the edit button, a dropdown is selected by default, for which the dependent dropdown is not selected.
Expected answer:
Here is the solution:
$('#menu_category_update').val(menu_item_category_selected);
modal.find('.modal-body #menu_update').val(menu_item_selected);
var menu_category_update_val = $("#menu_category_update option:selected").val();
var menu_update_val = $("#menu_update option:selected").val();
if (menu_category_update_val !== "") {
func();
$('#menu_update').val(menuItemSelected).trigger('change');
}
function func() {
$('#menu_category_update').change(function () {
$("#menu_update").empty();
var ddl_menu1 = GetLoadApptUpdate1($(this).val());
$('#menu_update').select2({
placeholder: "--Select Menu--",
data: ddl_menu1,
dropdownParent: $(this).parent()
});
}).change();
function GetLoadApptUpdate1(id) {
var b = [];
$.ajax({
type: "GET",
dataType: "json",
cache: true,
async: false,
url: "/admin/menu/item/entry1/" + id,
success: function (response) {
b = response;
},
error: function (response) {
b = {id: 0, text: "No Data"}
}
});
return b;
};
}

Validation DropDownList outside grid

I have kendo dropdownlist and button submit. I want if the user not select anything in dropdown(position), there will be validation that inform the user must select one position at least at dropdown. Then, if the user has click the position, so the user can submit the data. I have used some method like "required" but not working.
HTML
<input id="dropdown" style="width:200px;" />
JavaScript for kendoDropDownList (position)
$("#dropdown").kendoDropDownList({
optionLabel: "- Select Position -",
dataTextField: "functionName",
dataValueField: "hrsPositionID",
dataSource: {
transport:{
read: {
url: "./testjson.php",
type: "POST",
data: function() {
return {
method: "getDropdown",
}
}
},
},
},
change: function(e){
console.log(this.value());
// $('#AccountingTree').data('kendoTreeView').homogeneous.read();
homogeneous1.read();
homogeneous2.read();
homogeneous3.read();
homogeneous4.read();
homogeneous5.read();
homogeneous6.read();
homogeneous7.read();
homogeneous8.read();
homogeneous9.read();
homogeneous10.read();
homogeneous11.read();
homogeneous12.read();
homogeneous13.read();
homogeneous14.read();
}
}).data('kendoDropDownList');
dropdownlist = $("#dropdown").data("kendoDropDownList");
For dropdownlist above, i"m using homogeneous data (treeview).
Anyone have any idea or reference on this question?
JavaScript AJAX call for submit button
//AJAX call for button
$("#primaryTextButton").click(function(){
if($("#dropdown").data("kendoDropDownList").value() == ""){
kendo.alert("Please select position.");
}
});
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").val()
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS")
{
kendo.alert("Data saved");
}else
{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
});
When you click the button, just get the value of the kendoDropDownList and do a
conditional statement. Hope this helps. Happy Coding ;D
//AJAX call for button
$("#primaryTextButton").kendoButton();
var button = $("#primaryTextButton").data("kendoButton");
button.bind("click", function(e) {
var test = $("#dropdown").data("kendoDropDownList").value();
if(test == ""){
kendo.alert("Please select position.");
}
else{
$.ajax({
url: "../DesignationProgramTemplate/testjson.php",
type: "POST",
data: {
method: "addTemplate" ,
id: test,
progid: array
},
success: function (response) {
if(response === "SUCCESS"){
kendo.alert("Data saved");
}
else{
kendo.confirm("Update the data?")
.done(function(){
$.ajax({
type: "POST",
url: "../DesignationProgramTemplate/testjson.php",
data: {
method: "deleteTemplate" ,
id: test,
progid: array
},
success: function(){
kendo.alert("Data updated");
}
});
});
}
},
});
}
});

Why do the ajax requests fire multiple times

I have a form inside a modal that either saves a memo when one button is clicked or deletes it when another is clicked. The items get saved/deleted but the request count multiplies with each click. I'm getting 4 of the same request etc. How do i stop this. do i have to unbind something?
$('#modal').on('show.bs.modal', function (e) {
var origin = $(e.relatedTarget);
var memoId = origin.attr('data-id');
$('#modal').click(function(event){
if($(event.target).hasClass('memo-save')) {
event.preventDefault();
var memoText = $(event.target).parent().parent().find('textarea').val();
var memo = {
memo: memoText,
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/add-memo?memo=' +memo+'&id=' + memoId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Saved');
}
});
} else if($(event.target).hasClass('memo-delete')) {
event.preventDefault();
var memoText = "";
var memo = {
id: memoId
}
$.ajax({
type: "POST",
url: '/memos/remove-memo?id=' + itemId,
data: memo,
success: function (result) {
$(event.target).toggleClass('active').html('Memo Deleted');
}
});
}
});
});
you can move the $('#modal').click outside the $('#modal').on('show.bs.modal' that way it will not re-add the listener each time the modal is shown

Auto Complete Popup not working properly on cloned elements

I am unable to explain it properly,so i have added the image,please help me with this and please dont down vote.
Hi i am cloning the div on button click,and i want the auto complete box on the cloned elements also. on first element it is working fine but on cloned element the auto complete box(popup) is showing on 1st element but it should be shown on newly created textbox
following is the html code
<div class="repeatingSection">
<input id="Jobs[0].SampleType" name="Jobs[0].SampleType" type="text" class="form-control classSampleType" placeholder="Sample Name" required />
Add Job
following is the js code for cloning
function resetAttributeNames(section) {
var tags = section.find('input,button'), idx = section.index();
tags.each(function () {
var $this = $(this);
$.each(attrs, function (i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/\[\d\]/,'['+(idx-5)+']'))
}
})
})
}
$('.addJob').click(function (e) {
e.preventDefault();
var lastRepeatingGroup = $('.repeatingSection').last();
var cloned = lastRepeatingGroup.clone(true)
cloned.find("input").val("");
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned)
});
and following is the code for auto completion
$(".classSampleType").click(function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});
For Reference i have added the image Reference Image
worked for me by making following changes
var cloned = lastRepeatingGroup.clone(true,false)
$(document).on('click','.classSampleType',function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});

How to Hide multiple div on Ajax Success

I am trying to hide 2 div on Ajax Success by following code
$(".editButton").click(function () {
var self = this;
var membershipid = $(this).attr('id');
$.ajax({
type: 'POST',
url: '#Url.Action("GetMembershipDetail","User")',
data: { "MembershipID": membershipid },
success: function (data) {
$('#ddlStoreUpdate').val(data["fk_Store_ID"]);
$('#TxtTitleUpdate').val(data["MembershipTitle"]);
$('#TxtDescriptionUpdate').val(data["MembershipDescription"]);
$('#TxtTimeFrameUpdate').val(data["MembershipTimeFrame"]);
$('#TxtMembershipMinUpdate').val(data["MembershipMinVisit"]);
$('#chkUpdate').prop('checked', data["MembershipGroundLevel"]);
$('#HiddenMembershipID').val(membershipid);
if (data["MembershipGroundLevel"] == true)
{
alert("True");
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
}
else
{
alert("false");
$("#RowTimeFrame").show("slow");
$("#RowMinFrame").show("slow");
var storeid = $("#ddlStore").val();
$.ajax({
type: 'POST',
dataType: 'json',
url: '#Url.Action("GetTimeFrame","User")',
data: { 'StoreID': storeid },
success: function (data) {
$("#TxtTimeFrame").val(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
}
},
error: function (data) {
alert(JSON.stringify(data));
}
})
$("#myModalUpdate").modal('show');
});
If condition is working well, but Div(s) doesn't hide
If I remove $(self).closest() from second div, first div hides all well, Issue is with multiple div
You can use class to hide it, like this:
$(".resetValueTo0").val(0);
$(".divToHide").hide();
Therefor, you don't need to do this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
You might want to try this:
Replace this code:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").hide()
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").hide()
To this:
$("#TxtTimeFrameUpdate").val(0);
$(self).closest("#RowTimeFrameUp").each(function(){
$(this).hide();
});
$("#TxtMembershipMinUp").val(0);
$(self).closest("#RowMinFrameUp").each(function(){
$(this).hide();
});

Categories

Resources