How to repopulate form variables? - javascript

I've got a page that should warn if the user tries to leave the page having unsaved data. This dialog means "You have unsaved data. Do you want to conitnue?"
The problem is that the form values go blank when the user clicks a link to move on and is presented with the dialog. I want to form values to stay in place so that the user actually can choose not to continue and then still have left what was entered to the form.
The way the code is now is that it keeps a flag for whether the form has dirty data and that is a hidden variable:
<input type="hidden" name="saveStatus" value="<%=saveStatus%>" />
Touching the form sets this hidden variables with onclickand onkeypressed.
On the server I've got some logic that checks whether data is dirty:
public boolean returnToUnsavedData(ISessionHandler sessionHandler,
Action action) {
String saveStatus = sessionHandler.getRequestParameter("saveStatus");
if (saveStatus != null && !saveStatus.trim().equals("")) {
setHasUnsavedData(true);
} else {
setHasUnsavedData(false);
}
if (hasUnsavedData()) {
if (!"menuHasUnsavedDataOk".equalsIgnoreCase(action
.getActionCommand())
&& !action.getActionName().equals("Administrera")) {
ResourceBundle messages = ResourceBundle.getBundle("messages");
UserMessage um;
if (action.getActionCommand().equals("fastsearch")) {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand(), sessionHandler.getRequest().getParameter("fastsearch"));
} else {
um = new ExtendedUserMessage(
messages.getString("PV24"), UserMessage.TYPE_WARNING,
"Varning", action.getActionName(),
action.getActionCommand());
}
action.addUserMessage(um);
action.setReturnPage(action.getCurrPage());
setLatestActionTarget(action.getActionTarget());
return true;
} else {
setHasUnsavedData(false);
}
}
return false;
}
I suppose this is where I could check serverside for the variables and repopulate everything and then use a technique like above with the hidden variable to keep form values.
Do you think that this idea will work or can you present alternative solutions?

I don't think you need server-side involvement here, you can achieve this by using just javascript:
<input type="hidden" id="saveStatus" name="saveStatus" value="<%= saveStatus %>"/>
Register an observer before the page gets unloaded and check your saveStatus variable in there:
window.onbeforeunload = function() {
if (document.getElementById('saveStatus').value) {
return 'You have unsaved changes, are you sure you want to leave the page?');
}
};
However, by using this you will not have your own 'custom' confirmation screen, the browser's built in confirmation will be used (similar to stack-overflow's).

Related

Check checkbox and set value on load content/page

