Editable Subgrid setting the required field from onchange event broken - javascript

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

Related

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.

Mvc Telerik grid cancel cell changes when input invalid

I am facing a small problem regarding input validation in mvc telerik grid.
I have it set to batch editting and I'm modifing the cells in an InCell mode.
Now whenever a user enters an invalid value in one of the inputs(Telerik's comboboxes/autocompletes), I'd like to display a message that
the entered value is iligal(this far I've managed on my own).
In addition to the message I'd like to revert the cell's value to it's previus value before
the user input.
So far I've tried:
grid.CancelCell(this);
$('#grid .t-grid-edit-cell input[type="text"]').value or innerText = prevVal;
The closest so far was e.newVal = e.oldVal, although it sometimes throws me a wierd exception in the jquery scripts or displays the combobox's drop down.
All the validatios and things I've tried are from the grid's client event OnSave()
It's same like what i searched before and I have solution for you.
On your OnSave() method has event like OnSave(e) and that 'e' carry all the elemnts and functions inside in my example after validation if not ok i can change that value to old value. Also you can use inspecter element log to look up what is inside 'e'
function onSave(e){
if(!validation)
{
///
}
else
{
e.cell.firstChild.value = "0"; // that is my edited cell
}
}

overriding data-confirm values

I want to change the value of data-confirm attribute on a button (submit) based on user's choices on a form. I put the following on the change function of a dropdown list:
...
if($("#"+select_name).val() == "abc")
{
$(".variable_button").attr("data-confirm","abc is good choice!");
} else
{
$(".variable_button").attr("data-confirm","abc would have been great but this is fine too...");
}
...
The problem I am facing is that apparently data-confirm cannot be changed once it is assigned a non-empty string. I have it set to "" in the server code. And, it changes to one of the two messages shown above when the user first makes a selection on the dropdownlist. But if the user changes the selection one more time, the data-confirm message does not change. Is this per design or am I missing something?
Don't use .attr(), use .data():
var newData = ($("#"+select_name).val() == "abc")
? "abc is good choice!"
: "abc would have been great but this is fine too...";
$(".variable_button").data("confirm", newData);
jQuery does allow you to update a data- attribute with the .attr() method, so something else is breaking.
Here's a working example (JSFiddle):
var counter = 1;
$('#click').click(function() {
button = $('#click');
console.log(button.attr('data-confirm'));
button.attr('data-confirm', 'this is test ' + counter);
console.log(button.attr('data-confirm'));
counter++;
});
Can you try to repo the issue in a JSFiddle?
On rereading your question, it sounds like an event handler isn't firing the second time the user changes the selection. See if you can set a breakpoint in your event handler to see if it even gets hit.

JavaScript: True form reset for hidden fields

Unfortunately form.reset() function doesn't reset hidden inputs of the form.
Checked in FF3 and Chromium.
Does any one have an idea how to do the reset for hidden fields as well?
Seems the easiest way of doing that is having <input style="display: none" type="text"/> field instead of <input type="hidden"/> field.
At this case default reset process regularly.
This is correct as per the standard, unfortunately. A bad spec wart IMO. IE provides hidden fields with a resettable defaultValue nonetheless. See this discussion: it's not (alas) going to change in HTML5.
(Luckily, there is rarely any need to reset a form. As a UI feature it's generally frowned upon.)
Since you can't get the original value of the value attribute at all, you would have to duplicate it in another attribute and fetch that. eg.:
<form id="f">
<input type="hidden" name="foo" value="bar" class="value=bar"/>
function resetForm() {
var f= document.getElementById('f');
f.reset();
f.elements.foo.value= Element_getClassValue(f.elements.foo, 'value');
}
function Element_getClassValue(el, classname) {
var prefix= classname+'=';
var classes= el.className.split(/\s+/);
for (var i= classes.length; i-->0;)
if (classes[i].substring(0, prefix.length)===prefix)
return classes[i].substring(prefix.length);
return '';
}
Alternative ways of smuggling that value in might include HTML5 data, another spare attribute like title, an immediately-following <!-- comment --> to read the value from, explicit additional JS information, or extra hidden fields just to hold the default values.
Whatever approach, it would have to clutter up the HTML; it can't be created by script at document ready time because some browsers will have already overridden the field's value with a remembered value (from a reload or back button press) by that time that code executes.
Another answer, in case anyone comes here looking for one.
Serialize the form after the page loads and use those values to reset the hidden fields later:
var serializedForm = $('#myForm').serialize();
Then, to reset the form:
function fullReset(){
$('#myForm').reset(); // resets everything except hidden fields
var formFields = decodeURIComponent(serializedForm).split('&'); //split up the serialized form into variable pairs
//put it into an associative array
var splitFields = new Array();
for(i in formFields){
vals= formFields[i].split('=');
splitFields[vals[0]] = vals[1];
}
$('#myForm').find('input[type=hidden]').each(function(){
this.value = splitFields[this.name];
});
}
You can use jQuery - this will empty hidden fields:
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).val('');
});
Tip: just make sure you're not resetting csrf token field or anything else that shouldn't be emptied. You can narrow down element's specification if needed.
If you want to reset the field to a default value you can use(not tested):
$('form').on('reset', function() {
$("input[type='hidden']", $(this)).each(function() {
var $t = $(this);
$t.val($t.data('defaultvalue'));
});
});
and save the default value in the data-defaultvalue="Something" property.
I found it easier to just set a default value when the document is loaded then trap the reset and reset the hidden puppies back to their original value. For example,
//fix form reset (hidden fields don't get reset - this will fix that pain in the arse issue)
$( document ).ready(function() {
$("#myForm").find("input:hidden").each(function() {
$(this).data("myDefaultValue", $(this).val());
});
$("#myForm").off("reset.myarse");
$("#myForm").on("reset.myarse", function() {
var myDefaultValue = $(this).data("myDefaultValue");
if (myDefaultValue != null) {
$(this).val(myDefaultValue);
}
});
}
Hope this helps someone out :)
$('#form :reset').on('click',function(e)({
e.preventDefault();
e.stopImmediatePropagation();
$("#form input:hidden,#form :text,#form textarea").val('');
});
For select, checkbox, radio, it's better you know (hold) the default values and in that event handler, you set them to their default values.
Create a button and add JavaScript to the onClick event which clears the fields.
That said, I'm curious why you want to reset these fields. Usually, they contain internal data. If I would clear them in my code, the post of the form would fail (for example after the user has entered the new data and tries to submit the form).
[EDIT] I misunderstood your question. If you're worried that someone might tamper with the values in the hidden fields, then there is no way to reset them. For example, you can call reset() on the form but not on a field in the form.
You could think that you could save the values in a JavaScript file and use that to reset the values but when a user can tamper with the hidden fields, he can tamper with the JavaScript as well.
So from a security point of view, if you need to reset hidden fields, then avoid them in the first place and save the information in the session on the server.
How I would do it is put an event listener on the change event of the hidden field. In that listener function you could save the initial value to the DOM element storage (mootools, jquery) and then listen to the reset event of the form to restore the initial values stored in the hidden form field storage.
This will do:
$("#form input:hidden").val('').trigger('change');
You can reset hidden input field value using below line, you just need to change your form id instead of frmForm.
$("#frmForm input:hidden").val(' ');

I need help understanding a simple JavaScript script

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".

Categories

Resources