Toggle between images in javascript or jquery - javascript

I need to toggle between "edit.png" and "ok.png" . Initially web page loads the page contains "edit.png" image buttons. Like in the screen shot below
My requirement is, once i click on the edit.png it should be remains as edit.png image state. And once again i click on the edit.png it should changed to "ok.png". So how can i do this anyone help me.
What i tried is
$(function(){
$('.edit').on('click',function(){
$(this).toggle();
//show the ok button which is just next to the edit button
$(this).next(".ok").toggle();
});
$('.ok').on('click',function(){
$(this).toggle();
$(this).next(".edit").toggle();
});
})
$('#projectsTable').Tabledit({
url: '#',
deleteButton: false,
buttons: {
edit: {
class: 'btn btn-primary secodary',
html: '<img src="/concrete5/application/images/animated/btn_edit.png" class="edit" /><img src="/concrete5/application/images/animated/btn_ok.png" class="ok" style="display:none" />',
action: 'edit'
}
},
columns: {
identifier: [1, 'Projects'],
hideIdentifier: true,
editable: [[1, 'Projects'], [2, 'Subprojects'],[8, 'Project Status', '{"1": "Open", "2": "Closed"}']]
},
onDraw: function() {
console.log('onDraw()');
},
onSuccess: function(data, textStatus, jqXHR) {
console.log('onSuccess(data, textStatus, jqXHR)');
console.log(data);
console.log(textStatus);
console.log(jqXHR);
},
onFail: function(jqXHR, textStatus, errorThrown) {
console.log('onFail(jqXHR, textStatus, errorThrown)');
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},
onAlways: function() {
console.log('onAlways()');
},
onAjax: function(action, serialize) {
console.log('onAjax(action, serialize)');
console.log(action);
console.log(serialize);
}
});
$(function(){
$('.edit').on('click',function(){
$(this).toggle();
//show the ok button which is just next to the edit button
$(this).next(".ok").toggle();
});
$('.ok').on('click',function(){
$(this).toggle();
$(this).next(".edit").toggle();
});
})

Use a click counter, so when you click on the button the second time, it shows the "edit" button and resets the counter back to 0.
When you then click on the "ok" button it changes back to the "edit" button, and because you now have done the first edit, next time you click on the button it changes to "ok" right away.
$('.edit').each(function() {
var clickCounter = 0, // Sets click counter to 0 - No clicks done yet
firstEdit = false; // Sets first edit to false
$(this).on('click', function() {
clickCounter++;
if( clickCounter == 2 || firstEdit == true ) {
$(this).toggle();
$(this).next('.ok').toggle();
clickCounter = 0; // Reset counter
firstEdit = true;
}
});
});
$('.ok').on('click', function() {
$(this).toggle();
$(this).prev('.edit').toggle();
});
Working Fiddle

$(window).ready(function(){
$('.edit').each(function(){
var counter=0;//add a counter to each edit button
this.on('click',function(){
counter++;//increase counter
console.log(counter);
if(counter===2){//if button clicked twice
$(this).toggle();
//show the ok button which is just next to the edit button
$(this).next(".ok").toggle();
counter=0;//reset counter
}
});
});
});
or taking pure ES6:
window.onload=function(){//when the page is loaded
var imgs=[...document.getElementsByClassName("edit")];//get all edit imgs
imgs.forEach(img=>{//loop trough images
var counter=0;//add a counter for each image
img.onclick=function(){
counter++;//onclick increase counter
if(conter===2){//if img was clicked twice
this.src="ok.png";//replace the img
counter=0;
}
}
});
};

You can use one class to control and change the state of your button:
$('.edit').on('click',function(){
if ($(this).hasClass('is-state1')) {
$(this).next(".ok").toggle();
$(this).toggle();
}
$(this).toggleClass('is-state1');
});
$('.ok').on('click',function(){
$(this).toggle();
$(this).next(".edit").toggle();
});
Also I'm thinking you are wrong in ok button event as you want change your previous and not your next button:
$('.ok').on('click',function(){
$(this).toggle();
$(this).prev(".edit").toggle();
});

Related

Javascript button delete

