I need help understanding a simple JavaScript script - javascript

if(document.frmMain.POL_NO.value == "")
{
alert("Select Policy Number");
document.frmMain.ENDT_NO.value="";
document.frmMain.POL_NO.focus();
return false;
}
Can anyone explain the above code to me? I am new to Javascript.

It appears to be a bit of validation code to make sure a user has entered a value for an item referred to as "Policy Number". It is the sort of code that gets called when submitting a form to check that the values the user has entered are valid.
In detail:
if(document.frmMain.POL_NO.value == "")
Only run this code if the item called in POL_NO the form called frmMain doesn't have a value yet.
alert("Select Policy Number");
Display a message to tell the user that they need to enter a value.
document.frmMain.ENDT_NO.value="";
Set the ENDT_NO item of frmMain to a blank value.
document.frmMain.POL_NO.focus();
Set the focus to the POL_NO item (the same as the user tabbing to it or clicking on it).
return false;
Return false to the code that called the function that this code is in. If this code is used in the event handler for the submit button on a form then returning false will stop the form from being submitted to the server until the POL_NO item has a value.

If the contents of the item POL_NO from the form frmMain is empty, then throw an alert and change the value of the ENDT_NO item value to nothing (empty) and after that focus on the element POL_NO. Return false after that (I assume this code executes at onSubmit event, so the form won't be submitted if POL_NO doesn't have a value)
Probably the logic is that the ENDT_NO can't have a value if POL_NO is empty.
Enjoy!

document.frmMain is a form in the page, and POL_NO and ENDT_NO are fields in the form, presumably listboxes.
This code is a simple validation script to make sure you filled out the form correctly.
//if POL_NO hasn't been set (no policy number selected):
if(document.frmMain.POL_NO.value == "")
{
//show a message box
alert("Select Policy Number");
//clear the value (if any) of ENDT_NO
document.frmMain.ENDT_NO.value="";
//set the form focus to POL_NO (select it, as if you had clicked on it)
document.frmMain.POL_NO.focus();
//stop the form from being submitted
return false;
}
I'm assuming this code is part of a function which is called by frmMain's onSubmit event (and event handler) -- when the function returns false the submit is cancelled. Were this not here, it would show the message box, clear ENDT_NO, select POL_NO and then submit anyways.
Note that referencing members of a form in the document.formName.fieldName.property fashion is deprecated. The correct way is to use getElementById or a similar function:
document.frmMain.ENDT_NO.value = ""; //bad
document.getElementById("ENDT_NO").value = ""; //correct

