How to merge two javascript function with third function with condition? - javascript

I am beginer in js, and i have problem with merge two fucntions. I want to make third function with condition, when checkbox is marked and reCAPTCHA is marked, only then button is enable. By default, i set the button to disabled.
Single functions as below is working:
function clauseValid(elem) {
document.getElementById("sendBtn").disabled = false;
return true;
};
function captchaValid () {
document.getElementById("sendBtn").disabled = false;
return true;
};
<input type="checkbox" name="chkbx" id='#ID#' value="#seq_claim_id#" onClick="clauseVlid(this)">
<div class="g-recaptcha" data-sitekey="*****..." id="ckecCaptcha" type="checkbox" data-callback="captchaValid"></div>
I tried make someone like this but it doesn't work:
function clauseValid(elem) {
return true};
function captchaValid() {
return true};
function CheckTest() {
if (clauseValid(elem) && captchaValid()) {
document.getElementById("sendBtn").disabled = false;
}
}

Use variables for keeping track of the current status of each condition:
let isClauseValid, isCaptchaValid;
function clauseValid(elem) {
isClauseValid = elem.checked;
setButton();
}
function captchaValid() {
isCaptchaValid = true;
setButton();
}
function setButton() {
document.getElementById("sendBtn").disabled = !isClauseValid || !isCaptchaValid;
}
NB: make sure to correct the spelling mistake in your HTML onclick attribute.

Related

How can I use ng-if to display a button based on the current user?

I am create a user profile and would like to show an edit button that only displays for the profile's owner. I am attempting to use ng-if so that the edit capabilities are removed from the DOM.
How can I use ng-if to display a button based on the current user?
In my view:
<button ng-if="editProfile()">EDIT</button>
In my controller:
$scope.editProfile = function (canedit) {
var canedit = false;
for (var i=0;i<$scope.users.length;i++) {
if ($scope.users[i].id===$scope.currentUser.id) {
canedit = true;
}
}
}
Your function needs to return true or false
<button ng-if="editProfile()">EDIT</button>
$scope.editProfile = function () {
for (var i=0;i<$scope.users.length;i++) {
if ($scope.users[i].id===$scope.currentUser.id) {
return true
}
}
return false
}
You are returning nothing from your function.
You can make it this way
<button ng-if="canEdit()">EDIT</button>
and in your controller
$scope.canEdit = function () {
return $scope.users.find(u=>u.id === $scope.currentUser.id) ? true : false;
}
Just add
return canedit;
below the for closing bracket
As everyone mentioned, the function wasn't returning true or false. After adding the return I discovered that the for statement was extraneous and I just needed a simple check. This code is working correctly:
$scope.editProfile = function () {
if ($scope.user.id===$scope.currentUser.id) {
return true
}
return false
}

WinJS listview iteminvokedHanlder how to

