Global variable is not getting updated from within a function - javascript

I am creating a simple form where user can set the hour.
Through javascript validation it checks that there is a value in the form.
Originally the global variable "userInputHours" is set to 0.
Within the function "validation()" when user fullfills the required criteria of filling in something in the form, the validation goes to "else" and should update global variable "userInputHours".
As a last step the HTML info-box should update the user input hours.
What is the problem? I cannot get the user form input value to stay on the HTML info-box (it is visible for less than a second, then it gets overwritten by the original value "userInputHours").
I know some answer would indicate I should use AJAX but that is to solve that only parts of the page is being reloaded. Using AJAX does not solve the base of my problem.
Scenarios and what works/don't work:
Scenario-1: Enter digits in form field "hours" and press button "submit-1":
Works: Console log prints "You added: [the number you added in HTML form].
Does not work: Running a console.log(userInputHours) from console itself returns the originally value [0] not the user added value. Note! For a very short moment, less than a second you actually see the user value in the HTML form but to be overwritten by original value.
Wanted results: In HTML info-box the number user added should show up.
Scenario-2: Pressing submit-2 calls function "outsideValidation()",
that set's "userInputHours" to 5:
Works: the global variable "userInputHours" is being updated from within the function. The console.log(userInputHours) confirmes that global variable has been updated. The HTML info-box is being updated with the update global variabl value.
Does not work: Since this test is not connected to the user form field "hours", it does not work to add a number in the field "hours" and get it updated onf the HTML info-box.
Expected results: Works as expected. Does not solve the complete needed solution.
// Global variables.
var userInputHours = 0;
// Validation.
function validation() {
userInputHours = document.getElementById("userInputHours").value; // Works
/* Validates blank fields */
if (userInputHours == "") {
console.log("A field is left blank"); // Works
alert("Please fill in all fields!") // Works
return false;
}
else {
console.log("You added: " + userInputHours); // Works
// You see added value for a very short moment. The it returns to the original glbal value.
document.getElementById("info-box-text").innerHTML = userInputHours; // Does not work.
return true;
}
}
/* Not part of validation. Connected to button "submit-2" */
function outsideValidation() {
userInputHours = 5;
document.getElementById("info-box-text").innerHTML = userInputHours; // Works but is disconnected from HTML form user input.
}
/* Not part of function. Only run when saving the script. */
document.getElementById("info-box-text").innerHTML = userInputHours; // Works by save the script.
.box-1 {
background-color: white;
width: 100px;
height: 100px;
}
#userInputHours {
width: 100px;
}
#submit-1,
#submit-2 {
height: 60px;
}
<form onsubmit = "return validation();">
Hours:<br />
<input id="userInputHours" type="text" name="hours" value=""><br /><br />
<input id="submit-1" type="submit" value="Submit-1 (inside form)"><br /><br /> <!-- Submit button -->
</form>
<br />
<input id="submit-2" type="submit" value="Submit-2 (outside form)" onclick="outsideValidation()">
<br /><br />
<div id="info-box-title" class="info-box-title">Info-box - (you have set hours to):<br /></div>
<div id="info-box-text" class="info-box-text"></div>

The return value of validation is used by the browser to determine if the default behavior of the form submit should be done.
If the return value is true then the default behavior will take place, and the browser will submit the form to the URL which is defined in the action attribute (if no value is present for the action attribute then it defaults to the current url).
With a form submit you will leave the current page and load a new one or reload the current one depending on the value of action. And because of that all value stored with js are lost.
If you do not want to send the data to the server you have to write return false in both cases to prevent the form submit.

Related

How to reset sap ui5 input fields by using javascript?

i have created one submission form by using java script i need to reset the input data by using on reset button.
Help me out of this.
reset: function() {
var oInput1 = sap.ui.getCore().byId("firstname");
oInput1.setValue("");*/
this.getViewById("firstname").setValue("");*/
}
input1.getId("firstname").setValue("");
onExit: function() {
input1.setValue("");
}
the code is not resetting the form data
First of all your provided code-sample is incorrect, please correct it.
Second, onExit is executed when your view is destroyed, setting the input value to empty is rather useless there.
If you want to reset data of your input-field when clicking a button you'll need to have the following elements:
1) an Input- & Button-control (with press-event) in your XML-view.
2) an id assigned to your Input-control to be able to refer to the control when pressing the reset-button.
3) The press-event from the button worked out in your controller.
XML
<Input id="firstname" value=""/>
<Button text="Reset" press="reset"/>
Controller
reset: function() {
var oInput1 = this.getView().byId("firstname");
oInput1.setValue("");
}

How to see if a form element was not posted

I have a form where e-mail is optional. To control that there is a checkbox. If that checkbox is unchecked, the e-mail textbox would be disabled and therefore not posted on submit. However, on the next page, if I have code like as shown below, it gives me an error if the e-mail textbox is disabled.
if (isset($_POST['submit']))
{
$_SESSION["email"] = $_REQUEST['YourEMail'];
....
}
To get around that problem, I progammatically enable a disabled e-mail textbox just before submitting besides setting its value to an empty string. The code for that is shown below.
document.getElementById('YourEMail').disabled = false
document.getElementById('YourEMail').value = ''
However, one annoying problem remains, which is that, if the user goes back to the original page, the e-mail textbox is enabled, since I enabled it problematically just before submitting the form. However, I want it to be disabled in that case. How, can I achieve that? Alternatively, how in the next page, I could see that e-mail box was disabled and therefore not even try to read $_REQUEST['YourEmail']?
if the field "#YourEMail" is optional you can check if exists in PHP. There is no need for enable/disable the field using JS.
if (isset($_POST['submit']))
{
if (isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])){
$_SESSION["email"] = $_REQUEST['YourEMail'];
}
}
You can test it like this using a ternary:
(isset($_REQUEST['YourEMail']) && !empty($_REQUEST['YourEMail'])) ? $_SESSION["email"] = $_REQUEST['YourEMail'] : FALSE;
This would only set the session variable if the request variable is set.