HTML document
your HTML document has this defined somewhere in its content
<form id="frmMain" ...>
<input type="..." id="POL_NO">
<input type="..." id="ENDT_NO">
</form>
SCRIPT code
So. Your script checks whether your POL_NO input field has a value.
If it doesn't (it's an empty string),
it displays an alert (information window) and
empties ENDT_NO field's value and
puts focus on the POL_NO field - so the user can immediately start selecting/typing a value in this field
returns false - probably to cancel form submission
Business logic
Based on the logic of this script, the business process obviously doesn't allow any value in ENDT_NO field, until there's a value in POL_NO.
Observation
If you need to change something about this code (if there's a bug in it), I strongly suggest you get to know Javascript/DOM/HTML before doing any changes.

Actually your code does a pretty simple validation, just read the code and find the fields POL_NO and ENDT_NO in your HTML output. Here is my comments :
// if your POL_NO field is empty,
if(document.frmMain.POL_NO.value == "")
{
// warn user that he need to select Policy number
alert("Select Policy Number");
// set ENDT_NO field's value to empty
document.frmMain.ENDT_NO.value="";
// set POL_NO active - focussed
document.frmMain.POL_NO.focus();
return false;
}

If the value of the input named POL_NO in the form frmMain is empty, then show a message "Select Policy Number", empty the input named ENDT_NO, give the focus to the input named POL_NO, and the exit the function with the return value "false".

Related

Editable Subgrid setting the required field from onchange event broken

We were using this snippet on an editable subgrid in a form, while one of the attribute trigger onchange event triggering this function and the necessary fields were marked as required so far. So users cannot save the editable subgrid row and autosave will also get blocked with a notification message.
Suddenly it stopped working now and no errors or exceptions while debugging, though the field is marked as required from onchange function - still users are able to save the record without value in required field. No clue why this behavior change is observed now.
Anyone else faced this issue and any workaround for this?
function ReasonChange(eContext) {
debugger;
// get the attribute which fired the onchange.
var reasonAttr = eContext.getEventSource();
// get the container for the attribute.
var attrParent = reasonAttr.getParent();
// get the value of the reason.
var reason = reasonAttr.getValue();
if (reason != null) {
// var field1 Attribute
var field1 = attrParent.attributes.get("new_followupdate");
//Callback
if (reason[0].id == "{33E9E459-5A8B-EA11-A812-000D3A5A17E3}") {
// set field as mandatory.
field1.setRequiredLevel("required");
}
else {
//clear field value
field1.setValue(null);
// set field as mandatory.
field1.setRequiredLevel("none");
}
}
One workaround i could think now is to add code on Onsave event and check if field value contains data if not show error message.
Also, have you checked in other browser if the behavior is same or different?
Please mark my answer verified if i were helpful

jQuery form validation. How to prevent error messages appearing multiple times

I'm trying to validate a form in jQuery. I have it working, with 1 issue. If i click the submit button twice, the error messages will show twice, stacked on top of eachother.
EG
Name must not be empty
Name must not be empty
//Form Validation
//Store checkbox, and checkbox label in jQuery object
$terms = $('#terms');
$termsdoc = $('#terms-doc');
//Check if pet name is empty
if($name.val() == '')
{
$name.after('<p class="error">Name must not be empty</p>')
}
if($terms.is(':not(:checked)'))
{
$termsdoc.after('<p class="error">Please agree to the terms and conditions</p>')
}
Using .last() just adds the desired content as the last child of the target selection, so what you're seeing is a duplicate element being added.
SOLUTION:
You could target <p> tags with the class "error" and remove them before you add them with .last():
$("p.error").remove();
You could also disable the submit button in the handler. $(".submit").prop("disabled",true);
This would prevent duplicate submissions.

Jquery Issue in Appending Text to a label

I was doing validations for input fields using Jquery by just checking if a value is supplied for the fields or not.
In case there is NO value supplied, I just used to Append Text: "Duration:*Required" to the Field's "Label" controls as:
$('label[for="Duration_Value"]').Append(" Duration:* Required");
The problem is that for the very first time, if a user doesn't selects a value for the "Duration" dropdown, error message displays fine.
But, again , without selecting any value, if the Submit button is subsequently clicked, the Error Message: "Duration:* Required" keeps adding at end as seen below:
Which Jquery function shoul be used to change Text / error message displayed so that no matter how many times submit button clicked, Error message don't add up as above ?
Use indexOf to check if the message is already added, if not then only add the message to the label.
if ($('label[for="Duration_Value"]').text().indexOf(" Duration:* Required") === -1) {
$('label[for="Duration_Value"]').append(" Duration:* Required");
}
If value is not specified, then call this
$('label[for="Duration_Value"]').text(" Duration:* Required");
and if value is specified then clear label text like this
$('label[for="Duration_Value"]').text("");

Dynamics CRM 2011/13 - Reenable onChange event on form field when user didn´t make changes

I have a validation method for an email form field, which is called on the onchange event of the field and sets the focus back on the field, if the validation fails:
function ValidateEMail(event) {
var source = event.getEventSource();
var value = source.getValue();
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/igm;
if (value == '' || !re.test(value))
{
Xrm.Utility.alertDialog('Bitte geben Sie eine gültige E-Mail Adresse ein', null);
Xrm.Page.getControl(event.getEventSource().getName()).setFocus(true);
return false;
}
}
}
The problem is that the onchange event is not fired again if the focus leaves the field the next time and the user didn´t make any changes. Unfortunately there is no lostFocus event I could use instead. Du you have any suggestions to solve this?
You have a few options:
Revalidate onsave and block save if the field is not valid
Clear the field (set to null) and make required.
Call change from within validate email but insert a condition to avoid infinit loop.
Use text field of type email and let crm do this stuff for you.
Use jquery and add binding to lost focus event
This answer maybe a few months later but for future reference I would suggest the form field be customized as a Single Line of Text with a format option of "Email".
Setting the format option to "Email" will enable the client side validation of the user input on the field with no JavaScript required.
Here is a reference to the format options available for a Single Line of Text data type in Dynamics CRM.

Check All input text fields in form empty or not on Submission, Ignore if at least one text field is filled

Here is the situation
I have a form with many input fields in my JSP page. The number of input text fields are unknown as it is based on the previous action class.
When the form is submitting, I want to check all input text fields are empty or not. If all are empty, then it should not submit. Otherwise( in any case. ie, at least one text field must be filled), then form should submit.
The JQuery I have tried:
$('#dataFieldMapping').submit(function() {
if ($('input:text').is(":empty")) {
alert("Empty!");
preventDefault();
}
});
(dataFieldMapping is the id of form). When I click on submit, it alerts with "Empty!" always, even if all text fields are filled.
NB: My submit button is outside of form. So I was using
$('#dataFieldMapping').submit();
without validating. But I want to validate the form.
DEMO
$('#dataFieldMapping').submit(function (e) {
if (!$(this).find('input:text').filter(function () {
return $.trim(this.value) != ""
}).length) {
alert("Empty!");
e.preventDefault();
}
});
You are not calling preventDefault on event object, you need to call preventDefault on event object. The way you are trying to check that all fields are empty wont give you correct result as it will checks children not value.
:empty Select all elements that have no children (including text nodes), reference
$('#dataFieldMapping').submit(function(event) {
lst = $('input:text').filter(function(){
this.value != "";
});
if(lst.length)
{
alert("Empty!");
preventDefault();
}
});

Categories

Resources