I had an issue with delete button.
ex: I press delete at driver 1 and choose no, after that I press delete at driver 2 and choose yes. driver 1 also deleted automatically.
here's my delete button code :
$(document).ready(function(){
$('#datatable tbody').on('click', '.delete', function(event) {
event.preventDefault();
$('.modal-header h4').html($(this).data('title'));
$('.modal-body p').html($(this).data('message'));
var url = $(this).data('url');
var datatable = $('#datatable').DataTable();
$('#confirmDel').on('click', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('.modal-body input[name="_token"]').val()
},
url: url,
type: "DELETE",
success: function (data) {
console.log(data);
datatable.ajax.reload();
$.gritter.add(
{
title: "Record has been deleted succesfully",
});
},
error: function (data) {
console.log(data);
}
});
$('#modalDelete').modal('hide');
});
});
});
Any Idea ?
Do you use the same button with id ConfirmDel inside the modal?
Try unbinding the button event:
$('#confirmDel').unbind('click');
Before binding it again:
$('#confirmDel').on('click', function(e) { ...
I think this is an event bubble. Clicking on child element will fire the
click event on parent element also.
try something like this:
child.on('click', function(e){
e.stopPropagation();
});

Ajax + browser backbutton = checkbox not working

I have a content page which is loaded via Ajax with a checkbox on it. The checkboxes works as it should when I click the normal menu buttons on my webpage to get to the content. But when I go to another page and use the back button to get back to the page which has the checkboxes, the checkboxes stop working.
html:
<div id="filters">
<ul id="filters-background">
<li id="option-type">Filter Options</li>
<li class="wave2"><label for="white">White<input type="checkbox" name="white" value=".White" id="white"></label></li>
<li class="wave2"><label for="blue">Blue<input type="checkbox" name="blue" value=".Blue" id="blue"></label></li>
</ul>
</div>
<script type="text/javascript">
OnSort();
</script>
js:
function OnSort(e) {
console.log('aaa');
// filter button click
var filterCheckboxes = $('#filters input');
var filters = [];
filterCheckboxes.change(function() {
console.log('clicked checkbox');
filterCheckboxes.filter(':checked').each(function() {
console.log('working');
filters.push( this.value );
});
});
}
If you look at the above code, the console will output 'aaa' when I click on the back button but if I test a checkbox it will not output 'clicked checkbox' in the console. How can I make it so the checkboxes will keep working even after I use the browser back button?
Maybe relevant PageLoad and Backbutton Ajax code:
function OnLoadPage(e) {
e.preventDefault();
var pageurl = $(this).data('url');
$.ajax({
type: 'GET',
url: pageurl,
success: function(data) {
$('#content').html(data['content']); // update content
if(data['menu']) { // update menu
$('#menu').html(data['menu']);
}
else {
$('#menu').html('');
}
// update url
window.history.pushState({path:pageurl}, '', pageurl);
},
error: function(response) {
alert('ERROR:' + response.responseText);
}
});
}
function InitOverrideBrowserBackButton() {
// override the back button to get the ajax content without page reload
$(window).bind('popstate', function() {
$.ajax({url:location.pathname+'?rel=tab', success: function(data){
$('#content').html(data['content']); // update content
if(data['menu']) { // update menu
$('#menu').html(data['menu']);
}
else {
$('#menu').html('');
}
}});
});
}
I've also tried:
$(document).on('click', '#filters input', function() {
console.log('clicked checkbox');
filterCheckboxes.filter(':checked').each(function() {
console.log('working');
filters.push( this.value );
});
});
Which will output 'aaa' and 'clicked checkbox' but not 'working'.
Figured it out with help from others on StackOverflow. Here's the answer:
function OnSort(e) {
console.log('aaa');
// filter button click
var filters = [];
$(document).on('click', '#filters input', function() {
console.log('clicked checkbox');
$('#filters input', document).filter(':checked').each(function() {
console.log('working');
filters.push( this.value );
});
});
}

Wait for document mousedown to complete before element onclick can start

I have a panel that slides open on an element click called "details" and populates the panel via ajax depending on the data attribute value. I also have it setup that if you close outside that panel, it will close. If the panel is open and the user clicks on a different "details" element, I want the panel to close and open again populated with the data from the new data attribute.
Problem is that the codes checks if the panel is visible and won't load the ajax if it is. How can I change this so the click event knows the mousedown event is completed before it does it's thing?
// SLIDING PANEL
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
return false;
});
$(document).on("mousedown", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
//_self.parent().parent().removeClass("warning");
});
});
// don't close panel when clicking inside it
$(document).on("mousedown","#DetailsPanel",function(e){e.stopPropagation();});
$(document).on("click", "#ClosePanel", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
$("#LeadsTable tr").removeClass("warning");
});
});
// END SLIDING PANEL
Setting a timeout worked for me in another context:
onclick="window.setTimeout( function(){ DO YOUR STUFF }, 2);"
This solves many problems of this type.
I'm not totally sure about this but if you use "mouseup" instead "click" could work as you expect. Try it and let me know if I'm wrong.
Ok, so I found this little nugget http://www.gmarwaha.com/blog/2009/06/09/jquery-waiting-for-multiple-animations-to-complete/ and it works pretty good. No issues so far.
Here is the new code
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
var wait = setInterval(function() {
if( !$("#DetailsPanel").is(":animated") ) {
clearInterval(wait);
// This piece of code will be executed
// after DetailsPanel is complete.
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
}
}, 200);
return false;
});

