Pass a flag from one event to another in Jquery - javascript

If I have a Text Input field in a form with id say "input_id". During loading the page I would populate the field with existing data
While submitting the form using a button of id "form_submit", I want to determine if the field has been altered in any way. So that I would take particular action pertaining to the change.
In Jquery:
$("#input_id").on("keyup",function(){
//set a flag to indicate the field is altered
})
$("#form_submit").on("click",function(){
//check flag to see if #input_id is changed
}
So how do I set a flag in one event, and read it in another without using a global variable ?
Thanks in advance

One option would be to use the form data attribute:
$("#input_id").on("keyup",function(){
//set a flag to indicate the field is altered
$(this).closest('form').data('changed',true);
})
$("#form_submit").on("click",function(){
//check flag to see if #input_id is changed
console.log($(this).closest('form').data('changed'));
}

You can use .data() for this purpose,
var submit = $("#form_submit");
$("#input_id").on("keyup",function(){
submit.data("changed",true);
});
submit.on("click",function(){
if($(this).data("changed")){ //do something }
}

So why not just an upper scope flag?
var flag = false;
$("#input_id").on("keyup",function(){
// check stuff ...
flag = true;
});
$("#form_submit").on("click",function(){
if (flag) {
} else {
}
}

Related

ServiceNow show button if condition is true

I am trying to build a Client Script in ServiceNow - Geneva (function onChange), that does the following:
-> If the user writes something in an empty field a button should appear after change;
This is my code now, it doesn't work -> gives me an X on the form :):
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
//Define the variable and the name of the button
if (g_form.getValue('work_around') != ''){
var items = $$('BUTTON').each(function(item){
if(item.innerHTML.indexOf('Publish Known Error')=== -1){
item.show();
}
});
}
}
Instead of a Client Script, I would recommend using an onChange(<your field>) UI Policy. This can be accomplished by setting a Condition of your field not being NULL or some other value check.
Your UI Policy can then use the .append function to bind your button to an element of your choice.

How to save a value to localstorage from a select menu as soon as u select the option? It is not working

I have the following, but I keep getting a return value of null instead of the value I was trying to store. Here is my code:
function mySelectValue() {
// Add an event listener for the value
document.getElementById('mySelectValue').addEventListener('change', function() {
// Get the value of the name field.
var mySelectValue = document.getElementById('mySelectValue').value;
// Save the name in localStorage.
localStorage.setItem('mySelectValue', mySelectValue);
});
}
However when I try to retrieve the value, it is null which I think means that the value was not stored.
Basically, as soon as I select the option (not submit it yet), I want it to be stored in localstorage. Also I want it to overwrite the value if I change my selection.
If you allowed to use jQuery, try this:
$(document).ready(function(){
$('#mySelectValue').change(function(){
localStorage.setItem('mySelectValue', $(this).val());
});
});
You have problem somewhere else this code works you can check it here: FIDDLE

Disable Inputs on Dropdown Change

So I'm working on a webform right now and I need to disable all forms of input once one has a specific value. Is there an easy way to handle as soon as that dropdown gets to that value?
Currently I'm doing this:
setInterval('check()', 5000);
function check() {
// Disable all fields if the answer was no.
if ($("#has_contract").val() == 0) {
disable();
}
function disable() {
$("#inputs *").prop('disabled', true);
alert("There is no contract, please get a contract.");
}
has_contract is my element, and #inputs contains all of the inputs I would like to disable if #has_contract's value is 0.**
But this isn't ideal.
Is there a better way to do this rather than constantly checking every X amount of seconds?
Instead of checking for the value every 5 seconds, you can check the value on change.
// collect elements
var $hasContract = $("#has_contract");
var $inputs = $("#inputs input");
// on change, check the input
$hasContract.on('change', checkForm);
// Checks the hasContract input for a value
// of 0. If it does, disable the form.
function checkForm() {
if($hasContract.val() == 0) {
$inputs.attr('disabled', true);
}
}
Also, when you use setTimeout, or setInterval you don't have to use a string. Javascript supports passing functions as variables. See below.
// Do NOT do this
setInterval('check()', 5000);
// Do this instead
setInterval(check, 5000);
// or this
setInterval(function() {
//preform the check...
}, 5000);
I'm not completely certain that I understand your requirements, but would this work for you?
The below assumes that #has_contract is a <select> element:
$("#has_contract").change(function() {
if ($("#has_contract").val() == 0) disable();
});
First off, you should cache the elements as a variable and then run the function against that variable.
var myInputs
$(document).ready(function(){
myInputs = $("#inputs input"); // or '#inputs *' if you're excited about the asterix
});
Second thing, if I'm reading your setup correctly, you're going to pop an alert box every 5 seconds until the user has selected 'yes' to the contract. That will get QUITE annoying and they probably won't want to open a contract with you after that.
Without actually seeing your page, I'd imagine a better solution would be to check for the contract=yes when the click a submit button of some sort on the page.
$('#mySubmitButton').click(function(){
if ($("#has_contract").val() == 0) {
disable();
}
});
But maybe go one step further, what you really want to do is give them access to the form once they agree to the contract. So you should have the form disabled by default (coded into the html that everything is disabled), and attach a function to the 'yes' button that enables the form. Additionally, you can attach a function to the 'no' button that re-disables it, if they had previously clicked 'yes'.
$('#myYesBtn').click(function(){
myInputs.prop('disabled', false);
});
$('#myNoBtn').click(function(){
myInputs.prop('disabled', true);
});

How can I make this username suggestion work in javascript?

I have an application that requires both first name and last name. I need to have the username field automatically fill up as the user types in their first and last names to suggest a username. Right now, it works to a degree. This is the function that executes on a keyup for the name fields.
suggestUsername: function() {
var username = this.$('#user_login_field').val();
var first = this.$('#user_first_name_field').val();
var last = this.$('#user_last_name_field').val();
if(first == '' && last == ''){
this.$('#user_login_field').val('');
} else {
this.$('#user_login_field').val(first+'.'+last);
}
},
This works unless the user adds something to the username manually and then goes back to one of the name fields and enters something else. In the case that that happens, whatever the user added manually disappears. Not sure how to go about fixing it
Add an jQuery focus handler to the #user_login_field that unbinds the keypress events from the first and last name fields. (http://api.jquery.com/focus/)
$('#user_login_field').focus(function (e) {
// Unbind the keyup events
$('#user_first_name_field').unbind('keypress');
$('#user_last_name_field').unbind('keypress');
});
you can add a
$('#user_last_name_field').blur(function(){
//do username suggestion
})

Check the form has saved or not in CRM 2011 Javascript

I'm writing a Javascript to call external link on click of custom ribbon button in CRM 2011 entity form. In javascript I'm checking the form is dirty or not. If the form is dirty,(means some fields are modified by user) then JScript will save the form forcefully using Xrm.Page.data.entity.save(). But, when the mandatory fields have not filled, force save will not be happened and I have to show some custom message to fill those fields, terminate the flow of control and should not open the external link. How to get whether the form has saved or not..?
Piece of code as below:
function buttonOnClick() {
if (Xrm.Page.data.entity.getIsDirty())
{
Xrm.Page.data.entity.save();
}
else
{
window.open('http://www.google.com', 'name', 'width=900,height=800');
}
}
When you say 'form has been saved' do you mean for the first time? If so you can query the form type:-
Xrm.Page.ui.getFormType();
(Is it in Create or Update for example). If the form is already in Update mode then you can check if the form is dirty as you say. If you want to know which mandatory fields have not been completed you can also potentially loop over the attributes on the form and query whether they are Business Required or not:-
Xrm.Page.data.entity.attributes.get("myAttribute").getRequiredLevel();
and add this to a warning message to the user.
You could add your own OnSave method to validate the fields and return a value based on whether they are valid or not.
e.g.
Xrm.Page.data.entity.addOnSave(function() {
var isValid = VerifyOnSave();
if (isValid) {
//continue
}
else {
//show errors, cancel save
}
);
function VerifyOnSave()
{
//<insert validation logic here>
return true;
}
That doesn't explicitly tell you the form saved, but lets you know whether the form is valid, which may or may not be close enough.
You could try this way:
var entitySaved;
function OnLoad(){
entitySaved=false;
}
function OnSave(){
entitySaved=true;
}
function myFunction(){
if(entitySaved){
//do your logic here
}
}
Of course, you will have to add the form events from your CRM solution, by clicking in form properties.

Categories

Resources