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.
Related
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');
I'm working on a form where I have a text field which will be changed on radio button selection.
$("#id_radio1").click(function() {
$("#multi_language").hide();
$("#single_language").show();
});
$("#id_radio2").click(function() {
$("#single_language").hide();
$("#multi_language").show();
});
Say suppose id_radio1 and id_radio2 are two radio buttons and selecting each changes the form fields differently. Now I was able to do it successfully.
My problem is when I submit the form after single language button is clicked the values are stored as multi as the values of the multi language hidden fields are submitted overridding the values of first.CAn I disable the other field without interference of the same on submission.
How can I correct this?
I'm new to such problem. I want the field to be submitted only once.i.e, if single language field is selected single should be posted and not multi(as it is working now) and when multilanguage is selected multi should be posted.How can I correct this now with the following code.
Fiddle
I have other fields common for both single and multi language in the same form as well, whose values are not changed on submission
Now, in the console I see there are two posts for the same fields in the response i.e. one for single language and other multi language.
You can format your html code as below just if you want to pass the value of the checked field to some other script
<form method="post">
<input id="id_radio1" type="radio" name="name_radio1" value="single" />
<label for="id_radio1">Single Language</label>
<input id="id_radio2" type="radio" name="name_radio1" value="multi" />
<label for="id_radio2">Multi Language</label>
<input type="submit" />
</form>
and in your Jquery Code, you can do this
$("form").on("submit", function(e) {
e.preventDefault();
console.log($("input:checked").val()); //do whatever you want with the checked value
})
Fiddle
You can use the disabled attribute to prevent an element from being sent like so:
$("#id_radio1").click(function() {
$("#multi_language").attr('disabled','disabled').hide();
$("#single_language").removeAttr('disabled').show();
});
$("#id_radio2").click(function() {
$("#single_language").attr('disabled','disabled').hide();
$("#multi_language").removeAttr('disabled').show();
});
Since they are no hidden fields but just hidden by css it should prevent it from being submitted
Why not just have one text input, then in your server-side code simply check which radio button was selected and set the value of the server-side variable accordingly before committing data.
e.g. In PHP for instance:
$language = $_POST['language'];
if($_POST['name_radio1'] == 'single'){
some_function_committing_single_language_value($language);
} else {
some_function_committing_multi_language_value($language);
}
Or have one text input and set the form's onsubmit handler with a Javascript function to insert a hidden field with a name such as 'language_single' or 'language_multi' based on the radio button selection, and set that hidden input's value to the textfield's value.
So I'm trying to create a webpage where the user puts in there course information. There is an add button on the page, that adds another text field for them if they need more fields.
Once the Add button is pressed, the page is reset and all of the information that has been previously entered is gone. I could save the information in an array, and when or if the the add button is pressed save the information into an array, and re populate the fields using what was stored in the array.
My question is: Is there a way to refresh a page, and keep the information in the text fields, without taking the long process mention above, is there some attribute that I can use that will not delete information that has been previously entered into ?
If you code HTML5, you can use localStorage with a fallback to cookies. Also, if the information should be removed after session end, then you may use sessionStorage instead.
You can use ajax i think...it runs in background no page reload is done.
Assuming this HTML:
<form id="course-info-form" action="submit-course-info.php" method="post">
Professor name: <input type="text" name="professor"><br>
Additional info:<br>
<input type="text" name="additional0"><br>
<input type="submit" value="Submit">
</form>
<br>
<button id="add-button">Add Field</button>
<!-- Use jQuery for DOM manipulation -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
With JavaScript / jQuery:
var courseInfoForm = $('#course-info-form');
var addButton = $('#add-button');
// Keep track of how many fields there are, so each can have a unique "name" attribute
var additionalFieldsAdded = 1;
// Whenever "Add Field" is clicked, create another input field
addButton.on('click', function() {
var newInput = $("<input>", {
type: "text"
name: "additional" + additionalFieldsAdded
});
courseInfoForm.append(newInput, "<br>");
additionalFieldsAdded += 1;
});
I'm not very good at PHP. In your PHP script, make a while loop that checks to see if isset($_POST['additional0']), and additional1, additional2, etc, until you are sure that there were no more additional fields passed. Then store all those additional details into an array, and handle it how you see fit.
As for your original question, I recommend using my solution instead. It's better to avoid unnecessarily reloading the page, if all you're doing is simply adding a new form each time.
I suppose you could capture the information that was "tentatively-submitted" when the "Add Field" button is clicked, and then in your PHP script loop through all the additional fields and create 1 more input element each time another field is added, and set the value attribute of each "old" input element to whatever was "tentatively-submitted."
So, to answer your question, you can set the default value of an input field (server-side) with:
// add-course-information.php
<?php
$addingField = false;
// Check for the optional "?do=addfield" parameter
if (isset($_POST['do']) && $_POST['do'] == 'addfield') {
$addingField = true;
$fields = array();
$nextField = 'additional' . count($fields);
// Get each piece of POSTed field data
while (isset($_POST[$nextField]) && $_POST[$nextField] != '') {
array_push($fields, $_POST[$nextField]);
$nextField = 'additional' . count($fields);
}
}
?>
<!-- Silly HTML! -->
<?php
// If adding a field, recreate and repopulate all previous fields
if ($addingField) {
for ($i = 0; i < count($fields); i++) { ?>
<input type="text" name="additional<?= $i ?>" value="<?= $fields[$i] ?>">
<?php } ?>
<input type="text" name="additional<?php echo count($fields) + 1 ?>">
<?php }
// Otherwise, show the default additional field
else { ?>
<input type="text" name="additional0">
<?php } ?>
<!-- More awesome HTML! -->
That might work... (Currently untested.)
What that page is supposed to do (if it works) is:
On default, give the user his initial setup, with just 1 additional input field, "additional0".
When the user clicks "Add Field," ?do=addfield should be POSTed to add-course-information.php (you can write that part), and when this page receives the do=addfield parameter, then it knows to loop through all the submitted additional fields, and store them each into an array, and then afterwards output all the submitted data back into another loop's-worth of dynamically generated <input> elements.
But I think that that would be much more complicated, and unnecessarily increase the processing your server has to do. It could even be abused if someone was to hammer the "Add Field" button hundreds of thousands of times a minute, eventually making your for-loops iterate millions of times... (Unless you imposed a limit on the maximum number of fields, which would be easy.)
However, you might as well leverage the client's processing power if it's available.
I have multiple forms in my page and depending on the hidden input value, different sections are called.
Now my issue is, I have 2 input buttons in one of my forms, and depending on what button I click i need to send the appropriate hidden input type,
For example in the below form .
If i click on Generate password button,
I want the target value(the value of the hidden input field) as generate_password
If I click on Lock Password I want the target value to be user_locked. Here is my code.
puts "<input type=\"hidden\" name=\"target\" value=\"user_locked\">"
puts "<tr><td colspan='4'> New User request Review</td></tr>"
puts "<tr><td><label for=\"full_name\"> Full Name </label></td>"
puts "<td><input type=\"text\" value =\"$name\" name =\"full_name\" readonly=\"readonly\"></td>"
puts "<tr><td><input type=\"button\" value=\"Generate Password\" onclick=\"if(confirm('Are you user you want to add this user?')){submit()};\"></td>"
puts "<td><input type=\"button\" value=\"Lock User\" onclick=\"if(confirm('Are you user you want to add this user?')){submit()};\"></tr>"
well basically I am calling different functions depending upon the hidden field,
set target ""; catch { set target $CGI_DATA(target) }
switch $target {
"confirm" { set id [UpdateUserData $id] }
"user_locked { DeleteUser $id }
"user_confirmed" { NewUserConfirmed}
"newuser" { NewUserReview }
default { }
}
The code to your onclick event could do that when confirming instead of just submitting the form. If you use jQuery:
if(confirm('Are you user you want to add this user?')){
$("input[name=target]").val('Generate password');
submit();
}
The one for the other input button should be very similar.
It is also possible that you have a way of knowing which button was pressed to submit the form another way. If I remember correctly, in PHP at least the name of the button is passed through in the _REQUEST variable.
In HTML:
<input type="hidden" id="target" name="target" value="user_locked">
...
<input type="button" value="Generate Password" id="generate_button"/>
<input type="button" value="Lock User" id="lock_user"/>
In JS (jQuery):
$("#generate_password,#lock_user").click(function(){
("#target").val($(this).attr("id"));
$("form.myform").submit();
});
You can change around the IDs and classes of these elements, but make sure the JS and HTML match up.
On the site I am developing, I have a file input that users can upload files from. It uses "Ajax" (not really) to send the file to a php file that is bound to an iframe. My question is that Firefox automatically fills in the file input element. Is there a way I can give users the option of clicking the submit button without sending the file? Or do I set the file value to null somehow and check for that in the php file? My code looks like this:
Name: <input type='text' id='name'><br>
Description: <textarea id='description' rows=10 columns=100></textarea><br>
<form id="upload_form" method="post" enctype="multipart/form-data" action="uploadfile.php">
<input type='hidden' value='' id='descriptionid' name='descriptionid'>
<input type='file' name="file" id="file" size="27" value="">
<input type='submit' value='Submit' onclick=';' id='submitPopup'>
</form>
When the button is clicked it runs a JavaScript method and gets the values of name and description and also submits the input form. How do I let users have the option of uploading a file, and not have it auto filled in by their browser?
As a security measure, reading or setting the value of a file input field is not allowed. However, if you call form.reset() that will clear it out for you.
You could even loop through all the other inputs, remember their value, reset the form and then refill the other inputs, so only the files are cleared.
For safety you can not enter data by hand or by JavaScript in an input type file.
I answered this question in another topic: how to clear file input with javascript?
There's 3 ways to clear file input with javascript:
set value property to empty or null.
Works for IE11+ and other modern browsers.
Create an new file input element and replace the old one.
The disadvantage is you will lose event listeners and expando properties.
Reset the owner form via form.reset() method.
To avoid affecting other input elements in the same owner form, we can create an new empty form and append the file input element to this new form and reset it. This way works for all browsers.
I wrote a javascript function. demo: http://jsbin.com/muhipoye/1/
function clearInputFile(f){
if(f.value){
try{
f.value = ''; //for IE11, latest Chrome/Firefox/Opera...
}catch(err){
}
if(f.value){ //for IE5 ~ IE10
var form = document.createElement('form'), ref = f.nextSibling;
form.appendChild(f);
form.reset();
ref.parentNode.insertBefore(f,ref);
}
}
}