Unlimited fields in PHP? - php

How do I do unlimited fields in php? Here is the scenario:
At first, there are only 2 fields, lets called: first name1, last name1
What I want to do is, when I click the "add" button, it will add another 2 fields in new row, the fields label/name should be first name2, last name2. And when I click again, it will have first name3, last name3, and so on..
Can anyone give me some sample script in php? I am new to PHP.
The form should be in HTML. If somebody can give Ajax sample code, would be a big plus.

That depends on what you mean by "field." It sounds as though you're talking about a form, which wouldn't be PHP, but instead HTML. You could have a button [Add] post back to the server, which then refreshes the page with another set of form-inputs. You also do that via javascript without having to refresh the page.
Simple Javascript (jQuery) Example:
$(document).ready(function(){
$("input[value='Add']").click(function(event){
event.preventDefault();
$("p.field:last").clone().insertAfter("p.field:last");
});
});
<form method="post">
<p class="field">
<input type="text" name="firstname[]" value="" />
<input type="text" name="lastname[]" value="" />
</p>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>
Simple PHP Example:
I don't encourage you use this as-is
<?php
$count = 1;
if ($_POST["submit"] == "Add") {
$count = ($_POST["firstname"]) ? (count($_POST["firstname"]) + 1) : 1;
} else
if ($_POST["submit"] == "Done") {
print "<pre>";
print_r($_POST["firstname"]);
print_r($_POST["lastname"]);
print "</pre>";
}
?>
<form method="post">
<?php for($i = 0; $i < $count; $i++) { ?>
<p class="field">
<input type="text" name="firstname[]" value="<?php print $_POST["firstname"][$i]; ?>" />
<input type="text" name="lastname[]" value="<?php print $_POST["lastname"][$i]; ?>" />
</p>
<?php } ?>
<p>
<input type="submit" name="submit" value="Add" />
<input type="submit" name="submit" value="Done" />
</p>
</form>

There are two ways to do this, either using solely PHP or by some fancy JavaScript. I will tackle the PHP-only solution. A JavaScript solution would be much more responsive as there wouldn't be repeated round trips to the server but it would also only work for users who have JavaScript enabled, whereas a PHP solution works for everybody.
A general outline of the solution is this:
Initially $count is 1, and one row is generated.
If the user clicks Add, the form is posted back to the very same PHP file with a hidden count variable included. The script restarts from the beginning, increments $count, and displays one more row than the last time.
If the user clicks Submit, the names that have been entered are processed.
Here's some sample code. I apologize that I do not have PHP installed on the machine I'm writing this one so this is entirely untested. Hopefully there aren't too many horrendous syntax errors!
<?php
$count = isset($_POST['count']) ? $_POST['count'] : 1;
if (isset($_POST['add']))
++$count;
else if (isset($_POST['submit']))
{
header('Content-Type: text/plain');
print_r($_POST);
exit;
}
?>
<html>
<body>
<form action="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']) ?>" method="post">
<input type="hidden" name="count" value="<?php echo $count ?>" />
<?php for ($i = 1; $i <= $count; ++$i) { ?>
[<?php echo $i ?>]
First: <input type="text" name="firstName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["firstName$i"]) ?>" />
Last: <input type="text" name="lastName<?php echo $i ?>"
value="<?php echo htmlspecialchars($_POST["lastName$i"]) ?>" />
<br />
<?php } ?>
<input type="submit" name="add" value="Add" />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
Oh and you want a JavaScript solution, eh? Well you've got the really nice jQuery answer already. How about a ridiculously long plain-JavaScript solution, then?
<html>
<head>
<script type="text/javascript">
// <![CDATA[
var count = 0;
function addRow() {
var table = document.getElementById("table");
var row = document.createElement("tr");
var countCell = document.createElement("td");
var countText = document.createTextNode(++count);
var firstCell = document.createElement("td");
var firstInput = document.createElement("input");
var lastCell = document.createElement("td");
var lastInput = document.createElement("input");
firstInput.type = "text";
firstInput.name = "firstName" + count;
lastInput.type = "text";
lastInput.name = "lastName" + count;
table .appendChild(row);
row .appendChild(countCell);
countCell.appendChild(countText);
row .appendChild(firstCell);
firstCell.appendChild(firstInput);
row .appendChild(lastCell);
lastCell .appendChild(lastInput);
}
// ]]>
</script>
</head>
<body>
<form action="somewhere.php" method="post">
<table id="table">
<tr>
<th>Row</th>
<th>First</th>
<th>Last</th>
</tr>
</table>
<script type="text/javascript">
addRow();
</script>
<input type="button" value="Add" onclick="addRow()" />
<input type="submit" value="Submit" />
</form>
</body>
</html>