I have a some shop. In cart (when usually user is not logged) is checkbox for set Invoice. If is not checked - then user get a bill.
On next step, user has to login, and goes to Procced page. When user goes ahead (after login page), can't change checkbox without back to cart.
I need to check (after login, on procced page) Customer is Company or normal user (private) and if user is Company, set the invoice as default.
I have that code:
(I know is not pure php - is some kind of framework)
<!-- CART PAGE with checkbox -->
<div id="additionalRealizationInfo">
?{foreach system.cart.optionsData option}
<label>
<input class="additionalRealizationInfoCheckbox"
type="checkbox"
?{if true == option.option.enabled}
checked="checked"
?{endif}
name="additional?{=system.randomNumber}"
value="${system.controllerUrl}ToggleOption/?{=option.name}" />
?{=option.title}
</label>
?{endforeach}
// The Value of checkbox is: toggleOption/facture
<!-- PROCCED PAGE without checkbox - On this page, after login, user see own choice from cart before login -->
<div id="additionalRealizationInfo">
<h2>Infos</h2>
<div>
?{foreach system.cart.optionsData option}
<div>
?{if true == option.option.enabled}
You get Invoice
?{else}
You get recive
?{endif}
</div>
?{endforeach}
</div>
</div>
<script type="text/javascript">
var isCompany = "?{=system.userLogged.InvoiceData.company}"; <!-- Company Name -->
var enableInvoice = "?{=system.cart.invoiceEnabled}";
if (isCompany.lenght > 0) {
$.get("${system.controllerUrl}setInvoiceEnabled",function(resp) {
$.get("${system.baseUrl}view/enableinvoice",function(resp) {
$("#additionalRealizationInfo").html(resp);
});
});
$.get("${system.controllerUrl}toggleOption/facture",function(resp) {
});
};
</script>
// string to check choice: ?{if system.cart.invoiceEnabled}
// system.baseURL/view/enableinvoice is some code to show, that invoice is set default (when script works)
What's wrong. It doesn't work
At first glance, I'd examine this line of code:
if (isCompany.lenght > 0) {
You've misspelled length. Try this:
if (isCompany.length > 0) {
OR, depending on if the value of the "isCompany" variable is true/false, you could write it as
if (isCompany) { // check boolean value instead
Hope that helps!
I change the script and it works, but only after I reload/refresh a page.
<!-- CART PAGE before and after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
var klik = $("#additionalRealizationInfo>label:first-child>input:checkbox");
if (companyCustomer) {
klik.prop('checked', true);
klik.prop("disabled", true);
klik.css('cursor','default');
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // End if (companyCustomer)
<!-- PROCEED PAGE after login -->
var companyCustomer = "?{=system.userLogged.InvoiceData.company}";
//If user is logged, companyCustomer has a value. If not = ""
var enableInvoice = "?{=system.cart.invoiceEnabled}";
// If true = "1" , If false = "". That's not a boolean string.
if (companyCustomer) {
if (enableInvoice) {
} else {
$.get("${system.controllerUrl}toggleOption/facture",function(resp){
console.log(resp);
});
}; // end if (enableInvoice)
}; // end if (companyCustomer)
How it execute on load, and dynamically change/set this toggle option?
When I didn't check the checkbox in CART PAGE, go next to login, and automatically go to PROCEED PAGE I get
enableInvoice = "";
I tried .ready and .load() and .live() and nothing works. Tried execute by .click but I don't want this method. I don't want to also refresh page after content shows up.

The form is always invalid when I erase previously saved date with angular-datepicker

This problem is pretty hard to explain, but I'll try.
1) I fill the form and set a value in datetime field via angular-datepicker.
2) Press submit button. Form passes validation, everything is ok, the form was submitted and saved on server.
3) I want to edit previously completed form. I open form again and see previously saved results. If I erase the value from datetime field I can't submit the form any more. When I press submit button, nothing happens, no alerts, or errors. I can only see while debugging that operationsClientForm.$valid is false.
Important info:
1) If I just change the value of datetime, but will not erase it, everything will be ok. Issue happens only when I erase the value.
2) If I didn't fill the datetime field first time the form will be submitted. Issue happens only when I fill datetime filed first time and then erase it, while editing.
3) It is definitely client-side error.
Code samples:
<md-input-container class="md-block defaultInput deskInput">
<input type="text" date-time ng-model="client.date_of_birth" auto-close='true' timezone="UTC" format="DD.MM.YYYY" min-view="date" template='views\controls\datepicker.tpl.html' pattern="^(\d{2}).\d{2}.(\d{4})$">
</md-input-container>
$scope.saveClick = function (operationsClientForm) {
if (operationsClientForm.$valid) {
//submitting
}
}
<md-button class="md-raised rightAlign operationButton" ng-click="saveClick(operationsClientForm)" type="submit">
<translate>Save</translate>
</md-button>
So I found the probably reason of problem. When we erase a value from datetime field, the value inside model becomes undefined instead of "". It causes parse error inside angular form validators. The obvious (and dumb at the same time) idea is to replace undefined by "" in the model and then force angular validators again.
This is how it looks like:
<md-input-container class="md-block defaultInput deskInput">
<input ng-blur="onDateTimeBlur($event)" type="text" date-time ng-model="client.date_of_birth" auto-close='true' timezone="UTC" format="DD.MM.YYYY" min-view="date" template='views\controls\datepicker.tpl.html' pattern="^(\d{2}).\d{2}.(\d{4})$">
</md-input-container>
$scope.onDateTimeBlur = function (event) {
if (event.currentTarget) {
var modelReference = event.currentTarget.attributes["ng-model"].value;
if (event.currentTarget.value == "") {
this.value = "";
this.setDeepValue(modelReference, "");
}
}
};
$scope.reValidateParseErrors = function (form) {
var initialErrorsCount = 0;
if (form.$error.parse) {
initialErrorsCount = form.$error.parse.length; //to prevent infinite loop
while (form.$error.parse) {
form.$error.parse[0].$validate();
if (form.$error.parse && form.$error.parse.length == initialErrorsCount) {
break; //break the loop if real parse errors exist
}
}
}
};
$scope.saveClick = function (operationsClientForm) {
this.reValidateParseErrors(operationsClientForm);
if (operationsClientForm.$valid) {
//submitting
}
}
Anyway, the qustion is still open, because my solution looks like I'm trying to overwhelm the Angular.

