How do i make sure function createOverzicht only is excecuted after functions
checkNotEmpty and checkNumber are done, now if i click on the button function createOverzicht its called, but thats not supposed to happen, createOverzicht is only supposed to be called after the first two functions or done.
In this case i have a form and the first two functions are to validate the input, so thats why i dont want createOverzicht o excecute when there is nothing filled in
so to simplify the concept this is what i mean:
function createOverzicht() {
if (checkNotEmpty && checkNumber) {
alert('hi');
};
else {
//do nothing
};
}
function checkNotEmpty(field, span) {
if (field.value.length > 1 && isNaN(field.value)) {
document.getElementById(span).className = 'goed';
document.getElementById(span).innerHTML = '<img src=\'../img/ok.png\'>';
} else {
document.getElementById(span).className = 'nietgoed';
document.getElementById(span).innerHTML = '<img src=\'../img/notok.png\'>';
};
};
function checkNumber(field, span) {
if (field.value.length == 10 && !isNaN(field.value)) {
document.getElementById(span).className = 'goed';
document.getElementById(span).innerHTML = '<img src=\'../img/ok.png\'>';
} else {
document.getElementById(span).className = 'nietgoed';
document.getElementById(span).innerHTML = '<img src=\'../img/notok.png\'>';
};
};
function createOverzicht() {
alert('hi');
}
window.onload = function() {
document.getElementById('naam').oninput = function() {
checkNotEmpty(this, 'meldingNaam');
};
document.getElementById('achternaam').oninput = function() {
checkNotEmpty(this, 'meldingAchternaam');
};
document.getElementById('telefoonnummer').oninput = function() {
checkNumber(this, 'meldingTel');
};
document.getElementById('overzicht').onclick = function() {
createOverzicht()
};
};
As far as I can see you have two options:
1) store the status(valid or invalid) of each input
This could be hard to maintain!!
2) Inside "createOverzicht" call a function that check if everything is Ok
This alternative will imply make some changes in the functions that validate, you will need that they return true if the field is valid or by the contrary false; also add some code at the beginning of "createOverzicht".
The implementation will look like:
function createOverzicht() {
checkNotEmpty(document.getElementById('naam'), 'meldingNaam');
checkNotEmpty(document.getElementById('achternaam'),'meldingAchternaam');
checkNumber(document.getElementById('telefoonnummer'), 'meldingTel');
alert('hi');
}
function checkNotEmpty(field, span) {
if (field.value.length > 1 && isNaN(field.value)) {
document.getElementById(span).className = 'goed';
document.getElementById(span).innerHTML = '<img src=\'../img/ok.png\'>';
return true;
} else {
document.getElementById(span).className = 'nietgoed';
document.getElementById(span).innerHTML = '<img src=\'../img/notok.png\'>';
return false;
};
};
function checkNumber(field, span) {
if (field.value.length == 10 && !isNaN(field.value)) {
document.getElementById(span).className = 'goed';
document.getElementById(span).innerHTML = '<img src=\'../img/ok.png\'>';
return true;
} else {
document.getElementById(span).className = 'nietgoed';
document.getElementById(span).innerHTML = '<img src=\'../img/notok.png\'>';
return false;
};
};
May be use a javascript library like jQuery for this, the jQuery Validator plugging will help you a loot.
You need to move the call to createOverzicht() like this:
function myFunction() {
if (checkNotEmpty && checkNumber) {
createOverzicht();
};
else {
//do nothing
};
}
Also the checkNotEmpty and checkNumber functions need to return a Boolean value.
Related
I want to learn how to write Jquery plugin.This is my normal function and convert it into jquery plugin could you suggest me how to do this.
So that I can easily understand how to convert function to the plugin.
function probe_Validity(element) {
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
}
Take a look at this project jQuery plugin boilerplate
Consider this as a base plugin definition, look it up, follow the steps and adjust them to your needs.
It's quite easy to do you just use
jQuery.fn.theNameOfYourFunction = function() {}
then you can get the element the function is called on like this :
var element = $(this[0])
so with your function it would be :
jQuery.fn.probe_Validity = function() {
var element = $(this[0]);
var validate = true;
$(".required-label").remove();
var warnings = {
text: "Please enter Name"
};
element.find(".required").each(function() {
var form_Data = $(this);
if (form_Data.prop("type").toLowerCase() === 'text' && form_Data.val() === '') {
form_Data.after('<div class="required-label">' + warnings.text + '</div>').addClass('required-active');
validate = false;
}
if (validate) {
return true;
} else {
return false;
}
$(function() {
$(".required").on("focus click", function() {
$(this).removeClass('required-active');
$(this).next().remove();
});
});
});
};
this can be called like so :
$('#id').probe_Validity ()
I have several functions that use this given for loop below.
function startClaw(dir){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
isAnimating = $("#claw").is(':animated');
if(!isAnimating){// prevents multiple clicks during animation
if(isMoving || isDropping){ return; }
MCI = setInterval(function(){ moveClaw(dir); },10);
//console.log("startClaw:" + dir);
stopSwingClaw();
}
}
}
}
//.................................................................
function dropClaw(){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
if(isDropping){ return; } //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
}
}
Everything in the else if statement is different within the various functions. I'm wondering if there is any way to place the "pieces" of the for loop on the outside of the else if into its very own function. I feel like I've seen this or had done this a very long time ago, but it escapes me and I couldn't find any examples. Thanks everyone!
Previewing, I see this is similar to the above. Two differences (it looks like) are here the count gets passed to the function in case they needed to ever have different checks in the if statement, and, it's checking what the return value is since it looks like you return out of the loop if the condition is met. There are notes in comments in the code below.
function startClaw(dir) {
// Pass a function as a callback to the method which expects to receive the count as a param
doReadCount(qdata, function(theCount) {
if (theCount === 5) {
isAnimating = $("#claw").is(':animated');
if (!isAnimating) { // prevents multiple clicks during animation
if (isMoving || isDropping) {
return true;
}
MCI = setInterval(function() { moveClaw(dir); }, 10);
//console.log("startClaw:" + dir);
stopSwingClaw();
}
return false;
});
}
//.................................................................
function dropClaw() {
// Pass a function as a callback to the method which expects to receive the count as a param
doReadCount(qdata, function(theCount) {
if (theCount === 5) {
if (isDropping) {
return;
} //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
});
}
function doReadCount(qdata, elseFunction) {
var readCount = 0;
var elseReturn;
for (var isRead in qdata) {
readCount++;
if (qdata[isRead]['reading'] == true) {
return;
} else {
// call the function that was sent and pass it the current read count. If the return is true, then also return true here
elseReturn = elseFunction(readCount);
if (elseReturn) {
return;
}
}
}
}
You can pass a function into another function to achieve this. I've done it for dropClaw, and it should be clear from my example how to do also extract startClaw.
function operateClaw(func){
var readCount = 0;
for(var isRead in qdata){
readCount++;
if(qdata[isRead]['reading'] == true){
return;
}else if(readCount == 5){
func();
}
}
}
function drop () {
if(isDropping){ return; } //prevent multiple clicks
stopSwingClaw();
isDropping = true;
MCI = setInterval(moveDown,20); //start heartbeat
}
function dropClaw () {
operateClaw(drop);
}
I am trying to get a better understanding on javacsript. And I am not sure why this code is not working. I am trying to create functions that will call another function. And return the results of the called function.
When I call the below, I get fully logged in and presented with the screen I desire. But jsDidLogin Always returns undefined. Is there a better way to implement my methods?
var jsDidLogin = beginLogin()
console.log(jsDidLogin)
function waitUntilElementFound(element, time, callFunction) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
return callFunction();
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
waitUntilElementFound(element, time, callFunction);
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin);
}
Changing to this alerts me when Fully Logged in, but if I change it to return status. I still get no returns.
My head is starting to hurt :(
function waitUntilElementFound(element, time, callFunction, callBack) //Wait for the element to be found on the page
{
if (document.querySelector(element) != null) {
callBack(callFunction());
}
else {
if (!checkForFailedLogin()) {
setTimeout(function () {
callBack(waitUntilElementFound(element, time, callFunction, function(status){alert(status);}));
}, time);
}
else {
return false;
}
}
}
function checkForFailedLogin() {
if (document.querySelector("div[class='modal-body ng-scope'] h1") != null) {
if(document.querySelector("div[class='modal-body ng-scope'] h1").innerHTML == "Login Error")
{
return true;
}
}
else {
return false;
}
}
function initialTabSelect() //Load the bank page once login is completed
{
document.querySelectorAll("li[class='Tab'] a")[0].click();
return "Fully Logged In";
}
function initialDoNotAsk() {
document.querySelectorAll("a[ng-click='modalCancel()']")[0].click();
return waitUntilElementFound("li[class='Tab'] a", 1000, initialTabSelect, function(status){alert(status)};);
}
function initialLogin() {
var accountName = document.getElementById("username");
var accountPassword = document.getElementById("password");
var evt = document.createEvent("Events");
evt.initEvent("change", true, true);
accountName.value = "USERNAME";
accountPassword.value = "PASSWORD";
accountName.dispatchEvent(evt);
accountPassword.dispatchEvent(evt);
document.querySelectorAll("form[name='loginForm'] button.icon-login")[0].click();
return waitUntilElementFound("a[ng-click='modalCancel()']", 2000, initialDoNotAsk, function(status){alert(status)};);
}
function beginLogin() {
return waitUntilElementFound("form[name='loginForm'] button.icon-login", 1000, initialLogin, function(status){alert(status)};);
}
How I can update function _handlePaste() inside function paste?
$.FE.MODULES.paste = function(editor) {
var clipboard_html;
function _handlePaste(e) {
// Read data from clipboard.
if (e && e.clipboardData && e.clipboardData.getData) {
var types = '';
var clipboard_types = e.clipboardData.types;
if (editor.helpers.isArray(clipboard_types)) {
for (var i = 0; i < clipboard_types.length; i++) {
types += clipboard_types[i] + ';';
}
} else {
types = clipboard_types;
}
clipboard_html = '';
// HTML.
if (/text\/html/.test(types)) {
clipboard_html = e.clipboardData.getData('text/html');
}
// Safari HTML.
else if (/text\/rtf/.test(types) && editor.browser.safari) {
clipboard_html = e.clipboardData.getData('text/rtf');
} else if (/text\/plain/.test(types) && !this.browser.mozilla) {
clipboard_html = editor.html.escapeEntities(e.clipboardData.getData('text/plain')).replace(/\n/g, '<br>');
}
if (clipboard_html !== '') {
_processPaste();
if (e.preventDefault) {
e.stopPropagation();
e.preventDefault();
}
return false;
} else {
clipboard_html = null;
}
}
// Normal paste.
_beforePaste();
}
}
The function is the part of jquery plugin, so I would like to change the function outside of the plugin's files to be able further update it.
I am trying to change it like this:
(function ($) {
$.FE.MODULES.paste._handlePaste = function (e) {
// my implementation of _handlePaste
}
})(window.jQuery);
But I can't access _handlePaste this way.
I've got this function to check my form:
function checkFrm() {
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
});
}
When the user submits this, it runs this code, and ideally if the criteria is met the form won't submit because of the 'return false;' bit.
However, for some reason it's completley ignoring this!
If I set a return variable at the start like 'var toreturn = true;' then set 'toreturn = false' when the trigger is hit, then 'return toreturn;' right at the end it stops the form submitting just fine... however that's not much use, as the alerts and checks I run in between are all triggered at once which would be completely overwhelming for the user.
Any suggestions please?
Cheers :)
Returning false from the each will not return false from the function.
You will need to set a var to return false from the function also. You can still break out of the each by using return false as soon as your condition fails.
function checkFrm() {
var retVal=true;
$.each($('select'), function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
//set the var to return from the function
retval = false;
//exit out of the each
return false;
}
}
});
return retVal;
}
When you call return false; it refurns false for the function
function() {
var $this = $(this);
if( $this.val() === 'null') {
// do nothing
} else {
if($this.next('input').val().length < 1) {
return false;
}
}
}
That is not work for you.
You better get an array of selects like this:
var selectsArray=document.getElementsByTagName("select");
and work with them in a loop.
for(var i=0; i< selectsArray.length;i++){
if( selectsArray[i].value === 'null') {
// do nothing
} else {
if(selectsArray[i].next('input').val().length < 1) {
return false;
}
}
}