Saving form data to cookies

I've been trying to solve this problem for about a week now with no luck. I'm trying to save a value from a form field to a cookie onclick="updatePricingFunction() but when I click the updatePricingFunction button attached to the onclick, the value doesn't change to the new number. Can anyone help me with this?
function updatePricingFunction(){
var beforeNoonField = document.getElementById("beforeNoonNPSlot"); // beforeNoonNPSlot is a form id.
document.cookie = "beforeNoonCookie=" + beforeNoonField; // Create the cookie
}
lol your code was a bit wrong, but say for argument's sake, you had
<form name="myform">
Enter Number<input type="text" name="sampletext" id="beforeNoonNPSlot">
<button type="button" onclick="updatePricingFunction()">Set Cookie</button>
</form>
you need to get the name of your form and the name of the texbox where you want to get the value from. So that when the button is clicked the function updatePricingFunction() will be called, it will retrive the value from The textbox in your form
function updatePricingFunction()
{
//To get a value in a text field, you must have your variable equals
//document.forms["(form name here)"]["(name of the text field here)"].value
var beforeNoonField = document.forms["myform"]["sampletext"].value;//This gets your value
document.cookie = "beforeNoonCookie=" + beforeNoonField; // Create the cookie
}
Take note that this method is a more conventional method of getting values with javascript so you should be using this more often.

Input Field returns undefined but works after changing the value

When I first click on this function. It returns an undefined value. When I click on the function again, this code works fine in this form and every form after that.
alert(characters[x].ac+"/"+this.value+"/"+this.ac) returns undefined/undefined/0 initially.
It returns 26/undefined/0 when I click the function again and captures the value just the way I want. So it is basically saying that characters[x].ac is undefined when I initially click the bolded text to make the text field appear.
How do make the 'undefined' listing go away. It happens when I change the value of an array for the first time but works fine in the same array in every form after that.
function askAc(x) {
if(this.ac!=0) {
response=this.ac;
characters[x].setAc(response);
this.ac=0;
} else {
response="<input class=widgetstyle onClick=_setAc(this.value) size=2 type=text value="+characters[x].ac+">";
characters[x].setAc(response);
}
}
function _setAc(x) {
this.ac=x;
this.refresh();
}
Does your input field have a value="" attribute or is it missing? a missing value attr may result in undefined (maybe just in some browsers).
It is not clear from your code which input field you are accessing.

Javascript to prevent invalid user input

I have written a set of javascript functions that allow me to validate user input on a form. I only want to accept valid input, and impose the following behaviour:
When a user enters an invalid form, I display an alert and inform them that the value entered is incorrect. Crucially, the original (valid) value in the form is not changed.
The value is only changed when the value has been validated.
For example, suppose I want to accept only positive integers in a field.
This is the sequence of events that describes the desired behaviour.
Scenario 1 (valid input)
Form loads with valid default in the input field
User types in valid number
Input field value is updated (as per normal form behaviour)
Scenario 2 (INvalid input)
Form loads with valid default in the input field
User types in INvalid number
Alert box is shown alert('Invalid value')
Input field value is NOT CHANGED (i.e. the value is the same as BEFORE the user typed in the invalid number)
[Edit]
The only problem I am facing at the moment (i.e. what this question is seeking an answer for), is Scenario 2, action point 4. More specifically put, the question degenerates to the following question:
How do I stop the value of a field from changing, if I (somehow) determine that the value being entered by the user is invalid. This is really, all I'm trying to answer.
I am also doing server side checks, this question is just about the front end - i.e. refusing to change a field (form text input) value if I determine that the value is incorrect.
BTW, I am using jQuery, and would like to implement this in a manner that separates behaviour from display (I think this is what is meant by the term 'unobtrusive' ?)
Any suggestions on how to implement this behaviour as described above, would be very much appreciated.
PS: I dont want to use yet another jQuery plugin for this. I should be able to use jQuery + the simple javascript validation functions I have already written.
When loading the page, couldn't you create a hidden form value or js variable in which you store the initial/default value for the field? When they change the form field, validate it, and if it passes, update the hidden field or js variable to match that in the field they updated.
When the input given by the user fails validation, show the invalid entry along with the error message and then update the form field back to the value you have saved which would be either the
default value or the last valid value that they entered.
EDIT:
Note that this is only a quick and (very) dirty example of doing what I explained in my answer above. If you have a lot of inputs, you will probably want to store the values in an associative array instead of in hidden form values, but this should give you a good handle on what I am suggesting. I would also strongly encourage you to NOT use alert boxes for notification of invalid answers.
<html>
<head>
<script type="text/javascript">
function validate()
{
var field1 = document.getElementById("field1");
var saved = document.getElementById("field1_save");
if (field1.value < 0 || field1.value > 10)
{
alert("Field1 value of " + field1.value + " is invalid");
// Change the value back to the previous valid answer
field1.value = saved.value;
return false;
}
// Save the valid input
saved.value = field1.value;
return true;
}
</script>
</head>
<body>
Test User Input
<form name="form1" id="form1" method="post">
<input name="field1" id="field1" type="text" value="2" onblur="validate();"/>
<input name="field1_save" id="field1_save" type="hidden" value="2" />
<input name="btnSubmit" type="submit" value="Submit" />
</form>
</body>
</html>

Categories