How to fill a text field with a hidden value? - javascript

I am auto populating text fields from a database and I am also validating these fields in case someone mistypes anything. If validation fails I show the error messages but the fields get back the original values.
Is there a way to refill those text fields with something like hidden values to hold the mistyped value.
So this email field gets populated with a value from the database on page load.
<td align="left">
<s:textfield name="emailId" id="emailId" label="Email" cssClass="dataFieldCell3" value="%{#signerslist.email}" />
</td>
So if accidentally the value is changed I want to get that changed value and hold it because I am showing the error message for it without letting it go back and get the original value.
I am not sure what to do after this JavaScript.
function getIncorrectValue() {
var emailValue = document.getElementById('emailId').value;
}

With JQuery, you can add data to your DOM. This data is a string model, which means it will be an invisible or hidden data attached to your HTML element.
function getIncorrectValue() {
var emailValue = document.getElementById('emailId').value;
$('#emailId').data('incorrectValue', emailValue);
}
Then you can retrieve that data later by doing:
var emailValue = $('#emailId').data('incorrectValue');

Related

Resetting a form with 'sticky' input values (a solution)

I searched widely to find a solution for this, and eventually had to realise (as others have before me) that a form will always reset to the values with which it is loaded.
So my solution is to load the form with empty values, and then use pure Javascript to update the values from other hidden inputs. It requires one hidden input, and one line of JS, for each user input. My example below shows the code for just one input. Any further inputs follow the same pattern.
The input (I have omitted the label for clarity):
<li>
<input type="text" name="firstname" id="firstname" value='' tabindex="1" size="45" />
</li>
The hidden input:
<input type = 'hidden' id = 'jfn' name = 'jfn' value = '<?php echo $firstname; ?>' />
The Javascript (in the 'onload' or (if jQuery is available, 'document ready') function)':
document.getElementById('firstname').value = document.getElementById('jfn').value;
When the form is submitted the inputs (in $_POST) are saved to SESSION, whence they can be recalled for as long as the SESSION lasts:
foreach ($_POST as $name=>$value) {
$_SESSION['email'][$name] = $value;
}
and later recovered:
if (!empty($_SESSION['email'])) {
extract ($_SESSION['email']);
}
When/if the form is reloaded, the input values are initially empty. The previously input values are loaded into the hidden inputs. After the page has reloaded those values are transferred to the (visible) inputs. The 'Reset' button will now clear the form.

Automatically fill out textarea field from my database when selecting dropdown menu item

How can I automatically fill a textarea field with the text from the database and automatically display the associated text when selecting an item from the dropdown menu.
Textarea field were I want to post the data in:
<textarea
class="dropDown" Name="dropdownItem" Type="Text" id="dropdownItem" placeholder="New Option"
></textarea>
Thats only a quick try that prints out the same input as the dropdownItem from my database.
<script>
var select = document.getElementById('select');
var input = document.getElementById('TextAreaTemplate');
select.onchange = function(){
input.value = select.value;
}
</script>
I already connect to the database, but I just don't know how to do this.
Do I need more JavaScript?
What you are doing here is only putting the value from your input to your textarea.
You need to make a query to your database with the value you get from your input.
I guess your connection is made via PHP (since you put the PHP tag), so I would recommend you to use AJAX request to create your query with the value from your input.
Then, your response should contain the associated text to display in the textarea.
I found this resource which show the basis of AJAX and PHP if you need, but you probably can find better.

<textarea> has some text, after updating it in form, change is not reflecting while submitting the form

I wanted to construct a form, When it loads, it should have data which is currently stored in back end DB. At the same time user should be able to change content and submit form to update DB.
For this purpose I have used input and textarea elements. textarea is used to show email. But after update data, data of input elements changed but not for textarea
Here is code:
In HTML Form this is textarea, Where text is echoed via PHP
<textarea placeholder="EMAIL" class="form-control" rows="2" cols="6" id="email" style="resize:none;"><?php echo $retention_config['email'] ?></textarea>
In browser I updated the email content of this
After that before submitting data, I wished to validate that this field should not be empty, for this used JS
Here is JS code:
var email_text = $('#email').text().trim();
if(email_text == "") {
alert("Email is Mandatory");
}
But, I was not getting this alert, after deleting whole content of email, Then I checked the value of this using javascript.
console.log('#email').text();
I got the text which, i initially loaded via PHP, When I updated text in form it should be updated then, Please help, as I ran into this problem for first time. Please forgive me if there is any error in this post as I am learning to post in stack overflow, earlier only I got ready made help from this platform only.
This is an input so you need to get the value of it, as you are using jQuery you can use val(), like so:
var email_text = $('#email').val().trim();
if(email_text == "") {
alert("Email is Mandatory");
}
and your console log would be:
console.log($('#email').val());
You need to use val instead of text
var email_text = $('#email').val().trim();
if(email_text == "") {
alert("Email is Mandatory")
}

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.

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