Jquery post loading gif

I have the following script
<script>
$('#event li').click(function() {
var text = $(this).text();
$.post("A.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#result').html(return_data);
});
$.post("F.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#subresult').html(return_data);
initialize();
});
event.preventDefault() ;
});
</script>
Now the scripts A.php and B.php take some time to load the results , I want to show a loading gif during that portion of time. The approach which I took was
<img src="ajax-loader.gif" id="loadingImage" style="display: none;" />
<script>
$('#event li').click(function() {
$("#loadingImage").show();
var text = $(this).text();
.
.
.
However this didnt cause any change in the display. I still cant see the loader. Any other suggestions are welcome.
first:
1. Make sure that the actual image exists!
2. The code seems right, so please click the #event li element and go to your site-inspector to see of any errors appeared?
Probably your li hasn't been created yet and your click event is not binding. So, use $(document).ready(function() { ...// your code });
I would write your code as something like this (untested):
$(document).ready(function() {
$('#event li').click(function() {
var text = $(this).text();
$('#loadingImage').show();
var loaded = 0;
$.post("A.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#result').html(return_data);
loaded++;
if(loaded == 2) $('#loadingImage').hide();
});
$.post("F.php", { text: text }, function(return_data, txtStatus, jqXHR) {
$('#subresult').html(return_data);
loaded++;
if(loaded == 2) $('#loadingImage').hide();
initialize();
});
event.preventDefault() ;
}
});

Dialog pop up doesn't close

I'm trying to create a dialog box that adds an item to a dropdownlist;
here's the code.
$(function () {
$('#applicantDialog').dialog({
autoOpen: false,
width: 600,
height: 500,
modal: true,
title: 'Add Applicant',
buttons: {
'Save': function () {
var createApplicantForm = $('#createApplicantForm');
if (createApplicantForm.valid()) {
$.post(createApplicantForm.attr('action'), createApplicantForm.serialize(), function (data) {
if (data.Error != '') {
alert(data.Error);
}
else {
// Add the new Applicant to the dropdown list and select it
$('#Applicant').append(
$('<option></option>')
.val(data.id_applicant)
.html(data.Applicant.Applicant_name)
.prop('selected', true) // Selects the new Applicant in the DropDown LB
);
$('#applicantDialog').dialog('close');
}
});
}
},
'Cancel': function () {
$(this).dialog('close');
}
}
});
$('#applicantAddLink').click(function () {
var createFormUrl = $(this).attr('href');
$('#applicantDialog').html('')
.load(createFormUrl, function () {
// The createGenreForm is loaded on the fly using jQuery load.
// In order to have client validation working it is necessary to tell the
// jQuery.validator to parse the newly added content
jQuery.validator.unobtrusive.parse('#createApplicantForm');
$('#applicantDialog').dialog('open');
});
return false;
});
});
My problem is that when the form is saved and the item is added, it never closes the dialog box. When I click on cancel, the list is not updated until I refresh the page.
Is it a problem with postback and how can I deal with that?
Thanks

Categories

Resources