jQuery script fails executing for some of the users

I am using a custom form to submit data to Google Spreadsheets. When user attempts to submit the form, it is validated (with jQuery) and if the validation is passed, the main input field is being modified with jQuery and then the submission continues.
The user inputs a URL and during submission the script cuts off unnecessary parts of the link and adds IP (that is also gathered with jQ) of the user to it. After the modification is completed, the form continues submission and in result, only the modified data is being sent to Google Spreadsheet.
It works pretty well with 99% of submissions but there are several users whose browsers do not execute the script properly; i.e.: the URL they input is not being modified during the submission and thus, wrong data (unmodified) is sent to the Spreadsheet. I am not completely sure, but the problem may be caused by Firefox (but I am not 100% sure that all the faulty submission come from Firefox, if you want I could research and confirm whether it is only Firefox's issue). I have asked some of them (users, whose browsers seem not to execute script) about addons/if they had turned JS off but they say they did not do anything special with their browsers.
I am posting whole js file below so you could check whether I did some errors that could cause problems. Also, the script is running here (link), you can inspect the code to see what other jQuery stuff I use.
$(document).ready(function() {
//Tabbiing page is being initialised, doesn't really matter, I think
$.ionTabs("#fppp_taby");
//Script that checks whether user has been redirected back after submission, that's not the main problematic part yet
if (window.location.search != 0) {
var query = window.location.search.substring(1);
ideo = query.split("=")[1];
if (isNaN(ideo) || (ideo.length < 3) || (ideo.length > 10)) {
$("form").html("Wystąpił błąd podczas wysyłania Twojego zgłoszenia. Powiadom mnie o tym poprzez prywatną wiadomość podając również obecną godzinę za pomocą <a class='uline' href='http://www.erepublik.com/pl/main/messages-compose/2417512'>tego linka</a>.");
} else {
$("form").html("Dziękujemy za zgłoszenie!<br /><br />Możesz teraz przeczytać któryś z artykułów epolskiej prasy - lista wartch uwagi znajduje się po lewej stronie!");
var poZglosz = "Dziękujemy za zgłoszenie!<br />Spodziewaj się chlebków i broni od któregoś z tych graczy: Kijek93, twatwaratwa, Gregoric bądź Zawa99";
$("#poZglos").html(poZglosz);
$("#poZglos").removeClass();
}
} else {
var query = 0;
}
//Some simple stuff
$("#wlaczirc").click(function() {
$(this).hide();
$("#irc").html("<iframe src='http://webchat.quakenet.org/?channels=fppp&uio=OT10cnVlJjExPTM0OQ1f'></iframe>");
$("#irc").show("slow");
$("#info_irc").show("slow");
});
//Some data
infoPodkr = "Wklej tutaj prawidłowy link do twojego profilu!";
inputLink = $("#ffpolelinku");
//Resetting validation info in input
$(inputLink).focus(function() {
if ($(this).hasClass("podkresl") || $(this).val() == infoPodkr) {
$(this).val("");
$(this).removeClass("podkresl");
}
});
//Gathering ip
$.getJSON("http://jsonip.com/",
function(data) {
ip = data.ip;
});
//MAIN PART (executed when user pressses 'submit')
$("form").submit(function() {
//Form is being hidden (display:none class is being added)
$('aside').addClass("hidden");
//Check whether input is empty or contains error message (infoPodkr = error message vlaue), if yes, add class 'podkresl'
if (($(inputLink).val() == "") || ($(inputLink).val() == infoPodkr)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
} else {
$(inputLink).removeClass("podkresl");
}
//Tesing whether user added proper link, if not, 'podkresl' is added
//if (!/\b(https?|ftp|file):\/\/[\-A-Za-z0-9+&##\/%?=~_|!:,.;]*[\-A-Za-z0-9+&##\/%=~_|]/.test(inputLink.val())){
if (!/http\:\/\/www\.erepublik\.com\/[a-z]{2}\/citizen\/profile\/\d{5,}$/i.test(inputLink.val())) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Split link, and get the last part of it ('wycId'), check if it's numeral, if not - add 'podkresl' class
podzielony = $(inputLink).val().split('/');
wycId = podzielony.pop();
if (isNaN(wycId)) {
$(inputLink).addClass("podkresl");
$(inputLink).val(infoPodkr);
}
//Check whether the input class 'podkresl' class (= something was wrong in some of the steps above). If yes, remove the 'hidden' class from 'aside' which holds the form and show it to the user. If there were no errors, add the IP to the 'wycId' and additional "-n" to the end of the value and put it into input. Then, submit form.
if ($(inputLink).hasClass("podkresl")) {
$('aside').removeClass();
return false;
} else {
if (ip !== '') {
$(inputLink).val(wycId + "-" + ip + "-n");
} else {
$(inputLink).val(wycId + "-0-n");
}
}
return true;
});
});

How to setup a setting whereby a user can select which type of alert they wish to display in JavaScript

I have a Firefox AddOn that displays various alerts. Is there a way in which I can setup the user being able to select which type of alert they wish to use? Currently I have two types of alerts. The standard JavaScript alert and a alertNotification. Is there a way of having a menuitem with the two different alerts the user can select. Not sure how I would code this in JavaScript though. The settings page is in XUL.
Code for both alerts currently:
Code with both alerts:
if(resultEmail) {
prompts.alert(null, "Test", "Email Address Detected");
//Other form of alert.
var alertsService = Components.classes["#mozilla.org/alerts-service;1"].
getService(Components.interfaces.nsIAlertsService);
alertsService.showAlertNotification("",
"Test","Email Detected",
false, "", null, ""); }
How can I setup that the user can choose between which alert they wish to use and have it setup in an XUL window? Not sure whether this is possible.
Currently have implemented this below now but still unable to get the user to choose which alert they wish to use.
Current Code to choose which alert:
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var customAlert = prefManager.getBoolPref("extensions.yourextension.customalert");
if(resultEmail) {
if(!!customAlert)
{
// Show your alert
prompts.alert(null, "Privacy Exposure Detected", "Email Address Detected \n\nThis data is a privacy risk and should be reviewed");
} else {
// Show built in alert system
var alertsService = Components.classes["#mozilla.org/alerts-service;1"].
getService(Components.interfaces.nsIAlertsService);
alertsService.showAlertNotification("chrome://spellchecker/content/images/stop.png",
"Privacy Exposure Detected",vrs_getWin.document.getElementById(elementT).value+ "This data is a privacy risk",
false, "", null, "");
}
XUL Window code:
<vbox>
<hbox>
<label control="custom-alert" value="Custom Alerts"/>
<checkbox id="custom-alert" preference="customalert"/>
</hbox>
<button id="checkerOkButton" label="&savebutton.label;" oncommand="namespace_highlight.setPrefs();"/>
<button id="checkerCancelButton" label="&cancelbutton.label;" oncommand="window.close();"/>
</hbox>
</vbox>
Issue is that the checkbox does not appear to be saving the input and it just defaults to the standard alert.
Any help will be grateful
You can store the choice of the drop down the user wants in a input element and query it before showing the alert. This can also be saved in a cookie for future remembrance of cross page support
//OR get type from session variable or cookie or whatever
var type = 1;
type = document.getElementById("userchoiceofalert").value;
function showAlert(type, subject, message)
{
if (type===1) {
prompts.alert(null, subject, message);
} else {
//Other form of alert.
var alertsService = Components.classes["#mozilla.org/alerts-service;1"].
getService(Components.interfaces.nsIAlertsService);
alertsService.showAlertNotification("",
subject,message,
false, "", null, "");
}
}
//in your function
if(resultEmail) {
showAlert(type,"Test", "Email Address Detected");
}
I'm assuming you have a prefwindow or some way to store your options already. So, you could create a preference for it using something like the following:
<label control="custom-alert" value="Custom Alerts"/>
<checkbox id="custom-alert" preference="customalert"/>
Then use the prefManager component to fetch the selected preference in your javascript:
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
Will get you the prefManager service and from there you can check the value (in this case it's a boolean pref as we're using a checkbox:
var customAlert = prefManager.getBoolPref("extensions.yourextension.customalert");
Then where you are showing the alert type you would have:
if(!!customAlert)
{
// Show your alert
prompts.alert(null, "Test", "Email Address Detected");
} else {
// Show built in alert system
var alertsService = Components.classes["#mozilla.org/alerts-service;1"]....
}
Just make sure that in your prefs.js file you have the preference setup such as:
// Default value for the preference
pref("extensions.yourextension.customalert", false);

javascript - why doesnt this work?

<form method="post" action="sendmail.php" name="Email_form">
Message ID <input type="text" name="message_id" /><br/><br/>
Aggressive conduct <input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct <input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct <input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct <input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" onclick=validate() />
</form>
window.onload = init;
function init()
{
document.forms["Email_form"].onsubmit = function()
{
validate();
return false;
};
}
function validate()
{
var form = document.forms["Email_form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") { //No value in the "message_id"
box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
}
</script>
Am i missing something or am i just being stupid?
edit***
sorry i should add! the problem is that i want the javascript to stop users going to 'sendmail.php' if they have not entered a message id and clicked a radio button... at the moment this does not do this and sends blank emails if nothing is inputted
You are using
validate();
return false;
...which means that the submit event handler always returns false, and always fails to submit. You need to use this instead:
return validate();
Also, where you use document.forms["Email form"] the space should be an underscore.
Here's a completely rewritten example that uses modern, standards-compliant, organised code, and works:
http://jsbin.com/eqozah/3
Note that a successful submission of the form will take you to 'sendmail.php', which doesn't actually exist on the jsbin.com server, and you'll get an error, but you know what I mean.
Here is an updated version that dumbs down the methods used so that it works with Internet Explorer, as well as includes radio button validation:
http://jsbin.com/eqozah/5
You forgot the underscore when identifying the form:
document.forms["Email_form"].onsubmit = ...
EDIT:
document.forms["Email_form"].onsubmit = function() {
return validate();
};
function validate() {
var form = document.forms["Email_form"];
if (form.elements["message_id"].value == "") {
alert("Enter Message Id");
return false;
}
var conduct = form.elements['conduct']; //Grab radio buttons
var conductValue; //Store the selected value
for (var i = 0; i<conduct.length; i++) { //Loop through the list and find selected value
if(conduct[i].checked) { conductValue = conduct[i].value } //Store it
}
if (conductValue == undefined) { //Check to make sure we have a value, otherwise fail and alert the user
alert("Enter Conduct");
return false;
}
return true;
}
return the value of validate. Validate should return true if your validation succeeds, and false otherwise. If the onsubmit function returns false, the page won't change.
EDIT: Added code to check the radio button. You should consider using a javascript framework to make your life easier. Also, you should remove the onclick attribute from your submit input button as validation should be handled in the submit even, not the button's click
Most obvious error, your form has name attribute 'Email_form', but in your Javascript you reference document.forms["Email form"]. The ironic thing is, you even have a comment in there not to use spaces in your form names :)

Categories

Resources