Related

Need to display Inputs one at a time using For Loop

Guys I just needed to display inputs one by one each time the user click the submit. The problem on using php is that when you use loop, it display all at one time. Please Help guys.
Output: enter image description here
This is my code
<?php
for($c=1;$c<=10;$c++){
echo '<form method="POST" class="form-anticlear">
Enter Number :
<input type="number" name="num[$c]" required />
<input type="SUBMIT" name="button" value="Submit" required>
</form>';
}
?>
Your question isn't really clear as too what it is you are trying to accomplish. Assuming you want to show another input field every time submit is called, the code below will give you that. The file is called test.php change the action="test.php" if your file is called something different.
<?php
$total = 1;
if (isset($_POST["background-number"])) {
$total += $_POST["background-number"];
}
for ($c = 1; $c <= $total; $c++) { ?>
<form method="POST" class="form-anticlear" action="test.php">
Enter Number :
<input type="hidden" name="background-number" value="<?= $total ?>"/>
<input type="number" name="number-input" required/>
<input type="SUBMIT" name="button" value="Submit" required>
</form>
<?php
}
?>

How to scale the number of form fields based on user input?

I’m new to PHP and making a website to add an arbitrary number of values in a given base. How would I generate several fields based on a user’s input in a previous field?
The simple code without any validation will be like this:
<?php
if (isset($_POST['count_of_fields'])) {
echo '<form method="POST" action="">';
for ($i = 0; $i < (int) $_POST['count_of_fields']; ++$i) {
echo '<input type="text" name="field[$i]" /><br>';
}
echo ' <input type="submit"></form>';
} else {
echo '
<form method="POST" action="">
<input type="number" name="count_of_fields">
<input type="submit">
</form>
';
}
Beside the answer from #lis-dev which is generating fields in server side you will have to load the page each time to render the new fields, let's use JavaScript to do that for you without refreshing the page. and yes using mix and max you can put limit also
function generate()
{
var value = parseInt(document.getElementById("no").value);
for(var i =1; i <= value ; i++)
{
var input = document.createElement("input");
var br = document.createElement("br");
input.type = "text";
input.placeholder = "I am dynamic field " + i;
document.getElementById('form').appendChild(input);
document.getElementById('form').appendChild(br);
}
}
<html>
<head>
<title>dynamic fields test</title>
</head>
<body>
<form id="form">
<input id="no" type="text" min="5" max="10" placeholder="Enter no of Fields">
<input type="button" value="Generate" onclick="generate()">
<br />
</form>
</body>
</html>

Update form fields after posting with PHP_SELF

