Continuous execution of function? - javascript

I have a function that handles clicks when certain condition is met.
Scenario:
I want to close automatically the modal when click the Sign In button only if certain condition is met. And that condition is inside the $scope.empSignin().
So what I did according to some sources in the google, I create a function that will handle click event when the condition is valid.
html
//$scope.closeModal function
<button id="closeModal" type="button" class="close" data-dismiss="modal" ng-click="closeModal()">×</button>
//$scope.empSignin function
<input type="button" value="Sign In" ng-click="empSignin(signinInfo)">
this is the html file that contains a button that is automatically clicked in js function.
file.js
$scope.closeModal = function(){
console.log('entered');
$timeout(function(){
var el = document.getElementById('closeModal');
angular.element(el).trigger('click');
}, 0);
}
$scope.empSignin = function(signinInfo){
var data = {
username : signinInfo.username,
password : signinInfo.password
}
$http.post('server/emp_signin.php', data).then(function(res){
window.alert(res.data.message);
$scope.isMessage = res.data.message;
if($scope.isMessage == 'Successfully Signed In'){
console.log('true');
$scope.closeModal();
} else { console.log('false'); }
});
}
this js file contains function that handles click event.
It is working as I expected but when that event happened, in browsers console there is continuous execution (for what I know).
My question is what is happening there and why is that? And how I can solve that issue cause it is taking plenty of my device resources when I view in taskmanager.
Here is the screenshot of console:

Its because you are calling closeModal function on click event of the <button> and in the function, you are triggering click event again and which again calls closeModal function and thus it goes to infinite loop.And so you are seeing entered text in your console so many times. That's the issue.
angular.element(el).trigger('click'); // This is putting your code in infinite execution.
So remove above-mentioned line and there won't be the continuous execution of your code.

Related

button click event fires multiple times inside of a Bootstrap 3 Modal

I have a bug (or feature) whereby any button that is inside a Bootstrap 3 modal will fire the click event several times. Besides going "old-school" and calling a script from an HTML button directly (which always works), is there a workaround for this?
<div class="modal-footer">
<span id="spanSendReport">
<button type="button" id="btnSendReport" class="btn btn-success" data-dismiss="modal">Send Report</button></span>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
And the jquery
$("#btnSendReport").click(function (e) {
... my code
});
Using Bootstrap v3.4.1 and jQuery v3.3.1
Never ran into this before (except with things posting back, but there are no postbacks of any kind happening - checked in the browser and in debugger).
There is only 1 button in the DOM with the Id (first thing I checked), but it fires the click event 4 times, every time!
Any ideas?
NOTE: I forgot to mention, the modal is opened from another modal. Maybe that has something to do with it.
The complete code inside the click event function (just in case it has something to do with it):
$("#btnSendReport").click(function (e) {
var parElem = $(this).parent().parent().parent();
var listID = parElem.find("#hidLID").val();
var problemTypes = $.map(parElem.find('option:selected'), function (e) { return e.value; }).join(',');
var problemTypeOther = parElem.find("#txtProblemTypeOther").val();
var obj = {};
obj.lid = listID;
obj.ProblemTypes = problemTypes;
obj.ProblemTypeOther = problemTypeOther;
try {
$.ajax({
type: "POST",
url: "../../api/reportdiscrepancy/",
data: obj,
dataType: "json",
success: function (data) {
var result = data;
},
error: function (err) {
console.log(err);
}
});
} catch (err) {
console.log(err);
}
});
Found the problem and the answer to many issues I've been running into before and the culprit is function pageLoad() which is what older ASP.Net webforms uses for client side actions.
I removed the '#btnSendReport' click to OUTSIDE of the pageLoad() function and it's only firing once now.
It looks like any MS-AJAX accumulates ALL event bindings (not actually firing them) within an UpdatePanel, then a final call to a click event (or whatever) will fire x number of times.
I was clued in as I made 3 changes to get to the modal and the last thing I did was click on the button (so it fired 4 times).
I believe it may have to do with the default setting of the UpdatePanel with ChildrenAsTriggers=True (unfortunately, I have to leave that on as other functionality breaks if set to false).

JQUERY: Why don't any of my alerts appear when either one of my conditions matches true?

