keeping a div value after form submit - javascript

There are total 8 textboxes in my html form.I am displaying 2 of the textboxes by default and 6 are set to display:none.All these textboxes are wrapped with divs (named fa1 to fa8). I have added a button which will display the hidden divs(named from fa3 to fa8) upon each click.
html code:
<input type="hidden" id="countfa" name="countfa" value="3" readonly>
<button type="button" onClick="AddNewFa();" id="addfa" > + Add New FA </button>
I am using below javascript to listen the click and count and display hidden divs
function AddNewFa()
{
var facount = parseInt($('#countfa').val(),9) ;
if( facount < 9)
{
facount = facount+1;
for(i=3;i<9;i++)
{
if( i<facount )
$('#fa'+i).slideDown("fast");
else
$('#fa'+i).slideUp("fast");
}
$('#countfa').val(facount);
}
}
The problem that I am facing here is after form submit countfa value changing back to its default value 3. So if I have showing all hidden div before form submit after clicking the button countfa value will be 8, and after form submit it will be 3 again. Is there anyway I can keep countfa value as 8 ? even after form submit ?

I am not sure if i understood you correctly, but i faced a similar problem in the past and i resolved it rather easily. You can simply retrieve the value of countfa and then set its value.
Since you are using php, you can simply use this code
Note: Im assuming your using POST, if you are using GET then simply replace $_POST with $_GET
When you get to the part of your code printing the countfa div, simply use this code (Im assuming your using html and will introduce the php inline. Else just remove the <?php ?> tags
<?php
if(isset($_POST['countfa'])){
echo "<input type=\"hidden\" id=\"countfa\" name=\"countfa\" value=\"$_POST['countfa']\" readonly>";
}else{
echo "<input type=\"hidden\" id=\"countfa\" name=\"countfa\" value=\"3\" readonly>";
}
?>

You can store the value in the browser local storage and check after page load if a previous value is stored and restore it if that's the case.
Here is the minimal working example: http://jsfiddle.net/C5Fe7/
$(function () {
if (localStorage['countfa']) {
$('#countfa').val(localStorage['countfa']);
}
$('#addfa').click(AddNewFa);
$('form').submit(function () {
localStorage['countfa'] = $('#countfa').val();
});
});

Related

HTML Form: How to submit many (100+) inputs

I am working on a system that allows the user to preview the result as an HTML table. I put a checkbox in the leftmost cell that is checked by default. Should the user uncheck any row, that row will not appear in the final product.
Submitting this form, which as of now is only these checkboxes, with just HTML yields a 404 error. Removing or significantly reducing the number of the checkboxes fixes this problem.
I implemented name = "checkbox[]" instead of name = "checkbox1", name = "checkbox2", ... to see if that would solve the problem; it didn't.
I also tried serializing and submitting the form data with jQuery post and PHP, which still gives me the 404. I tried submitting the form using AJAX and jQuery to the same effect.
I'm not sure if submitting the data through $_SESSION will help. I don't know how I would implement this in my use case.
How can I submit many inputs without causing an error?
EDIT: A hopefully minimal, complete and verifiable example (using only HTML, since none of the scripting methods produced a better result):
<?
print "<form action = 'target.php' method='get'>";
for( $i = 0 ; $i < 200 ; $i++ ){
print '<input type="checkbox" name="chk[]" checked /> Checkbox ' . $i . '<br />';
}
print '<input type="submit" value="Submit">';
?>
This produces the same error for me: 404.
Replace <form action = 'target.php' method='get'> with <form action = 'target.php' method='post'>
You use the GET method, which means that the input names and values will be sent in the URL. If you send data to the server, always use POST.
If you have 100+ inputs, then the URL gets too long

HTML text input tags generated with javascript do not POST when the form is submitted

I have a form which asks for employment history, where you have applied to college etc. So for example for colleges they applied to I have one text box at first and there is a button below that calls a javascript function to add another text input right below it. When I first made this form I was doing that with a few different pieces of data then once they were submitted I would get them from $_POST and put them in arrays then add each element of the array to the corresponding table in my db. All of a sudden though, I can no longer submit my form and I get a message telling me that I have tried to get an unspecified index. However when i inspect the text inputs in my browser they are correctly named. I read that I should name them college[] so that they all go into an array, but that also did not work.... now what?
js:
var numcol = 1;
function addnewschool(){
numcol++;
var container = document.getElementById("collegecontainer");
container.appendChild(document.createTextNode(numcol));
var input = document.createElement("input");
input.type = "text";
input.name = 'applied'+numcol;
container.appendChild(input);
container.appendChild(document.createElement("br"));}
html:
<p class="text-dark mb-4">List the Colleges you have applied to:<br>
<div id="collegecontainer" name="collegecontainer">
<input type="text" name='applied1'><br>
</div>
<input type="button" id="addcollege" name="addcollege" value="Add College"
onClick="addnewschool()"><br>
</p>
php:
$applied = array();
foreach($_POST['applied'] as $value){
array_push($applied, $value);
}
Update: Ok so I changed it to another way and that didn't work so i decided to just copy an earlier version of it which was working and paste it into the correct layout. And that worked... SO now that it was fixed i continued adding to it. I added "required" to a few tags, changed some styling a bit, and changed my javascript file a bit. But now I'm having the same issues as before. All of my POST arrays only have the first value in them. What could I have added that changed this? Has anyone ever had any issues like this?
Your first additional input should have index "applied1", not "applied2"
look at:
var numcol = 1; // put this to 0
function addnewschool(){
numcol++; // or move this to the end of the function
You don't need to add a different name for each input. Just use applied[] in all input names.
To get the array in PHP, just use $_POST['applied'].
If you want to use each of them later, you could use a foreach, like
foreach ($_POST['applied'] as $value) {
// Do what you want. Retrieve the value using $value
}
Or any other method you prefer.
Name your text input field(s) applied[] and when you process the form the post value of $_POST['applied'] will be an array already filled for you with however many entries were completed.
To get the data into your table:
foreach ($_POST['applied'] as $id => $applied) {
$sql = "INSERT INTO Colleges(id, college) VALUES('$id','$applied')";
if($conn2->query($sql) === TRUE){
echo "New Record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn2->error;
}
} // end of foreach

JavaScript variable passed to PHP

I'm working on a form that adds up the totals selected (via checkboxes). In my JavaScript file, build.js, the totals are added together. On my PHP page, the code takes the items selected on the previous form/HTML page and passes them to what is shown on the PHP page. I want to be able to take the total that was added up via JavaScript on the form page and bring it over to be listed as a total underneath all the options that were selected.
My knowledge of PHP and JavaScript are very rudimentary. This is the first real form I have created in either of these languages. I have poured over this site and the internet in general and have not been able to get any of the options I've found to work. I think I just lucked out on getting the form this far, so I apologize if my code isn't very clean!
Any help would be amazing, as specific as possible please. Here is my code:
The JavaScript that adds the total:
$(document).ready(function() {
$("input[type=checkbox]:checked").attr("checked", false);
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
}
$("input[type=checkbox]").change(function() {
recalculate();
});
});
Code written on the form itself that shows the total:
<span id="output" class="total"></span><BR><BR>
Code written on the PHP page:
<b>Estimate:</b>
<?php
$aTruck = $_POST['formSelected'];
if(empty($aTruck))
{
echo("You didn't select a truck.<BR><BR>");
}
else
{
$N = count($aTruck);
echo("<h3>Truck Type: ");
for($i=0; $i < $N; $i++)
{
echo($aTruck[$i] . " ");
}}
$aAddons = $_POST['formAddons'];
if(empty($aAddons))
{
echo("You didn't select any options.");
}
else
foreach ($aAddons as $v)
{
echo "<h3> $v </h3>";
}
?>
If I'm not mistaken, the reason I can't currently pass the total is because of something I read on here: the PHP is run on the server while the JavaScript runs on the user's end. My options are thus to send the total in the form (possibly as a hidden variable, which I can't figure out either), pass it along in Ajax (I don't know if the server I'm on is capable of this- possibly so and it's all use error!), or use an XMLHttpRequest. I've tried anything I could find on any of those and either do not have the right variable listed inside, am placing it in the wrong spot, or it's just plain wrong.
As I mentioned, I've poured over the forums for everything I can that's related to this and nothing I've found is specific enough for the tiny bit of understanding I have. Among other things I've tried: Pass a javascript variable value into input type hidden value and Pass Javascript Variable to PHP POST along with using an XMLHttpRequest, using Ajax, passing it as a hidden variable (which I'm leaning towards but don't think I'm implementing correctly) and a ton more- it's pretty much all I did all day at work yesterday so I'm not trying to be redundant with my question- I just can't figure out where I'm going wrong.
It looks like you hit upon it right here:
send the total in the form (possibly as a hidden variable)
Since you're talking about one page posting to another page, and that other page showing the results, then there's no need for AJAX here. You can just use a form value like any other. The "hidden variable" in this case is actually an input element:
<input type="hidden" name="sum" />
In your JavaScript where you're displaying the sum on the first page:
$("#output").html(sum);
You can also set that sum to the form element's value:
$("#output").html(sum);
$("input[name=sum]").val(sum);
As long as that input is inside the same form as the other input elements (like formSelected and formAddons) then when the first page posts to the second page, the code in the second page can access the sum value the same way:
$_POST["sum"]
In your form you should add a hidden input like this :
<input type="hidden" name="sum" value="">
Then in your recalculate() (javasript) function, you should change the value of this input once you calculated everything :
function recalculate() {
var sum = 0;
$("input[type=checkbox]:checked").each(function() {
sum += parseInt($(this).attr("rel"));
});
$("#output").html(sum);
// Change the hidden input value
$("input[name='sum']").val(sum);
}
Now, when your form is submitted, you should access the sum value, server side (PHP), with a simple :
$sum = $_POST['sum'];

Saving information on HTML page without using variables

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.

changing value of hidden input fields depending on submit button

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.

Categories