I have a GridView with textboxes in its cells. I need to call a javascript function when the user changes the contents of a TextBox, and then hits Enter or leaves the TextBox. The latter is achieved by doing onchange="MyJavascriptFunc", but the javascript function is not called when Enter is pressed. If I call the javascript function from EnterKeyPressHandler function, MyJavascriptFunc is called twice, which I would prefer to avoid.
Could you please help me with this?
Thanks.
Check if the func is called when the user presses enter.
var called = false;
if(called != true)
{
called = true;
// and do sth
}
called = false;
Related
I have a working Active Form, which can be submitted, and validated via Yii PHP. However, I would like to determine if the form is valid, when clicking a Next button.
I can pass error messages to the user via this:
$("#form").yiiActiveForm("validate", true);
But this function doesn't return anything; I don't know if there are indeed any errors or not. I tried this:
$error_count = document.getElementsByClassName("help-block").length
but this does not work; the errors are counted before the UI has updated. If I press the button again, a second time, then error_count is what I'd expect.
This doesn't seem to do anything:
$("#form").yiiActiveForm("validate");
I also tried this:
$('#form').on('afterValidate', function (event, messages, errorAttributes) {}
But this is only triggered after the fact so I'm not sure what to do.
Any advice would be appreciated.
If you need to react to button you simply need to combine both events:
let isNextClicked = false;
$('.next-btn').on('click', function(e) {
e.preventDefault();
isNextClicked = true;
$("#form").yiiActiveForm("validate", true);
});
$('#form').on('afterValidate', function(event, messages, errorAttributes) {
if (!isNextClicked) {
//validation wasn't triggered by clicking next
return;
}
// reset the state
isNextClicked = false;
if (errorAttributes.length > 0) {
//there are errors so we won't let user to continue
//we can also show some alert() here
return;
}
// ... code to show the next tab of form ...
});
I want to know if this is a proper usage of the .blur function, since I have a larger code with many validations and a .blur for each one and does not work, maybe I'm doing it wrong. I will comment how I understand it.
$(document).ready(myFunction); //.ready function runs myFunction
//"userinfo" is a text field that when loses focus it runs validateuser function
function myFunction(){
$("userinfo").blur(validateuser);
}
function validateuser(){
var user = $("#userinfo").val(); //variable stores data input from the user
//validates that the user contains text only, showing messages accordingly
if(/^[a-zA-Z]+$/.test(user)){
$("#msg").html("The information is correct.");
}else{
$("#msg").html("The information is not correct");
}
}
JavaScript :
function validateuser(){
var user = $("#userinfo").val();
if(/^[a-zA-Z]+$/.test(user)){
$("#msg").html("The information is correct.");
}else{
$("#msg").html("The information is not correct");
}
}
$(document).ready(function(){
$("#userinfo").blur(function(){
validateuser();
});
});
Use this code.You can create function within $.ready() or outside.It doesn't matter.Call that validateuser() function when $("#userinfo").blur() event.
You have missed the #. check below for correction
function myFunction(){
$("#userinfo").blur(validateuser);
}
I'm trying to create a custom JavaScript variable for Google Tag Manager, and I can't seem to get the functions to run in the right order...
(As seen below:)
This is a chunk of code that was created to check whether an email form was filled out correctly or not. ValidateForm() is run when the user has entered their name and email address, and hit the 'send' button (the function EmailCheck checks whether the email address is valid or not). ValidateForm will then return either true or false. When ValidateForm evaluates to true AND the user has hit the 'send' button, I want to send an event to Google Analytics.
My approach has been to try and store the result of ValidateForm in a variable when it's run the first time, so that my additional anonymous function will evaluate to true, but I can't seem to get the syntax right and now I'm doubting this is even possible (?).
My other idea was to just run the anonymous function on onload, but that will never evaluate to true since ValidateForm is not run until the user has entered their details and hit the 'send' button... How do I make this right? Any help appreciated :)
function ValidateForm() {
var emailID = document.cpren.email
if ((emailID.value == null) || (emailID.value == '')) {
alert('Please enter a valid email address')
emailID.focus()
return false;
}
if (EmailCheck(emailID.value) == false) {
emailID.value = ""
emailID.focus()
return false;
}
return true;
}
//anonymous function
function () {
var result = //the result of ValidateForm when it was run when user hit the 'send' button
if (result) {
return = "checkedOutTrue"
} }
From your question, I think you essentially want to validate your form. To do this part I would just use a standard Custom HTML tag which is fired on page load (DOM ready probably). If you want to be able to fire certain tags when a valid (or invalid) form is submitted, then you should push custom events on to the dataLayer as appropriate.
You probably want to do the following, create a new custom HTML tag with the following code. This code will bind a function to the 'submit' event of your form:
$('#myform').on('submit', function(){
function ValidateForm(){
var emailID = document.cpren.email;
if ((emailID.value == null) || (emailID.value == '') || EmailCheck(emailID.value) == false) {
alert('Please enter a valid email address');
emailID.focus();
dataLayer.push({'event':'form-submitted', 'status':'fail', 'error':'invalid email'});
return false;
}else{
dataLayer.push({'event':'form-submitted', 'status':'success'});
return true;
}
}
});
With this code, you always get a custom event in the dataLayer to tell you when a form has been submitted and you then have dataLayer items to tell you the status of the submission and an error code if it's failed.
You can then build a trigger to fire off of the form-submitted event and populate variables to understand the status and then fire tags accordingly.
The problem I am finding with custom javascript variables in GTM is that they are executed at all phases during the page load. Not just on the triggers where you want them to be executed and the order that they are executed cannot even be set.
So I think you will need to re-evaluate your approach.
to be more specific, when we submit our empty form which should have information in it should submit an alert saying "please enter a value" it does this but then after selecting okay on the alert it still sends the email on submit. I want it that if there's an error they must fulfill the requirements of the form before the email on submit can be sent. the code is:
this checks to see if there's any values in the fields
function notEmpty(elem, helperMsg) {
if (elem.value.length >= 2) {
return true;
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
the start of the form:
<form method="get" onsubmit="notEmpty();" action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
the submit button:
<input type="submit" name='Submit' value="Send" onClick='notEmpty();'>
any insight to our problem is most welcome!
There are several reasons this will fail.
The first one you will encounter is, because you don't pass any arguments when you call notEmpty, the variable elem will be undefined. When you try to access a property (value) on it, an exception will be thrown and the function will stop.
Let's take this from the top.
First, we'll use a more modern method to apply the event handlers.
Provide a means to identify the form you want to deal with. An id attribute is a good general choice (but use a more meaningful name then I am):
<form id="myForm"
method="get"
action="http://www.censoredgaming.co.uk/cgi-bin/mailer.pl">
Next, get a reference to the form in the DOM and add an event listener to it:
document.getElementById('myForm').addEventListener('submit', notEmpty);
Note that you have to do this after the form has been added to the DOM. The easiest way to achieve this is to place your <script> after the </form> (just before </body> is a popular place). You can also use an event handler that fires when the DOM is ready or the document has loaded.
Old versions of Internet Explorer don't support addEventListerner, if you want to support them see the MDN documentation which has a compatibility routine.
Next, update the notEmpty function. Since it is an event handler, it will get one argument - an event object. It will also be called in the context of the element to which is is bound (the form).
function notEmpty(event) {
var aForm = this;
}
You want to check that some element has a value of a certain length, but there is no sign of such an element in your question. Let's work with this example:
<label> Some data <input name="example"></label>
You can reference the element through the form's elements collection:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
}
Now you can add your test:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
} else {
}
}
If you don't want the form to submit, then prevent the default action on the event:
function notEmpty(event) {
var aForm = this;
var input = aForm.elements.example;
if (input.length >= 2) {
// At least two characters, all is well
} else {
alert("An error");
input.focus();
event.preventDefault();
}
}
Your first return true should be removed :P
I have a javascript method for validating a form. But under a certain condition, control should stop the script and allow the user to save a form.
Will 'return' keyword work here?
if(matchSearch==null)
{
alert('Mismatch in Subsidiary and Year. Stopping script to allow form submission.');
return;
}
The idea is, if matchSearch == null, script should stop and user should be allowed to save the form.
If you're saying that you have a function that has been assigned as an onsubmit handler, i.e., the function is called when the user tries to submit, then return; as in your example will stop execution of the function and allow the submission to continue.
Any return statement will exit from the current function. The value that you return might matter depending on how the submit handler was assigned: return false; from an inline onsubmit="" attribute will prevent the form from being submitted. Your return; statement without a value implicitly returns undefined which won't prevent submission.
If you want to check form fields before the the form is submitted, the (submit) handler function that does the check should return false. That way the submit is cancelled, and the form stays on the screen, retaining the values a user already typed. Something like:
function checkValues(){
//check values
if (/*return value of the check is wrong*/){
// save form functionality
return false
}
// check ok
return true;
}
yourform.onsubmit = checkValues;
See this jsfiddle for a very basic example
Alternatively you can also program a 'listener' function that checks the contents of every form field periodically. You can find an example in this jsfiddle. It is designed to show a submit button only if all fields have valid values.
Using return false; will stop the execution of the script.