I'm using the iteminvokedHandler and was wonder if there is a better way to interact with the listView.
Currently using this:
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
myEdit();
});
};
});
The problem is that everytime I click on the listview myEdit() is run and propagates within the listview. I was wondering how to do it once and stop invoking listview until I am done with myEdit? Is there a simpler way to handle such a situation as this?
Simple yet hard to see when you have a mind block and forget some of the basics (yes yes I'm still learning):
var testtrue = true;
WinJS.UI.processAll(root).then(function () {
var listview = document.querySelector('#myNotePad').winControl;
listview.addEventListener("iteminvoked", itemInvokedHandler,false);
function itemInvokedHandler(e) {
e.detail.itemPromise.done(function (invokedItem) {
if (testtrue === true){
myEdit();
}
});
};
});
In myEdit:
function myEdit() {
var theelem = document.querySelector(".win-selected #myNotes");
var gestureObject = new MSGesture();
gestureObject.target = theelem;
theelem.gestureObject = gestureObject;
theelem.addEventListener("pointerdown", pointerDown, false);
theelem.addEventListener("MSGestureHold", gestureHold, false);
function pointerDown(e) {
e.preventDefault();
e.target.gestureObject.addPointer(e.pointerId);
}
function gestureHold(e) {
if (e.detail === e.MSGESTURE_FLAG_BEGIN && test === true) {
e.preventDefault();
editNotes();
} else {
}
console.log(e);
}
theelem.addEventListener("contextmenu", function (e) {
e.preventDefault();}, false); //Preventing system menu
};
function editNotes() {
//The Code I wish to execute
return test = false;
};
What I needed was a conditional statement so that it would run if true and not if false. That same test needed to be done in the gestureHold otherwise it would continue to fire myEdit on the invoked item because of the way the gesture is attached to the item the first time it is run.

Why is my jQuery function not being called correctly?

I have this jQuery function that is using another jQuery library called html5csv.js (which explains some of the CSV stuff you will see)
Here is it:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
}
Here is how I am trying to call my function, from an onsubmit within my form:
<form method="post" action="createplay.php" onsubmit="return validateNewQuiz();" enctype="multipart/form-data">
My function has been thoroughly tested, along with my regex to make sure it was working. When I decided to implement it into my large document, and wrap it around function validateNewQuiz(){ //my function here } , it stopped working.
I did not make my tests with the onsubmit part within my form either.
Does anyone have any suggestions to why my form is always submitting, even when my function should be returning false?
The onsubmit event handler allows the submission to proceed if it is passed a true value by the validation function, and does not allow the submission to proceed if it receives a false value. In your case, the inner function is returning a true or false value, but this value is not being passed to the outer validateNewQuiz function, so the true/false result of the validation is not being passed to the onsubmit event handler. To fix this, just return the value of the CSV function.
function validateNewQuiz()
{
var csvValidation = CSV.begin("#upload_csv").go(function(e,D)
{
if (e)
{
return console.log(e);
alert("Sorry, an error occured");
}
var s = "";
for (var i = 0; i <= D.rows.length - 1; i++)
{
s +=D.rows[i].join(',');
s += "\n";
}
var fullString = s;
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
return true;
}
else
{
return false;
}
});
return csvValidation;
}
You can make a button that would be calling your function:
<button onclick="validateNewQuiz()">Submit</button>
... and submitting the form once it is validated:
function validateNewQuiz()
{
CSV.begin("#upload_csv").go(function(e,D)
{
//...
if(/^(([^,]+,){4}[^,]+\n){3}$/.test(fullString))
{
$("form").submit();
}
});
return false;
}

ajax $.get callback reported as undefined

