Unable to reset the data form - javascript

Unable to reset the data in jQuery. I am trying to save the data using jQuery its happening. But when I click on remove glyph-icon, data is not reset in the form. I tried a code but it is not working. When I click on remove icon also the data is being saved. I am stuck with place the reset code. Used glyphicons to save and reset the data. I do not wish do abort in ajax.
//Banking details form validation
$(document).ready(function() {
$('.editBankDetailBtn').click(function() {
if ($('.editBankDetail').is('[readonly]')) { //checks if it is already on readonly mode
$('.editBankDetail').prop('readonly', false); //turns the readonly off
$('.editBankDetailBtn').html('<span class="glyphicon glyphicon-floppy-disk"> </span>' + '<span id="reset-form" class="glyphicon glyphicon-remove"> </span>');
// $('.glyphicon-remove')[0].reset();
} else { //else we do other things
var patt = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
var reg = /^[A-Za-z]{4}[0-9]{6,7}$/;
patt.test('acdbdfdsfsf22-333-666666'); // true
var bname_1 = document.getElementById('bankName').value;
if (bname_1 == "") {
document.getElementById('bankName').style.borderColor = "red";
return false;
} else {
document.getElementById('bankName').style.borderColor = "#cccccc";
}
var aaccount_number = document.getElementById('accountNumber');
if (!patt.test(aaccount_number.value)) {
document.getElementById('accountNumber').style.borderColor = "red";
return false;
} else {
document.getElementById('accountNumber').style.borderColor = "#cccccc";
}
var bifsc = document.getElementById('ifscCode').value;
if (!reg.test(ifscCode.value)) {
document.getElementById('ifscCode').style.borderColor = "red";
return false;
} else {
document.getElementById('ifscCode').style.borderColor = "#cccccc";
}
var bank_address = document.getElementById('branchAddress').value;
if (bank_address == "") {
document.getElementById('branchAddress').style.borderColor = "red";
return false;
} else {
document.getElementById('branchAddress').style.borderColor = "#cccccc";
}
$('.editBankDetail').prop('readonly', true);
$('.editBankDetailBtn').html('<span class="glyphicon glyphicon-pencil"> </span>');
}
$(document).ready(function() {
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
});
});
});
function saveBankDetail() {
$.ajax({
url: '${pageContext.request.contextPath}/update-bankdetail.html',
type: "post",
data: {
bankName: $('#bankName').val(),
branchAddress: $('#branchAddress').val(),
accountNumber: $('#accountNumber').val(),
ifscCode: $('#ifscCode').val(),
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

You have $(document).ready(...) within $(document).ready(...). Note that the event is only fired once, which means that the inner one is never fired. You have also nested the click events (not recommended).
Your code should be looking something like:
$(document)
.ready(
function() {
$('.editBankDetailBtn').click(function() {
...
};
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
...

Related

How To Stop all Functions in JavaScript using an IF Function

I'm trying to use one function and a lot of IF functions to run this code.
I'm going to make this as a note app.
I want to add an IF function that has an class called stop-note.
I want to add it in the notes list for it's IF function then I want to add it to the "renderNotes" for it's link like style.
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
var abort = false;
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});
This is my function that runs my function above.
function renderNotes(notes) {
var html = '';
if (notes.length) {
notes.forEach(function (note) {
html += `<li class="note">
<p class="header">
<span class="date">${note.date}</span>
Listen
Edit
html = <button class="stop-note" onclick="abort = true">Stop</button>
Delete
</p>
<p class="content">${note.content}</p>
</li>`;
});
} else {
html = '<li><p class="content">You don\'t have any notes yet.</p></li>';
}
notesList.html(html);
}
abort is a local variable, and you set it to false whenever they click on a note list. So onclick="abort = true" has no effect on the variable that's being tested in the function.
You need to make it a global variable.
window.abort = false;
notesList.on('click', function (e) {
e.preventDefault();
var target = $(e.target);
// Listen to the selected note.
if (target.hasClass('listen-note')) {
if (abort) {
return;
}
var content = target.closest('.note').find('.content').text();
readOutLoud(content);
}
//Edit Note
if (target.hasClass('edit-note')) {
editText(content);
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
var content = target.closest('.note').find('.content').text();
}
// Delete note.
if (target.hasClass('delete-note')) {
var dateTime = target.siblings('.date').text();
deleteNote(dateTime);
target.closest('.note').remove();
}
});

Reload page after click OK on the Alert Page

I want to reload page after clicking OK button on the javascript Alert box.
Here is my code :
$(".erase").click(function () {
var answer = confirm("Delete This Data?");
if (answer === true) {
var erase = false;
if (!erase) {
erase = true;
$.post('delete.php', {id: $(this).attr('data-id')} );
erase = false;
}
window.location.reload();
} else {
return false;
}
});
if I put the window.location.reload(); there, the page reloading after click OK, but I can't delete the data I want.
If I remove it, I can delete the data but the page doesn't reload.
Please help me on this
You just need to provide the window.reload() as a callback to $.post.
$(".erase").click(function () {
var answer = confirm("Delete This Data?");
if (answer === true) {
var erase = false;
if (!erase) {
erase = true;
$.post('delete.php', {id: $(this).attr('data-id')}, function() { // here's the new bit
window.location.reload();
} );
erase = false;
}
} else {
return false;
}
});
Change your first line to (I write code from head):
$(".erase").click(async function () {
and line with $.post to this:
let postResult = await Promise.resolve($.post('delete.php', {id: $(this).attr('data-id')} ));

Object doesn't support property or method 'stop' IE

When i click on submit button. I got an error like "Object doesn't support property or method stop " in Internet Explorer but data is successfully added in database.
Here is my code.
function SaveComment(subCommentId, trShowresponseId, tdShowresponseId, startDate, endDate) {
// alert("");
debugger;
try {
var response = document.getElementById("TextBoxResponse~" + subCommentId).value;
if (response === "") {
alert("Please Enter Response.");
return false;
}
else {
// var isAdvanceComment = 1;
$("#showloading").show();
var commentType = 'A';
var returnReult = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, startDate, endDate, 0).value;
if (returnReult.match("Error")) {
document.getElementById("spanErrorMessage").innerHTML = returnResponse;
}
else {
document.getElementById(tdShowresponseId).innerHTML = returnReult;
}
// document.getElementById(tdShowresponseId).innerHTML = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, 0).value;
document.getElementById("trHiddenTextBox~" + subCommentId).className = "hide";
document.getElementById("trAddSpan~" + subCommentId).className = "show";
document.getElementById("TextBoxResponse~" + subCommentId).value = "";
document.getElementById(trShowresponseId).className = "show";
$("#showloading").hide();
window.stop();
}
}
catch (ex) {
alert(ex.description);
}}
Instead of using window.stop(), return false or call preventDefault on the event object in the form’s submit listener – likely wherever you call SaveComment. Something along the lines of:
commentForm.addEventListener('submit', function (e) {
// …
SaveComment(…);
e.preventDefault();
});
The alert here suggests you might already be passing the return value straight through:
alert("Please Enter Response.");
return false;
in which case you should be able to do it here too:
$("#showloading").hide();
return false;
See https://developer.mozilla.org/en-US/docs/Web/API/Window/stop
The stop() method is not supported by Internet Explorer.
Also: I don't know what you are trying to achieve by calling stop().
However: you call window.stop(); as the last line in your file. Since you don't rollback in your catch-block or anything, everything before that call (e.g. writing to database) gets executed and not rolled back
Finally i solved this error by using this .
function SaveComment(subCommentId, trShowresponseId, tdShowresponseId, startDate, endDate) {
// alert("");
debugger;
try {
var response = document.getElementById("TextBoxResponse~" + subCommentId).value;
if (response === "") {
alert("Please Enter Response.");
return false;
}
else {
// var isAdvanceComment = 1;
$("#showloading").show();
var commentType = 'A';
var returnReult = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, startDate, endDate, 0).value;
if (returnReult.match("Error")) {
document.getElementById("spanErrorMessage").innerHTML = returnResponse;
}
else {
document.getElementById(tdShowresponseId).innerHTML = returnReult;
}
// document.getElementById(tdShowresponseId).innerHTML = dashboards_DiscreteRating.SaveComment(response, subCommentId, commentType, 0).value;
document.getElementById("trHiddenTextBox~" + subCommentId).className = "hide";
document.getElementById("trAddSpan~" + subCommentId).className = "show";
document.getElementById("TextBoxResponse~" + subCommentId).value = "";
document.getElementById(trShowresponseId).className = "show";
$("#showloading").hide();
if ($.browser.msie) { //************** Here is the answer ************
document.execCommand('Stop'); //************** Here is the answer ***********
}
else {
window.stop();
}
}
}
catch (ex) {
alert(ex.description);
}}
Internet Explorer does not support window.stop() so we can use document.execCommand("Stop") for IE.

Don't allow multiple form submissions

I'm trying to validate Google Captcha and my form, which currently does work. I'm using JQuery Forms and Validate Unobstructive. The problem is after submission, you can still submit the form as many times as you click.
Is there a way to ensure this only happens once?
I have tried using the following (commented in the code), but then you can't submit the form again to recheck the captcha:
if ($form.data('submitted') === true) { } else { }
JS:
$(document).ready(function () {
//Intercept Submit button in order to make ajax call instead of a postback
$('#contactForm').preventDoubleSubmission();
});
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function () {
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
// if ($form.data('submitted') === true) {
// // Previously submitted - don't submit again
// } else {
if ($form.valid()) {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
if ( captchaCheck() == false) {
captchaCheck();
} else {
// Make ajax call form submission
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
}
});
}
}
// }
});
// keep chainability
return this;
};
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
$(".contour-button").addClass("success");
var formFields = $(".contactForm input, .contactForm textarea, .contactForm button");
$(formFields).attr('disabled', 'disabled');
$(formFields).animate({'opacity':'0.5'});
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
You might disable clicked button just putting
var that = this;
$(that).attr("disabled", true);
after
e.preventDefault();
then, if you need, enable it when the operation is completed with
//probably after success()
$(that).attr("disabled", false);
I hope that's what you need!
I managed to solve this in a similar way to MonkeyZeus's suggestion by wrapping the AJAX call in a condition, using a bool (true/false).
var ajaxRunning = false;
$("button").click('submit', function (e) {
e.preventDefault();
var $form = $("#contactForm");
$($form).bind("invalid-form.validate", function() {
if( $("invalid-form.validate") ) {
formErrors();
}
})
if ($form.valid()) {
if ( captchaCheck() === false) {
captchaCheck();
formErrors();
} else {
if(!ajaxRunning){
ajaxRunning = true;
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
},
error: function (result) {
captchaCheck();
formErrors();
}
});
}
}
}
});
function hover() {
$(".contour-button").on("mouseenter", function() {
return $(this).addClass("hover");
});
}
function hoverOff() {
$(".contour-button").on("mouseleave", function() {
return $(this).removeClass("hover");
});
}
function success() {
var disabledElements = "#formFooter button, .contourField input, .contourField textarea";
var opacityElements = ".contourField input, .contourField textarea";
// disable button & inputs once submitted
$(disabledElements).attr('disabled', 'disabled');
// change opacity of elements
$(opacityElements).animate({ 'opacity' : '0.5' });
$(".contour-button").addClass("success");
$(".contour-btn-arrow").addClass("contour-btn-success");
$(".contour-button .submit").html("Thank you for your enquiry");
}
function formErrors() {
$(".contour-button").addClass("form-errors").delay(3500).queue(function(){
$(this).removeClass("form-errors").dequeue();
});
$(".contour-btn-arrow").addClass("contour-btn-error").delay(3500).queue(function(){
$(this).removeClass("contour-btn-error").dequeue();
});
$(".contour-button .submit").html("There are errors on the form").delay(3500).queue(function(){
$(this).html("Submit").dequeue();
});
}
function captchaCheck() {
var captchaResponse = grecaptcha.getResponse();
if(captchaResponse.length == 0) {
// html for the captcha error message
var captchaMsgHtml = '<img src="/images/form-error-icon.png" /> Please check the captcha and try again';
$("#captchaMsg").html(captchaMsgHtml).slideDown(500);
$(".g-recaptcha div div").addClass("recaptchaHighlight");
return false;
} else {
$(".g-recaptcha div div").removeClass("recaptchaHighlight")
$("#captchaMsg").hide();
return true;
}
}
hover();
hoverOff();
For starters, if you are actually using a <form> with a dedicated <submit> or <button type="submit">Submit</button> then you should be listening for on.('submit'):
var allowSubmit = TRUE;
$('form').on('submit', function(e)
{
if(allowSubmit === TRUE)
{
allowSubmit = FALSE;
// Perform your validations + AJAX calls and make sure to set
// allowSubmit = TRUE; wherever appropriate
if(validationFails)
{
allowSubmit = TRUE;
}
else
{
$.ajax({
url: $form.attr('action'),
type: 'POST',
cache: false,
data: $form.serialize(),
success: function (result) {
success();
allowSubmit = TRUE;
},
error: function() {
// Do some error handling
allowSubmit = TRUE;
}
});
}
}
else
{
e.preventDefault();
}
});

