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);
}
Related
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.
We have a requirement to refresh the form after saving (to ensure that some hide/show logic works as expected based on a field value).
Currently the form does not automatically refresh after saving the record.
I have gone through some articles and found this reference:
http://msdn.microsoft.com/en-us/library/dn481607%28v=crm.6%29.aspx
When I try to do either of the below, it results in an infinite loop and throws a 'Callstack exceeded Max limit' error.
OnSave(context)
{
//my logic
...
...
Xrm.Page.data.save.then(SuccessOnSave, ErrorOnSave);
}
function SuccessOnSave()
{
//force refresh
Xrm.Page.data.refresh();
}
function ErrorOnSave()
{
//do nothing
}
OnSave(context)
{
...
...
//force refresh
Xrm.Page.data.refresh(true).then(SuccessOnSave, ErrorOnSave);
}
function SuccessOnSave()
{
//do nothing
}
function ErrorOnSave()
{
//do nothing
}
Can someone please explain me how to use the refresh or save method to do a force refresh of the form ??
Rajesh
I use to achieve it with following code
Xrm.Page.data.save().then(
function () {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId());
},
function (errorCode, message) {
}
);
For me this is what solved the purpose (CRM 2015)
// Save the current record to prevent messages about unsaved changes
Xrm.Page.data.entity.save();
setTimeout(function () {
// Call the Open Entity Form method and pass through the current entity name and ID to force CRM to reload the record
Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId());
}, 3000);
If you want to do a hard refresh on the form data, you will likely want to do a location reload. What I've done in the past is put the refresh logic in a function that is called when the Form is loaded (after being saved). The tricky part about this is that the function can get called if the form is auto-saved in CRM 2013. You also want to take into account that you don't want to refresh the form on the first load, since this would result in an infinite reloading loop. Here's an example:
var formLoaded = false;
function formLoad() {
if (formLoaded) {
window.location = location.href;
}
formLoaded = true;
}
You have attached the OnSave() method to OnSave event. So, logically if you call save again within the same event, the calls goes recursively.
From MSDN
Xrm.Page.data.refresh(save).then(successCallback, errorCallback);
Parameter: save - A Boolean value to indicate if data should be saved
after it is refreshed.
So, you will have to pass 'false' to this method (You just need to refresh, no save is required)
As I couldn't find the complete code for this written in a 'generically' reusable way, here goes:
var triggeredSave = false;
//Attach the OnSave Form event to this OnSave function
//and select passing of context as the first parameter.
//Could instead be attached programmatically using the code:
//Xrm.Page.data.entity.addOnSave(OnSave);
function OnSave(context) {
var eventArgs = context.getEventArgs();
var preventedAutoSave = false;
//Preventing auto-save is optional; remove or comment this line if not required.
preventedAutoSave = PreventAutoSave(eventArgs);
//In order to setup an after save event function, explicitly
//invoke the save method with callback options.
//As this is already executing within the OnSave event, use Boolean,
//triggeredSave, to prevent an infinite save loop.
if (!preventedAutoSave && !triggeredSave) {
triggeredSave = true;
Xrm.Page.data.save().then(
function () {
//As the form does not automatically reload after a save,
//set the save controlling Boolean, triggeredSave, back to
//false to allow 'callback hookup' in any subsequent save.
triggeredSave = false;
OnSuccessfulSave();
},
function (errorCode, message) {
triggeredSave = false;
//OPTIONAL TODO: Response to failed save.
});
}
}
function PreventAutoSave(eventArgs) {
if (eventArgs.getSaveMode() == 70 || eventArgs.getSaveMode() == 2) {
eventArgs.preventDefault();
return true;
}
return false;
}
//Function OnSuccessfulSave is invoked AFTER a save has been committed.
function OnSuccessfulSave() {
//It seems CRM doesn't always clear the IsFormDirty state
//by the point callback is executed, so do it explicitly.
Xrm.Page.data.setFormDirty(false);
//TODO: WHATEVER POST SAVE PROCESSING YOU REQUIRE
//e.g. reload the form as per pre CRM 2013 behaviour.
ReloadForm(false);
//One scenario this post save event is useful for is retriggering
//Business Rules utilising a field which is not submitted during save.
//For example, if you implement a Current User field populated on Form
//Load, this can be used for user comparison Business Rules but you
//may not wish to persist this field and hence you may set its submit
//mode to 'never'.
//CRM's internal retriggering of Business Rules post save doesn't
//consider changes in fields not submitted so rules utilising them may
//not be automatically re-evaluated or may be re-evaluated incorrectly.
}
function ReloadForm(preventSavePrompt) {
if (preventSavePrompt) {
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
attribute.setSubmitMode("never");
});
Xrm.Page.data.setFormDirty(false);
}
Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(),
Xrm.Page.data.entity.getId());
//Another way of trying Form reload is:
//window.location.reload(true);
}
Use Mscrm.Utilities.reloadPage();
I found this post helpful in demonstrating the difference between Xrm.Page.data.refresh() and Xrm.Utility.openEntityForm(entityName, id).
TL;DR - if you want the screen to repaint, consider using Xrm.Utility.openEntityForm(entityName, id).
You can achieve by placing Modified On field on the form. And set visible by default property to false.
Use below JS to refresh the form
function refreshCRMFORM()
{
setTimeout(function () {
// Call the Open Entity Form method and pass through the current entity name and ID to force CRM to reload the record
Xrm.Utility.openEntityForm(Xrm.Page.data.entity.getEntityName(), Xrm.Page.data.entity.getId());
}, 1000);
}
Create On Change event on Modified on field and provide above function name.
Here's my code:
<script type="text/javascript">
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username() {
$("#check_username").html('<img src="images/site/ajax-loader.gif" />username avilable??').delay(5000);
var usernametotest = $('#username').val();
$.post("backend/username_available.php", { username: usernametotest})
.done(function(data) {
$("#check_username").replaceWith(data);
});
}
</script>
I use this code for checking with AJACX the availability of a username in my form.
It works perfect but just once. When an username is occupied and I change the username, no AJAX checks are done after the first one? The text "username already exists" (in the variable data), is not replaced by "username ok".
This JavaScript is added just before the </html> tag.
Your code looks fine - see this jsfiddle with an alert on the usernametotest value for more visibility
$(document).ready(function() {
$('#username').change(check_username);
});
function check_username(){
$("#check_username").html('username avilable??').delay(5000);
var usernametotest = $('#username').val();
alert('posting username ' + usernametotest);
$.post("backend/username_available.php", { username: usernametotest} )
.done(function(data) {
$("#check_username").replaceWith( data );
});
}
The post requests are being made every time with the correct payload, so no problems there (check browser developer tools e.g. Network tab / XHR in Chrome)
Must be an issue with the response coming back from backend/username_available.php? Check the response of the first request vs the rest, and the difference and hence the problem will probably jump out at you.
Whenever you replace an element... and here you do just that...
$("#check_username").replaceWith( data );
all those element's handlers are lost. So change() no longer works. To be able to use it again, you just need to bind again the element after it has been rewritten:
$('#username').change(check_username);
Or bind the handler to a parent and delegate it:
$('#username').parent().on('click', '#username', check_username);
(I feel that a class selector would work better - call it superstition on my part)
You could try this:
$('#username').on('change', function() {
// write your code here
});
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 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;