I have these pages:
secondpage.php
<center>
Go back
<form action="fourthpage.php" method="POST">
<select name="what" class="what" required oninvalid="this.setCustomValidity('Please enter what are you paying for ')" oninput="setCustomValidity('')" />
<option value="" disabled selected>Choose what you are paying for</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
<option>Something</option>
</select>
<br>
<button>other...</button>
<br><br>
<label for="price">Type the price</label>
<br>
<input id="amount" name="price" placeholder="€" required oninvalid="this.setCustomValidity('Please enter the price ')" oninput="setCustomValidity('')" / type="number">
<br><br>
<label for="payment">Who has to pay for it:</label>
<br>
<label for="everybody">Everybody</label>
<input name="check_list[]" class="everybody" type="checkbox" value="everybody" onclick="ckChange(this)" required>
  
<label for="John">John</label>
<input name="check_list[]" class="John" type="checkbox" value="John" required>
  
<label for="Peter">Peter</label>
<input name="check_list[]" class="denis" type="checkbox" value="Peter" required>
  
<label for="Ferrari">Ferrari</label>
<input name="check_list[]" class="Ferrari" type="checkbox" value="Ferrari" required>
<br>
<input type="submit" name="submit" value="SEND">
</form>
</center>
fourthpage.php
<table>
<center><h1>John</h1></center>
<tr><td>WHO </td><td>WHAT </td><td>HOW MUCH</td><td>MY DEBT</td><td>TOTAL DEBT</td></tr>
<tr><td class="d"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
echo $selected."</br>";
}}} ?></td>
<td class="r"><?php if (isset($_POST['submit'])) { echo $_POST["what"];} ; ?></td>
<td class="a"><?php if (isset($_POST['submit'])) { echo $_POST["price"];} ; ?></td>
<td class="debt"><?php if(isset($_POST['submit'])){//to run PHP script on submit
if(!empty($_POST['check_list'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['check_list'] as $selected){
if ($selected == 'everybody'){ echo $_POST["price"]/4;}
elseif ($selected == 'John' || 'Peter' || 'Ferrari'){ echo $_POST["price"]/2;}
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;} ;
}}}?> </td></tr>
<td class="total"><?php if (isset($_POST['submit'])) { ;} ; ?></td></tr>
</table>
<button onClick="location.reload();location.href='secondpage.php'">ADD</button> <button>PAY</button></center>
and javascript
function ckChange(el) {
var ckName = document.getElementsByName(el.name);
if (el.checked) {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = ckName[i] !== el;
}
} else {
for (var i = 0; i < ckName.length; i++) {
ckName[i].disabled = false
}
}
}
$(function(){
var requiredCheckboxes = $(':checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
}
else {
requiredCheckboxes.attr('required', 'required');
}
});
});
When i try to get the answer of 2 checked checkboxes like
elseif ($selected == 'John' && $selected == 'Peter') { echo $_POST["price"]/3;}
it doesn't give me the right answer. I don't get the price divided by 3. For example: i chose the price 15 and under debt should be 15/3 = 5. Instead of 5 i get 7.5 7.5. Any solutions?
The problem not just in
elseif ($selected == 'Jacopo' && 'Denis' && 'Angus'){ echo $_POST["price"]/2;}
So first you want to know that this line must wrote like this.
elseif ($selected == 'Jacopo' || $selected == 'Denis' || $selected == 'Angus'){ echo $_POST["price"]/2;}
And Second you don't want to use another foreach. we want to make sure that the elements you're looking for inside the check_list array, So you can use in_array() function.
This is your final code.
<td class="debt"><?php
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])){
if (in_array('everybody', $_POST['check_list'])){ echo $_POST["price"]/4;}
elseif (in_array('Jacopo', $_POST['check_list']) && in_array('Denis', $_POST['check_list'])) { echo $_POST["price"]/3;}
elseif (in_array('Jacopo', $_POST['check_list']) || in_array('Denis', $_POST['check_list']) || in_array('Angus', $_POST['check_list'])){ echo $_POST["price"]/2;}
}
}
?></td>
I hope everything is clear and i hope i helped you.
I think you want it like this (correct me if not):
if "everybody" was checked, case 1
if ALL THREE (respectively TWO) boxes with names are checked, cases 2 or 3
any other combination will be ignored
In this case you must ensure, that $_POST['check_list'] has all the required items checked and nothing more. Please consider the following example:
// to play around with...
$_POST['check_list'] = ['everybody', 'Jacopo', 'Denis'];
$case1 = ['everybody'];
$case2 = ['Jacopo', 'Denis', 'Angus'];
$case3 = ['Jacopo', 'Denis'];
$result1 = array_intersect($_POST['check_list'], $case1);
$result2 = array_intersect($_POST['check_list'], $case2);
$result3 = array_intersect($_POST['check_list'], $case3);
if (count($case1) == count($result1)) {
echo 'case 1';
}
elseif (count($case2) == count($result2)) {
echo 'case 2';
}
elseif (count($case3) == count($result3)) {
echo 'case 3';
}
The array_intersect will compare all arrays to find things in common. Anything that is not in any of the other arrays will be removed. Set theory.
edit: fixed typos
Related
I have created a jquery code for my checkbox. My jquery codes working like this. If user checked some two checkboxes then I give alert like alert("You can not select this two checkbox");
$("body").on("click", ".submit", function(){
var lookChecked = $('#c').is(':checked');
var lookCheckedTwo = $("#java").is(':checked');
var lookCheckedTree = $("#php").is(':checked');
var lookCheckedFour = $("#html").is(":checked");
var lookCheckedFive = $("#unix").is(":checked");
if(lookChecked && lookCheckedTwo || lookChecked && lookCheckedTree) {
alert("You can not select #c and #java or #c and #php at the same time");
}
});
This is working fine. But I want to check it also with PHP
if(isset($_POST['submit'])){
if(!empty($_POST['check_list'])) {
// Seçimlerin toplamını kontrol et
$checked_count = count($_POST['check_list']);
if($checked_count >=3) {
echo "You can not select ".$checked_count." ";
}else{
echo "".$checked_count." checkbox result for: <br/>";
foreach($_POST['check_list'] as $selected) {
echo "<p>".$selected ."</p>";
}
}
}
else{
echo "<b>Please select a checkbox</b>";
}
}
HTML
<form action="index.php" method="post">
<label class="heading">Select your categories:</label>
<input type="checkbox" name="check_list[]" id="c" value="C/C++"><label>C/C++</label>
<input type="checkbox" name="check_list[]" id="java" value="Java"><label>Java</label>
<input type="checkbox" name="check_list[]" id="php" value="PHP"><label>PHP</label>
<input type="checkbox" name="check_list[]" id="html" value="HTML/CSS"><label>HTML/CSS</label>
<input type="checkbox" name="check_list[]" id="unix" value="UNIX/LINUX"><label>UNIX/LINUX</label>
<input type="submit" class="submit" name="submit" Value="Submit"/>
<!----- Including PHP Script ----->
<?php include 'checkbox_value.php';?>
</form>
So what I want to do with PHP. If the user checked C/C++ and Java same time. I want to show a just warning. (No result for C/C++ and Java please select another category) or if the user selected PHP and Unix (No result for PHP and Unix please select another category). How can I do that with PHP
if (in_array("C/C++", $_POST['check_list']) && in_array("Java", $_POST['check_list'])){
echo "No result for C/C++ and Java please select another category";
}else{
if (in_array("PHP", $_POST['check_list']) && in_array("Unix", $_POST['check_list']))
{
echo "No result for PHP and Unix please select another category";
}
}
The best way is when you change your input name like this:
<input type="checkbox" name="check_list[cc]" id="c" value="C/C++"><label>C/C++</label>
<input type="checkbox" name="check_list[java]" id="java" value="Java"><label>Java</label>
Than check it with PHP
if( isset($_POST['check_list']['cc'],$_POST['check_list']['java']) OR
isset($_POST['check_list']['php'],$_POST['check_list']['html']) ){
echo "You check PHP & HTML or C++ & Java";
} else if( empty($_POST['check_list']) ) {
echo "Please select a checkbox";
} else {
echo "Please select C/C++ & Java or PHP & Java";
}
if user want to submit their form, they have to checked the terma and condition box first.
so where should i add the code?
<?php
// Start the session
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title Goes Here</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="form1.css"/>
</head>
<body onload="disableSubmit()">
<?php
//define variable and set to empty value
$forenameErr = $surnameErr = $emailErr = $postalAddressErr = $landLineTelNoErr = $mobileTelNoErr = $sendMethodErr = "";
$valid = true;
// if forename is null , make it null , else test_input()
$forename = empty($_POST["forename"]) ? NULL : test_input($_POST["forename"]);
// if surname is null , make it null , else test_input()
$surname = empty($_POST["surname"]) ? NULL : test_input($_POST["surname"]);
// if postalAddress is null , make it null , else test_input()
$postalAddress = empty($_POST["postalAddress"]) ? NULL : test_input($_POST["postalAddress"]);
// if landLineTelNo is null , make it null , else test_input()
$landLineTelNo = empty($_POST["landLineTelNo"]) ? NULL : test_input($_POST["landLineTelNo"]);
// if mobileTelNo is null , make it null , else test_input()
$mobileTelNo = empty($_POST["mobileTelNo"]) ? NULL : test_input($_POST["mobileTelNo"]);
//email
$email = empty($_POST["email"]) ? NULL : test_input($_POST["email"]);
// if sendMethod is null , make it null , else test_input()
$sendMethod = empty($_POST["sendMethod"]) ? NULL : test_input($_POST["sendMethod"]);
if (isset($_POST["submit"])){
//check forename
if($forename === NULL) {
//forename is empty
$forenameErr = "*Forename is required";
$valid = false;
} else {
//check characters
if (!preg_match("/^[a-zA-Z ]*$/",$forename)) {
$forenameErr = "Only letters and white space allowed";
$valid = false;
}
}
//check surname
if($surname === NULL){
//surname is empty
$surnameErr = "*Surname is required";
$valid = false; //false
} else {
//check charaters
if (!preg_match("/^[a-zA-Z ]*$/",$surname)) {
$surnameErr = "*Only letters and white space allowed";
$valid = false;
}
}
//check address
if (!preg_match("/^[a-zA-Z0-9\-\\,. ]*$/", $postalAddress)) {
// check characters
$postalAddressErr = "*Invalid Postal Address";
$valid = false;//false
}
// check if invalid telephone number added
if (!preg_match("/^$|^[0-9]{12}$/",$landLineTelNo)) {
//check number
$landLineTelNoErr = "*Only 12 digit number can be entered";
$valid = false;//false
}
//check valid mobiel tel no
if (!preg_match("/^$|^[0-9]{11}$/",$mobileTelNo)) {
//check number
$mobileTelNoErr = "*Only 11 digit number can be entered";
$valid = false;//false
}
//check valid email
if (isset($email) && !filter_var($email, FILTER_VALIDATE_EMAIL))
{ $emailErr = "*Invalid email format";
$valid = false;//false
}
//check sendMethod
if($sendMethod === NULL){
//send method is empty
$sendMethodErr = "*Contact method is required";
$valid = false; //false
} else {
$sendMethod = test_input($_POST["sendMethod"]);
}
//sendmethod link to information filled
if (isset($sendMethod) && $sendMethod=="email" && $email ==NULL){
$emailErr ="*Email is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="post" && $postalAddress ==NULL){
$postalAddressErr ="*Postal Address is required ";
$valid = false;
}
if (isset($sendMethod) && $sendMethod=="SMS" && $mobileTelNo ==NULL){
$mobileTelNoErr ="*Mobile number is required ";
$valid = false;
}
//if valid then redirect
if($valid){
$_SESSION['forename'] = $forename;
$_SESSION['surname'] = $surname;
$_SESSION['email'] = $email;
$_SESSION['postalAddress'] = $postalAddress;
$_SESSION['landLineTelNo'] = $landLineTelNo;
$_SESSION['mobileTelNo'] = $mobileTelNo;
$_SESSION['sendMethod'] = $sendMethod;
header('Location: userdetail.php');
exit();
}
} else{
//user did not submit form!
}
//check
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div id="wrapper">
<h1>Welcome to Chollerton Tearoom! </h1>
<nav>
<ul>
<li>Home</li>
<li>Find out more</li>
<li>Offer</li>
<li>Credit</li>
<li>Admin</li>
<li>WireFrame</li>
</ul>
</nav>
<form id = "userdetail" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<fieldset id="aboutyou">
<legend id="legendauto">user information</legend>
<p>
<label for="forename">Forename: </label>
<input type="text" name="forename" id="forename" value="<?php echo $forename;?>">
<span class="error"> <?php echo $forenameErr;?></span>
</p>
<p>
<label for="surname">Surname:</label>
<input type="text" name="surname" id="surname" value="<?php echo $surname;?>">
<span class="error"> <?php echo $surnameErr;?></span>
</p>
<p>
<label for="postalAddress">Postal Address:</label>
<input type="text" name="postalAddress" id="postalAddress" value="<?php echo $postalAddress;?>">
<span class="error"> <?php echo $postalAddressErr;?></span>
</p>
<p>
<label for="landLineTelNo">Landline Telephone Number:</label>
<input type="text" name="landLineTelNo" id="landLineTelNo" value="<?php echo $landLineTelNo;?>" >
<span class="error"> <?php echo $landLineTelNoErr;?></span>
</p>
<p>
<label for="mobileTelNo">Moblie:</label>
<input type="text" name="mobileTelNo" id="mobileTelNo" value="<?php echo $mobileTelNo;?>" >
<span class="error"> <?php echo $mobileTelNoErr;?></span>
</p>
<p>
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" value="<?php echo $email;?>">
<span class="error"> </span> <?php echo $emailErr;?> </span>
</p>
<fieldset id="future">
<legend>Lastest news</legend>
<p>
Choose the method you recommanded to recevive the lastest information
</p>
<br>
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="email") echo "checked";?> value="email">
Email
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="post") echo "checked";?> value="post">
Post
<input type="radio" name="sendMethod" id="sendMethod" <?php if (isset($sendMethod) && $sendMethod=="SMS") echo "checked";?> value="SMS">
SMS
<span class="error"> <?php echo $sendMethodErr;?></span>
</fieldset>
<p><span class="error">* required field.</span></p>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" value="submit" />
</p>
</form>
</form>
</fieldset>
</form>
</div>
</body>
</html>
and so here is my userdetail.php to get user data...
<?php
session_start();
$forename = $_SESSION['forename'];
$surname = $_SESSION['surname'];
$email = $_SESSION['email'];
$postalAddress = $_SESSION['postalAddress'];
$landLineTelNo = $_SESSION['landLineTelNo'];
$mobileTelNo = $_SESSION['mobileTelNo'];
$sendMethod = $_SESSION['sendMethod'];
echo "<h1>Successfull submission :</h1>";
echo "<p>Forename : $forename <p/>";
echo "<p>Surname : $surname <p/>";
if($_SESSION['postalAddress']==NULL)
{echo "<p>postalAddress:NULL</p>";}
else {echo "<p>PostalAddress : $postalAddress </p>";}
if($_SESSION['email']==NULL)
{echo "<p>email:NULL<p/>";}
else {echo "<p>email : $email</p>";}
if($_SESSION['landLineTelNo']==NULL)
{echo "<p>landLineTelNo:NULL<p/>";}
else {echo "<p>landLineTelNo : $landLineTelNo </p>";}
if($_SESSION['mobileTelNo']==NULL)
{echo "<p>mobileTelNo:NULL<p/>";}
else {echo "<p>mobileTelNo : $mobileTelNo </p>";}
echo "<p>sendMethod : $sendMethod </p>";
?>
i need the term and condition check box to be checked else use cannot submit the form....
REMEMBER! Using javascript will just make it easy for user.It prevents loading another page to display error. STILL if a browser has javascript turned of it will pass the checked Terms without even checking it. so you should Always check it serverside (PHP) and use javascript for users ease.
in your HTML:
<form id="userdetail" ....>
...
<input type="checkbox" name="terms" id="terms" value="accepted" />
...
</form>
then in your javascript:
Pure JS:
document.getElementById('userdetail').addEventListener('submit', function(event){
if(document.getElementById('terms').checked == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
Using JQuery (jquery.com)
$('#userdetail').submit(function(event){
if($('#terms').is(':checked') == false){
event.preventDefault();
alert("By signing up, you must accept our terms and conditions!");
return false;
}
});
and in your PHP to check if it is checked you should use
if(isset($_POST['terms']) && $_POST['terms'] == 'accepted') {
// Continue Registring
} else {
// Display Error
}
Instead of submit you do:
<input type="button" onclick="javascript:myFunction()" Value="Submit">
And then the javascript function:
function myFunction() {
if(document.getElementById("terms").checked == true){
document.getElementById("userdetail").submit();
}
else{
alert("You have to agree on terms and conditions");
}
}
In Jquery you can do like below:
<script>
$('#userdetail').submit(function(){
if($('#terms').is(':checked'))
{
return true;
}
else
{
return false;
}
});
</script>
Replace the part of html with the given html in answer and add the function below to you script...
function verify_terms()
{
if (!$('#terms').is(':checked'))
{
alert('Please agree terms and conditions');
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" name="terms" id="terms">
I have read and agree to the Terms and Conditions and Privacy Policy
<br><br>
<p>
<input type="submit" name="submit" onclick="return verify_terms();" value="submit" />
I have this code which delete from database rows.But it removes one by one when pressing delete, checkbox not working.I want to multiple delete by checking checkbox.
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
function check() {
document.getElementById("myCheck").checked = true;
}
function uncheck() {
document.getElementById("myCheck").checked = false;
}
HTML
<a href="javascript:confirmDelete('?action=deleteurl&id=<?php echo $row[0]; ?>')">
<input type="checkbox" id="myCheck[]">delete</td>
PHP
<?php
if($_GET['action'] == "deletelink" && !empty($_GET['id']) && is_numeric($_GET['id'])) {
$result = mysql_query("SELECT * FROM books WHERE id='".intval($_GET['id']);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
}
Your logic is not for multiple delete
this should be html
<input type="checkbox" id="myCheck[]" class="multicheck" name="<?php echo $row[0]; ?>" value="<?php echo $row[0]; ?>">delete</td>
Multiple Delete</td>
and this should be javascript
function confirmMultiDelete() {
if (confirm("Are you sure you want to delete")) {
var str = [];
$.each(".multicheck:checked",function(){
str.push($(this).val());
});
ids = str.join(",");
document.location = '?action=deleteurl&id='+ids;
}
}
here is my approach.
You need some modification to do multiple delete as my approach.
First you have to put value in checkbox so you can get its value to
delete.
Second you have to add another button or action to delete multiple
record.
Your Code ( with Modification ):
HTML + PHP CODE
<a href="javascript:confirmDelete('?action=deleteurl&id=value="<?php echo $row[0]; ?>"')">delete
</a>
<input type="checkbox" class="delCheck" id="myCheck[]" value="<?php echo $row[0]; ?>">
</td>
<!-- This will generate html code like below -->
<!--
<td>
delete
<input type="checkbox" class="delCheck" value="1" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="2" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="3" id="myCheck[]" class="delCheck">
</td>
<td>delete
<input type="checkbox" class="delCheck" value="4" id="myCheck[]" class="delCheck">
</td>
<td>
<input type="button" value="Delete" name="delete_value" id="delete_value" class="delCheck">
</td>
-->
<!-- Multiple Delete Button -->
<input type="button" id="delete_value" name="delete_value" value="Delete" />
Javascript + Jquery
function confirmDelete(delUrl) {
if (confirm("Are you sure you want to delete")) {
document.location = delUrl;
}
}
$( document ).ready(function() {
$("#delete_value").on("click", function (e){
var ids = '';
$('.delCheck:checked').each(function(i){
ids += $(this).val() + ',';
});
// go to delete url with action delete_all_ur
confirmDelete('?action=delete_all_url&id='+ids)
});
});
PHP Delete Code:
if( #$_GET['action'] == "delete_all_url" )
{
$all_ids = $_GET['id'];
// Remove trailing ',' from IDs
$all_ids = trim($all_ids, ",");
// Temporary variable to check only integer value passes
$tempId = str_replace(",", "", $all_ids);
// Check id numeric or not
if ( is_numeric($tempId) ) {
$sql_query = "SELECT * FROM books WHERE id in (".intval($_GET['id'].")";
$result = mysql_query($sql_query);
while ($row = mysql_fetch_array ($result) )
unlink("/home/me/public_html/upload/image/{$row['image']}");
} else {
//echo 'errors';
}
}
I am working on a very simple php page. The user picks how many numbers they would like to be added up, then enters the numbers on the new page, clicks a button, and then the sum is displayed.
I cannot figure out how to add up the numbers though since I can't just assign variables to each number because of the loop. I've tried this not using loops, assigning variables to each one, and simply making the button add those variables, but that required making the code for the inputs many many times, and I want this to work with a loop in case I wanted to integrate the choice to pick hundreds of numbers or something. If php isn't the best thing for this, please let me know what would be better, but anyways... how do I add up the numbers that the user inputs?
Index page:
<p>How many number would you like to add?</p>
2<br>
3<br>
4<br>
5<br>
Calculator page:
<?php
$inputs = $_GET['inputs'];
?>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
?>
</div>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'></form>
<?php
if (isset($_POST['findvalue'])) {
}
?>
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number"><br>';
}
You cant use input without any name. You can use dynamic name, for example:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number_'.$x.'"><br>';
}
Or better way to use array names:
for ($x=0; $x < $inputs; $x++) {
echo '<input type="number" name="number[]"><br>';
}
After that, var_dump your $_POST variable.
But, best way to create dynamic fields is creating one and clone it with javascript, when user want to add next value. Example with jQuery:
<div class="myInputs"><input type="number" name="numbers[]"></div>
Add input
<script>
$('#Add').click(function(){
$('.myInputs input:first').clone().appendTo(".myInputs");
return false;
});
Try this:
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'>
<div>Enter the numbers<br>
<?php
for ($x=0; $x < $inputs; $x++) {
echo '<input name="numbers[]" type="number"><br>';
}
?>
</div>
<input type='submit' value='Find value' name='findvalue'>
</form>
<?php
if (isset($_POST['findvalue'])) {
print_r($_POST["numbers"]);
}
?>
There is currently no JavaScript on your page. To interact with the client, JavaScript would be the best choice since there is no need to go to the backend to create input fields unless you need to save the number before interacting with the user
window.onload = function() {
document.getElementById("nums").onchange = function() {
var fields = document.getElementById("fields"),
numberOfField = parseInt(this.value, 10),
inputs = [];
for (var i = 0; i < numberOfField; i++) {
inputs.push('<input type="text" class="calcField" name="number' + i + '" />');
}
fields.innerHTML = inputs.length > 0 ? inputs.join("<br/>") : "";
}
document.getElementById("calc").onsubmit = function() {
var total = 0,
fields = document.querySelectorAll(".calcField");
for (var i = 0; i < fields.length; i++) {
var val = parseInt(fields[i].value, 10);
total += isNaN(val) ? 0 : val;
}
document.getElementById("total").value=total;
return false; // stop submission - remove to submit the form
}
}
<p>How many numbers would you like to add?</p>
<form id="calc">
<select id="nums">
<option value="0">Please select</option>
<option value="2">Two numbers</option>
<option value="3">Three numbers</option>
<option value="4">Four numbers</option>
</select>
<div id="fields"></div><hr/>
<input type="submit" value="Find value" /> <input type="text" id="total" />
</form>
try adding a hidden field for the number of inputs then use it to loop
<?php
$inputs = $_GET['inputs'];
?>
<form action='' method='post'><input type='submit' value='Find value' name='findvalue'>
<div>Enter the numbers<br>
<input type="hidden" name="numberofinputs" value="<?php echo $inputs;?>"/>
<?php
for ($x=0; $x < $inputs; $x++) {
//Please note the $x
echo '<input type="number'.$x.'"><br>';
}
?>
</div>
</form>
<?php
if (isset($_POST['findvalue'])) {
$numberOfinputs = $_POST['numberofinputs'];
for($i=0; $i<numberOfinputs; $i++){
//You can access it here
echo $_POST['number'.$i];
}
}
?>
how can i make textarea a read only but will not be greyed out?
i am using this script but its not working:
$(".readonly").keydown(
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
)
i tried to use <textarea readonly> but its making the field greyed out, I want it to be readonly but dont want the textarea field to change to being greyed out.
here is my entire code:
<body>
<form name="search" method="post" action="">
<fieldset style='width: 500px'>
<legend align='left'><strong>Search</strong></legend>
<p>
Seach for: <input type="text" name="find" id="find" /> in
<Select NAME="field" id="field">
<Option VALUE="testA">A</option>
<Option VALUE="testB">B</option>
<Option VALUE="testC">C</option>
<Option VALUE="testD">D</option>
</Select>
<input type="hidden" name="searching" value="yes" />
<input type="submit" name="search" id="search" value="Search" />
</p>
</fieldset>
</form>
<script>
$(".readonly").keydown(
function keydown(e) {
if(!e.ctrlKey) return false; // Cancel non ctrl-modified keystrokes
if(e.keyCode == 65) return true;// 65 = 'a'
if(e.keyCode == 67) return true;// 67 = 'c'
return false;
}
)
</script>
<?php
//This is only displayed if they have submitted the form
if (isset($_POST['searching']) && $_POST['searching'] == "yes")
{
//If they did not enter a search term we give them an error
if (empty($_POST['find']))
{
echo "<p>You forgot to enter a search term";
exit;
}
// Otherwise we connect to our Database
mysql_connect("host", "username", "passw") or die(mysql_error());
mysql_select_db("testdb") or die(mysql_error());
// We preform a bit of filtering
$find = strtoupper($_POST['find']);
$find = strip_tags($_POST['find']);
$find = trim ($_POST['find']);
$field = trim ($_POST['field']);
//Now we search for our search term, in the field the user specified
$data = mysql_query("SELECT * FROM testtable WHERE UPPER($field) LIKE UPPER('%$find%')");
//And we display the results
while($result = mysql_fetch_array( $data ))
{
$myRes = "<form action='' method='post'>
<fieldset style='width: 10px'>
<legend align='left'><strong>Results</strong></legend>
<p>
<table width='auto' border='1' cellspacing='1' cellpadding='1' align='center'>
<tr>
<th align='center' scope='row'>A</th>
<td><textarea class=readonly name=testA id=testA cols=65 rows=3>" . $result['testA'] . "</textarea></td>
</tr>
<tr>
<th scope='row'>B</th>
<td><textarea class=readonly name=testB id=testB cols=65 rows=3>" . $result['testB'] . "</textarea></td>
</tr>
</table>
</p>
</fieldset>
</form>";
}
echo $myRes;
//This counts the number or results - and if there wasn't any it gives them a little message explaining that
$anymatches=mysql_num_rows($data);
if ($anymatches == 0)
{
echo "Sorry, but we can not find an entry to match your query<br><br>";
}
//And we remind them what they searched for
echo "<b>Searched For:</b> " .$find;
}
?>
</body>
You could use css
something like
textarea[readonly="readonly"], textarea[readonly] { //your styling }
eg
textarea[readonly="readonly"], textarea[readonly] { background-color:white; }
Also note that the mysql_ functions have been deprecated. You should MySQLi or PDO with prepared statements.
Looking at your code you are using class=readonly, unless you've actually created that class in css you should be using
<textarea readonly></textarea>