Replace button before ajax call and then revert back after call

I have a button on my webpage that is generated like this :
<div class="btn2" id="btPost" onclick="$('#Delete').val('False'); ValidateFormAndAjaxSubmit('frmEditPost', this);" onmousedown="this.className='btn2_click';" onmouseout="this.className='btn2';" onmouseover="this.className='btn2_hover';" onmouseup="this.className='btn2_hover';">
<span>Posta</span>
</div>
When I have this javascript :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$.post(_form.attr("action"), _form.serialize(), function (data) {
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}
This is working fine, but the problem is that I want to show the enduser that the form is loading. The best solution might be to simple remove the callingElement from the webpage and replace it with a temporary disabled(special CSS) button. The button needs to return then the ajax method is done.
I know about this :
$("#regTitle").html("Hello World");
But it is only replacing inner part of the div and I do also need to store the current markup to beable to go back when the ajax call is done.
It would also be good if the text within the span is placed also on the temporary button.
The question is how I do this as simple as possible?
Try this
$.ajax({
'type': 'POST',
'url': _form.attr("action"),
'data': _form.serialize(),
'beforeSend': function() {
$('.btn2').hide();
$('#regTitle').html('Loading ...');
$('#regTitle').show();
},
'success': function() {
$('.btn2').show();
$('#regTitle').hide();
},
'error': function() {
$('.btn2').show();
$('#regTitle').html('Error ...');
}
});
This is how I solved it :
Generate extra hidden div under the botton like this :
<div class="loadingDiv" id="loadingDiv_btPost"></div>
with the following css :
.loadingDiv {
float: left;
display: none;
height: 26px;
width: 60px;
background: url("images/animations/ajaxLoader.gif") no-repeat;
background-position: center center;
}
Then changed the javascript like this :
function ValidateFormAndAjaxSubmit(formId, callingElement) {
if (IsNotDblClick(callingElement.id)) {
var _form = $("#" + formId);
var validator = _form.validate();
var anyError = false;
anyError = !_form.valid();
if (anyError) {
window.latestClick = '';
return false; // exit if any error found
}
$('#' + callingElement.id).hide();
$('#loadingDiv_' + callingElement.id).show();
$.post(_form.attr("action"), _form.serialize(), function (data) {
$('#loadingDiv_' + callingElement.id).hide();
$('#' + callingElement.id).show();
if (data.success && data.redirectUrl.length > 0) {
window.location.href = data.redirectUrl;
}
else {
var isValid = validateResponse(_form, data);
window.latestClick = '';
}
})
}
}

Categories