My alert divs don't show up when I click the submit button.
An 'Error' div should alert when there's an empty required field and,
a 'Success' div should alert right before the form submits. The form submits so I know the validation check works but, I don't see any of my alert divs. See code below:
const goaForm = document.getElementById('goa-form');
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
let success = document.getElementById('success-msg');
let error = document.getElementById('error-msg');
let submitButton = document.getElementById("btnSubmit");
function checkForm() {
if (formCompleted) {
success.style.visibility = 'visible';
goaForm.submit();
} else if (formIncomplete) {
error.style.visibility = 'visible';
$("#error-msg").fadeOut(28000);
return false;
}
}
submitButton.addEventListener("click", checkForm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="error-msg" style="visibility: hidden;" class="alert alert-danger" role="alert">
<span class="fs-14">Error message div</span></div>
<div id="success-msg" style="visibility: hidden;" class="alert alert-success" role="alert">
<span class="fs-15">Success!</span></div>
// Submit Button
<button onclick="checkForm()" id="btnSubmit" class="btn btn-success lift d-flex align-items-
center" type="submit">Submit my application <i class="fe fe-arrow-right ml-5"></i>
</button>
Thanks for the help guys.
checkForm() is fired when your button is clicked, but it uses values (formCompleted, formIncomplete) defined earlier, on page load. So you may fill out your form, but those variables are not updated, and clicking the button uses the old values that were set when the page was first loaded.
Instead, check the input states and define those variables inside your checkForm() function, so that they are set up as the actual, current results when the button is clicked. Then the tests evaluate what the form looks like at the time of the button click.
function checkForm() {
let formCompleted = $.trim($('#goa-form input[required]').val()) == !'';
let formIncomplete = $.trim($('#goa-form input[required]').val()) == '';
// ... rest of your code ...
Update
Here's a working JSFiddle.
Notes:
You're using a mix of plain JS and jQuery. There's nothing technically wrong with that, but it would certainly be easier to read and maintain if you stuck to one. If you are going to take the hit in loading jQuery (extra http request, 90kb odd extra resource, etc) you may as well use it.
I am not sure if it is actually invalid, but the formCompleted test seems wrong. I'd use the standard !== '' instead of == !'' (I've done that in the JSFiddle);
If you're going to use the type comparison for formCompleted, you should be consistent and also use it for formIncomplete, ie use === '' (I've done that in the JSFiddle);
Don't use both an inline onClick() on the button, and add an addEventListener in your JS. They both do the same thing, use only one of them. It is considered bad practice to mix JS in with your HTML, so using the plain JS addEventListener (or jQuery .on()) is better. I've removed the inline one from the JSFiddle.

In javaScript during a while loop how do you make the program stop to get user input?

So this is what i have, very simplified version of my code. So basically the 'userinput' function needs to know whether the user clicked on button 'run' or 'hit':
html code:
<button id="run">Run</button>
<button id="hit">Hit</button>
javascript code:
slaying = true;
while(slaying){
//gets user input
userinput();
// continue with the rest of the while loop until slaying is true
}
How would you write userinput()??
Instead of using a function "userInput()" you can use events and perform the same steps as you would do inside userInput()
You can use the onclick event as,
<button id="run" onclick="run()">Run</button>
<button id="hit" onclick="hit()">Hit</button>
And write the below script for this as,
function run(){
alert("You pressed Run");
//Steps to follow when Run is pressed.
}
function hit(){
alert("You pressed Hit");
//Steps to follow when Hit is pressed.
}
Here is a JSFiddle
You can use
var response = prompt("Question ?", "Default answer");

Button.onclick automatically triggers, then will not trigger again

I have a script, which I'm using to try and display only one section of a webpage at a time.
function showMe(id){ clearPage(); changeDisplay(id, "block"); console.log(id)}
Currently, I'm using buttons to change which section is displayed.
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=showMe("a-btn-section-id");
otherBtn.onclick=showMe("other-btn-section-id");
However, when I load the page, the following happens:
I see the function attached to each button activate once in sequence in the console.
The page refuses to respond to further button inputs.
Testing with the console shows that showMe() and the functions it calls still all work properly. I'm sure I'm making a very basic, beginner mistake (which, hopefully, is why I can't find this problem when I Google/search StackOverflow/read event handling docs), but I'm at a loss for what that mistake is. Why would my script assume my buttons are clicked on load, and why won't it let me click them again?
You're calling the function an assign the value to onclick property instead of attach the function, try defining your onclick property as:
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
Try the follow jsfiddle:
function showMe(id){ // some stuff..
console.log(id)
}
var aBtn = document.getElementById("a-btn");
var otherBtn = document.getElementById("other-btn");
aBtn.onclick=function(){showMe("a-btn-section-id");};
otherBtn.onclick=function(){showMe("other-btn-section-id");};
<input type="button" value="a-btn" id="a-btn"/>
<input type="button" value="other-btn" id="other-btn"/>
Hope this helps,

Why is my code firing multiple times

I have the following which is called from a $(document).ready(function() {:
$('#file_upload_form').submit(function(){
// show loader [optional line]
//if(document.getElementById('upload_frame') == null) {
// create iframe
$("#upload_list_button").hide();
$("#loading_icon_upload_addresses").show();
$('body').append('<iframe style="display: none" id="upload_frame" name="upload_frame"></iframe>');
$('#upload_frame').on('load',function() {
$("#upload_frame").unbind('load');
if($(this).contents()[0].location.href.match($(this).parent('form').attr('action'))){
// display server response [optional line]
var html_return = $(this).contents().find('html').html();
if ( html_return.indexOf("Error") > -1 ) {
$('#server_response').css("background-color", "#FFDEDE");
}
if ( html_return.indexOf("Success") > -1 ) {
$('#server_response').css("background-color", "#EEFCED");
}
$('#server_response').html(html_return);
args = {
ajax_token : getAjaxToken(),
client : $("input[name=client]").val(),
address_type : address_type
}
loadAddressList(args);
$("#upload_list_button").show();
$("#loading_icon_upload_addresses").hide();
}
})
$(this).attr('method','post');
$(this).attr('enctype','multipart/form-data');
$(this).attr('target','upload_frame').submit();
//}
});
I am essentially trying to upload a file by using an iframe to do the upload (found it too hard to do async).
Firebug shows that almost 100 requests are fired off. Why so? The ajax code that is firing is loadAddressList(args);
When you submit the form, the submit handler fires. Inside the submit handler (the last line of your code), you are submitting the form again. That causes another fire of submit handler, and this creates an infinite loop.
Try using e.preventDefault(); at the first line of your submit handler to make sure you submit the form only once.
Your code is being executed when a form is submitted but the last line of your code submits the form again.

Categories