I have defined a div within which a form with default input values is appended based on MySQL table data returned by PHP via an ajax $.get call.
The div looks like:
<div id="esfContainer1">
</div> <!--end esfContainer1 div-->
The div is absolutely positioned relative to the body tag.
The script associated to the form validation broke when it was included on the main page where the call to the form was being made, so I moved it to the PHP output $formContent.
Here is the form validation and submit script included in the PHP output:
<script type="text/javascript">
var senderName = $("#sendName");
var senderEmail = $("#fromemailAddress");
var recipientEmail = $("#toemailAddress");
var emailError = $("#esemailerrorDiv");
senderName.blur(checkName);
senderEmail.blur(checkSEmail);
recipientEmail.blur(checkREmail);
function checkName() {
if (senderName.val() == "YOUR NAME") {
$("#esemailerrorText").html("Please provide your name");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
} else {
return true;
}
};
function checkSEmail() {
var a = senderEmail.val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(a)) {
return true;
} else {
$("#esemailerrorText").html("Please enter a valid email address");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
function checkREmail() {
var a = recipientEmail.val();
var filter = /^([\w-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
if (filter.test(a)) {
return true;
} else {
$("#esemailerrorText").html("Your friend\'s email is invalid");
$(emailError).removeClass("esemailError");
$(emailError).addClass("esemailErrorNow");
$(emailError).fadeIn("fast","linear");
$(emailError).delay(2000).fadeOut("slow","linear");
return false;
}
};
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData,processEmailer).error("ouch");
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
};
return false;
};
return false;
});
I have splatter-bombed the above submit function with "return false;" because the submit function has been simply opening the processing PHP script rather than executing the $.get. Watching the submit function with Firebug reports that processEmailer is undefined.
I am very new to this. I was assuming that because the ajax callback is being defined within the submit function (and that the processEmailer function is defined directly below the ajax call) that there wouldn't be a problem with definition.
Thanks in advance for any help.
You've been trapped by function statements. Function declarations (which would be hoisted) are not allowed inside blocks (if/else/for bodies) and if they are appear there, behaviour is not defined. Firefox defines them conditionally, and in your case after you've used it in the $.get call - where it was undefined then - like in var functionName = function() {} vs function functionName() {}.
To solve this, simple put it outside the if-block (or even outside the whole callback). Btw, .error("ouch") won't work, you need to pass a function.
$("#emailForm").submit (function() {
if (checkName() && checkSEmail() && checkREmail()) {
var emailerData = $("#emailForm").serialize();
$.get("style.php",emailerData).done(processEmailer).fail(function() {
console.log("ouch");
});
}
return false;
// now a proper function declaration, will be hoisted:
function processEmailer(data) {
if (data=="fail") {
return false;
} else if (data=="pass") {
$("#c1Wrapper").fadeOut("slow","linear");
$("#confirmation").fadeIn("slow","linear");
$("#esfContainer1").delay(2000).fadeOut("slow","linear");
$("#backgroundOpacity").delay(2000).fadeOut("slow","linear");
return false;
}
}
});

How do I add a function to an element via jQuery?

I want to do something like this:
$('.dynamicHtmlForm').validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (!$(this).closest('.dynamicHtmlForm').validate()) {
return false;
}
return true;
});
And then when I have a form of class dynamicHtmlForm, I want to be able to provide a custom validate() function:
$('#myDynamicHtmlForm').validate = function() {
// do some validation
if (there are errors) {
return false;
}
return true;
}
But I get this when I do this:
$(this).closest(".dynamicHtmlForm").validate is not a function
Is what I've described even possible? If so, what am I doing wrong?
Yes, it is technically possible. You will need to reference the element itself, however, and not the jQuery collection. This should work:
$('.dynamicHtmlForm').each(function (ix,o) {
o.validate = function() {
return true;
}
});
$('.dynamicHtmlForm .saveButton').click(function() {
if ($(this).closest('.dynamicHtmlForm')[0].validate()) {
return false;
}
return true;
}
jQuery.fn.validate = function(options) {
var defaults = {
validateOPtions1 : '',
validateOPtions2 : ''
};
var settings = $.extend({}, defaults, options);
return this.each(function() {
// you validation code goes here
});
};
$(document).ready(function() {
$('selector').click(function() {
$('some selector').validate();
// or if you used any options in your code that you
// want the user to enter. then you go :
$('some selector').validate({
validateOPtions1: 'value1',
validateOPtions2: 'value2'
});
});
});
You're not adding the function to the element, you're adding it to the jQuery wrapper around the element. Every time you pass a selector to jQuery, it will create a new wrapper for the found elements:
$('#myEl'); // gives a jQuery wrapper object
$('#myEl'); // creates another jQuery wrapper object
If you save the wrapped element to a variable and use that later, it would be a different story because you're accessing the saved jQuery wrapper object.
var dynamicHtmlForm = $('.dynamicHtmlForm');
dynamicHtmlForm.validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (dynamicHtmlForm.validate()) {
return false;
}
return true;
}
You could also add the function directly to the element using
$('.dynamicHtmlForm')[0].validate = function () { return true; }
// and later...
if (!$(this).closest('.dynamicHtmlForm')[0].validate())
Or you could look at extending jQuery properly by writing a plugin.

Categories

Resources