I am using php_self to submit a form. Once the data has been posted, I want to pass a calculated value to another form field on the same page, original form.
The $title_insurance field stays blank. Any ideas on why? Thanks!
<?php
if(isset($_POST['submit']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="submit" type="submit" class="bordered" id="submit" value="Calculate" />
</form>
The submit button is called button, also if you are outputting a javascript to amend the value it need to be run after the DOM has created the element title_insurance.
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
A better way in this case would be to forget about the javascript as it is unnecessary and do this
// I am assuming you have initialized $title_insurance
// somewhere above here to its default value!!!!
$title_insurance = isset($_POST['button']) ? ($_POST['sale_price'] * 0.00575) + 200 : $title_insurance;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
You have an extra space in your getElementById parameter:
// VV
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
What you want to do is best done by AJAX. The <form> construction is outdated and not useful unless you are transferring the user to another page and sending some data along with it - or, if you are finished getting user data and just want to process what was entered and display a completion message.
If you wish to continue processing on the same page, then AJAX is the way to go. And the best way to use AJAX is to have a separate processor file (PHP) that receives the data, processes it, and sends it back.
To convert a <form> construct to AJAX, you really just need to remove the <form></form> tags and convert the submit button from type="submit" to type="button" id="mybutton", and use the IDs on the button and on the other elements to grab the data they contain and feed them to the AJAX code block. The examples in the link at bottom shows what you need to know - they are simple, helpful examples.
To conserve resources, you can use the same PHP processor page for multiple AJAX requests -- just send a variable (eg. 'request=save_to_db&first_name=bob&last_name=jones', ) and test for what "request" is received, that will determine what your PHP processor file does and echoes back.
This post, and the examples it contains, will help.
try this first
In you coding you missed this $_POST['button']
and
<?php
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
and also refer this FIDDLE it will more helpful to you..

Display message including the session name

Is there a way, when clicking on a button, using HTML and PHP, to display an alert message containing the name of the session started, a radio button checked and the date and time choose? The button is included in a form, so I am looking if there is way to get these things done...
Here's my code:
<?php
if (!isset($_SESSION)) {
session_start();
}
echo $_SESSION["uname"]; ?>
</div>
<br>
<form id="form1" action="welcome.php" method="post" >
Blood Type Needed :
<br>
<br>
<input id="input1" type="Radio" value="A+" name="bn"/> A
<input id="input1" type="Radio" value="B+" name="bn"/> B
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
$('input[#name="bn"]:checked').val();
var radios = document.getElementsByName('bn');
if (radios.checked) {
function showSession(){
var x=document.getElementById("sessionId");
var y=new Date();
alert(x.value+" wants "+radios.value+y);
}
}
</script>
<input id="done" class="button1" type="button" onClick="showSession();" value=" DONE ">
</form>
I will use a INPUT hidden and a javascript function, after attack it to onClick event on your button, but suggest you use Jquery to make all cross-browser:
HTML input
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
JAVASCRIPT
function showSession(){
var x=document.getElementById("sessionId");
alert(x.value);
}
HTML BUTTON
<input type="button" value="Click me" onClick="showSession();" />
FULL SCRIPT
<?php
if (!isset($_SESSION)) session_start();
echo "Session ID: ".$_SESSION["uname"];
?>
</div><br/>
<script>
function showData(){
var sessionId = document.getElementById("sessionId").value;
var today = new Date();
var x = document.getElementsByName('bn')
var selected = false;
// Check the selected value
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert(' '+ sessionId + " wants " + x[k].value + " " +today);
selected = true;
}
if (!selected) alert('Select something please...');
}
</script>
<form id="form1" action="welcome.php" method="post" ><br/>
Blood Type Needed :<br/><br/>
<input id="AP" type="Radio" value="A+" name="bn"/><label for="AP"> A</label><br/>
<input id="BP" type="Radio" value="B+" name="bn"/><label for="BP"> B</label><br/><br/>
<input id="done" type="button" onClick="showData();" value=" DONE " class="button1">
<input type="hidden" id="sessionId" value="<?php echo $_SESSION['uname']; ?>" />
</form>
You can do this by using simple Javascript
<script>
function showValue()
{
var sessionVal=<?php echo $_SESSION['uname']; ?>;
var selectedDate=documnet.form1.dt.value;
var selectedRadio=document.form1.bn.value;
alert(sessionVal+" "+selectedRadio+" "+selectedDate); //what ever format you want to show.
document.form1.actiom='welcome.php';
document.form1.submit();
}
</script>
In your html add onsubmit function
<form id="form1" action="" onsubmit="return showValue();" method="post" >

Adding numbers using HTML forms and PHP

I'm trying to make a simple web application that adds scores from a physical game such as Scrabble. Most of the code is a HTML form, asking for one input per form element. It then puts the data generated from the form and initializes the appropriate variables. The one part I can't figure out is how to add the new score to the last score. I tried to add variables, like $lastScore, but that didn't seem to work either. Does anyone have any suggestions?
<?php
//Gets data from HTML form
$addScore1 = $_REQUEST['addScore1'];
$addScore2 = $_REQUEST['addScore2'];
//Generates HTML form
echo "<!DOCTYPE html>
<html>
<head>
<title>Score Add</title>
</head>
<body>
<div id=\"displayNames\">
<p>
$player1
<form method=\"post\" action=\"\">
<label for=\"addScore1\">Enter your score:</label>
<input type=\"text\" name=\"addScore1\" id=\"addScore1\" />
<input type=\"submit\" />
</form>
</p>
<p>
$player2
<form method=\"post\" action=\"\">
<label for=\"addScore2\">Enter your score:</label>
<input type=\"text\" name=\"addScore2\" id=\"addScore2\" />
<input type=\"submit\"/>
</form>
</p>
</div>
</body>
</html>";
?>
On submit, the script is calling itself and loses all the variables. You need to store their current score, e.g. in the session, in a database, or in a hidden field in the form.
With hidden field in your form:
<form method="post" action="">
<label for="addScore1">Enter your score:</label>
<input type="text" name="addScore1" id="addScore1" />
<--! the addition is done in the next line in value-->
<input type="hidden" name="oldScore1" id="oldScore1" value="<?=($oldscore1 + $addScore1)?>" />
<input type="submit" />
</form>
Do the same with your second form --> oldScore2 etc...
At the top of your script, read the oldscore from $_REQUEST
//Gets data from HTML form
$addScore1 = $_REQUEST['addScore1'];
$addScore2 = $_REQUEST['addScore2'];
$oldScore1 = $_REQUEST['oldScore1'];
$oldScore2 = $_REQUEST['oldScore2'];
// as alternative, do the addition here:
$oldScore1 += $addScore1;
$oldScore2 += $addScore2;
Rewriting your code as a whole, try it:
I edited all those <?php=$somevalue?>because they don't seem to work with your PHP-setup, and replaced them with <?php echo $somevalue> ?>... let me know how it works...
<?php
// Get data from HTML form. $_POST is fine, because form method is set to POST.
$addScore1 = $_POST['addScore1'];
$addScore2 = $_POST['addScore2'];
$oldScore1 = $_POST['oldScore1'];
$oldScore2 = $_POST['oldScore2'];
// if these are numeric values, add them up
if (is_numeric($addScore1) && is_numeric($oldScore1)) $oldScore1 += $addScore1;
if (is_numeric($addScore2) && is_numeric($oldScore2)) $oldScore2 += $addScore2;
// Generate HTML form -- in HTML, much to complicated in PHP, unless it is necessary for sth else
?>
<html>
<head>
<title>Score Add</title>
</head>
<body>
<div id="displayNames">
<p><?php echo $player1; ?> current score: <?php echo $oldScore1; ?>
<form method="post" action="">
<label for="addScore1">Enter your score:</label>
<input type="text" name="addScore1" id="addScore1" />
<input type="hidden" name="oldScore1" id="oldScore1" value="<?php echo $oldscore1; ?>" />
<input type="submit" />
</p>
<p><?php echo $player2; ?> current score: <?php echo $oldScore2; ?>
<label for="addScore2">Enter your score:</label>
<input type="text" name="addScore2" id="addScore2" />
<input type="hidden" name="oldScore2" id="oldScore2" value="<?php echo $oldscore2; ?>" />
<input type=\"submit\"/>
</form>
</p>
</div>
</body>
</html>

Categories