php input form can only be numbers not words - php

i made a form where you can put a number and show which one is the highest.
i want to make sure you can put any words in this form.
that there show a notification you cant put words in the form
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="text" name="tweedegetal" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>

The following code shows a notification when a letter is typed.
<?php
function maxGetal($getal1, $getal2)
{
if ($getal1 > $getal2) {
return ($getal1);
} elseif ($getal2 > $getal1) {
return ($getal2);
} else {
return ("gelijk");
}
}
?>
<form action="" method="post">
<input type="text" id="eerstegetal" name="eerstegetal" oninput="Eerste_check()" placeholder="Eerste getal"><br>
<input type="text" id="tweedegetal" name="tweedegetal" oninput="Tweede_check()" placeholder="Tweede getal"><br>
<input type="submit" name="submit" value="Bereken hoogste getal">
<p> -----------------------------------------------------------------------</p>
</form>
<?php
if (isset($_POST["submit"])) {
$maxgetal = maxGetal($_POST["eerstegetal"], $_POST["tweedegetal"]);
echo $maxgetal;
}
$input1 = doubleval($_POST["eerstegetal"]);
$input2 = doubleval($_POST["tweedegetal"]);
?>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"></script>
<script>
function Eerste_check(){
var eerstegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(eerstegetal)){
alert('Eerstegetal should contain only numbers.')
}
}
function Tweede_check(){
var tweedegetal = $('#eerstegetal').val()
var pattern = /^\d+\.?\d*$/;
if(!pattern.test(tweedegetal)){
alert('Tweedegetal should contain only numbers.')
}
}
</script>

Try the following:
<input type="number" name="eerstegetal" placeholder="Eerste getal"><br>
<input type="number" name="tweedegetal" placeholder="Tweede getal"><br>
I hope it helps

Related

Not inserting null values

I am trying to insert multiple values in the todo input of the form. but if i do not input a value to any input the null value is inserted in the database. This is my controller action:
public function actionAdd()
{
if (Yii::$app->request->isAjax) {
$request = Yii::$app->request;
$add = new Project();
$add->project_name = $request->post('project');
$add->deadline = $request->post('deadline');
$add->profile_id = $request->post('profile_id');
$add->project_status = "Running";
$add->save();
$getlast = Yii::$app->db->getLastInsertId();
$todo = $request->post('todo');
if (isset($todo)) {
foreach ($todo as $to) {
$add = new Todo();
$add->todo_name=$to;
$add->status="Running";
$add->project_id=$getlast;
$add->save();
}
}
echo json_encode(TRUE); die;
}
echo json_encode(FALSE);die;
}
the form is:
<form class="formclass" method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/todo/add/" role="form" id="register-form" novalidate="novalidate">
<label> Project Name: </label> <input type="name" name="project" class="form-control" placeholder="Project Name" required><br><br>
<input type="hidden" name="profile_id" value="<?php echo $profile_id;?>">
<label> Todo: </label><br>
<textarea type="text" name="todo[]" placeholder="Todo Description..."></textarea>
<div id="dynamicInput">
<span class="glyphicon glyphicon-plus" onClick="addInput('dynamicInput');"></span>
</div><br>
<label> Project Deadline:</label><br>
<input type="date" name="deadline"><br><br>
<button type="submit" class="btn btn-default">Add Project</button><BR><BR>
</form>
And the jquery is:
var counter = 1;
var limit = 10;
function addInput(divName)
{
if (counter != limit)
{
var newdiv = document.createElement('div');
newdiv.innerHTML = "<br><textarea type='text' name='todo[]' placeholder='Todo Description...'></textarea>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
Could be you problem is related to the validation rules ..
for check this and only for debugging try use $add->savel(false)
$add = new Todo();
$add->todo_name=$to;
$add->status="Running";
$add->project_id=$getlast;
$add->save(false);
if in this case the rows are inserted the check for validations rule (eventually comment temporary) .. for find the wrong rules or condition

how to return a value in PHP Factorial Program

I am working on one of my assignment for Factorial Program. I am struck on one point.
Fact.php
<html>
<body>
<form action="FactCalc.php" method="post">
Enter a Number: <input type="text" name="number">
<input type="submit" Value="Calculate Factorial">
</form>
</body>
</html>
FactCalc.php
<?php
$num = $_POST["number"];
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
this program is running fine. I want to return $factorial to Fact.php and display it there below the text box. I am kind of struck here, can you please help.
<?php
if (isset($_POST["number"]))
{
$_POST["number"] = ($_POST["number"] * 1);
include "FactCalc.php";
}
?>
<form action="FactCalc.php" method="post">
<p>
Enter a Number:
<input type="text" name="number">
<input type="submit" Value="Calculate Factorial">
<?php
if (isset($factorial))
{
echo "</p><p>Factorial of $num is $factorial";
}
?>
</p>
</form>
You can use AJAX for this but here is a simple way, hope you get an idea...
<?php
$result="";
if(isset($_POST['ispost']) && $_POST['ispost']=="y"){
$num = $_POST["number"];
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
$result="Factorial of ".$num." is ".$factorial;
}
?>
<html>
<body>
<form action="" method="post">
<input type="hidden" name="ispost" value="y" />
Enter a Number: <input type="text" name="number" />
<input type="submit" value="Calculate Factorial /">
</form>
<?php print($result); ?>
</body>
</html>
Here is the AJAX enabled, more eloquent solution. This answer anticipates potential conflict problems with the "$", and potential caching problems with jQuery.get or post
Fact.php:
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.11.0.min.js"></script>
</head>
<body>
<form action="" method="post">
<input type="hidden" name="ispost" value="y" />
Enter a Number: <input type="text" name="number" id="number" />
<input type="button" id="factorial_button" value="Calculate Factorial /">
</form>
<script>
jQuery(document).ready(function(){
jQuery("#factorial_button").click(function(){
var number = jQuery("#number").val();
jQuery.ajax({
url: "FactCalc.php",
type: "POST",
data: {
"number":number,
},
dataType : "html",
cache: false,
beforeSend: function () {
jQuery("#result").html("retrieving information...");
},
success: function( data ) {
jQuery("#result").html(data);
},
error: function( xhr, status, errorThrown ) {
jQuery("#result").html("Ajax error");
}
});
});
});
</script>
<div id="result"></div>
</body>
</html>
FactCalc.php:
<?php
$num = $_POST["number"];
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
echo "Factorial of $num is $factorial";
?>
You can do something like this
Fact.php
<?php
if(isset($_POST["number"]))
{
$num = $_POST["number"];
$factorial = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial = $factorial * $x;
}
}
else
$factorial = "";
?>
<html>
<body>
<form action="" method="post">
Enter a Number: <input type="text" name="number">
<input type="submit" Value="Calculate Factorial">
<?php
if($factorial)
echo "Factorial of $num is $factorial";
?>
</form>
</body>
</html>
You can't "share" the variable between FactCalc.php and Fact.php
**try this very easy to use this factorial**
<?php
$fact=1;
for($i=5;$i>=1;$i--)
{
$fact=$fact*$i;
}
echo $fact;
?>
function factorial($number) {
if ($number < 2) {
return 1;
} else {
return ($number * factorial($number-1));
}
}
Check code demo here

HTML form with 2 (hidden) submit buttons and 1 other hidden input

I'm trying to build this application that runs on Android tablets with barcode scanners attached.
The barcode scanners send an Enter after each scanned code.
I need to scan 2 barcodes and submit the form.
I created a form with two sets of input + submit button, the second one hidden. After the first barcode is scanned and the scnner send the Enter key, the hidden elements are revealed and I can scan the second barcode. However, the second time the Enter key doesn't work. It only work if I push the button (after I unhide it).
How can I take care of this so it will not need user input (other than scanning barcodes)?
Here's my code so far:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
</fieldset>
</form>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
</script>
And the barcode.php file:
<?php
ob_start();
mysql_connect ("localhost","root","root") or die (mysql_error());
mysql_select_db ("eficacitate");
$barcode = $_POST["barcode"];
$kos = $_POST["kos"];
$marca = $_COOKIE["marca"];
$operation = $_COOKIE["operation"];
if (substr($barcode,0,1)=="^") {
$j_nou = substr($barcode,1,strpos($barcode, "|")-1);
$parts = explode('|',$barcode);
$of_nou = $parts[1];
$cantitate_nou = $parts[2];
$serie_nou = $parts[3];
$adauga="INSERT INTO master (marca, operation,j,of,cantitate,serie,kos)
VALUES
('$marca','$operation','$j_nou','$of_nou','$cantitate_nou','$serie_nou','$kos')";
mysql_query($adauga);
}
header('Location: /eficacitate/scan.php');
ob_flush();
?>
Please give this a try:
<form action="barcode.php" method="post" class="pure-form" style="width:100%">
<fieldset>
<legend>Scaneaza o fisa noua de <?php echo $operation; ?>:</legend>
<input type="text" name="barcode" autofocus id="InputID" placeholder="Codul de bare" style="width:100%;font-size:2em">
<button id='barcodeButton' style="width:0;visibility:hidden;" type="submit" onclick="show_popup('my_popup'); return false;"></button>
<div id="my_popup" style="display:none;border:3px dotted gray;padding:.3em;background-color:white;position:absolute;width:80%;height:20%;margin:-50px 50px 0 50px;">
<legend>Introdu numarul de KO-uri:</legend>
<input type="text" name="kos" autofocus id="InputID" placeholder="KO-uri" style="width:100%;font-size:2em">
<button id='kosButton' type="submit" class="pure-button pure-button-primary" style="/*width:0;visibility:hidden;*/" onclick="hide_popup('my_popup'); return true;">Trimite</button>
</div>
<script type="text/javascript">
function FocusOnInput() { document.getElementById("InputID").focus(); }
document.onkeydown = function(event) {
if (event.keyCode == '13') {
barcodeButton = document.getElementById('barcodeButton');
kosButton = document.getElementById('kosButton');
if (document.getElementById('my_popup').style.display == 'none') {
barcodeButton.click();
show_popup('my_popup');
} else {
kosButton.click();
hide_popup('my_popup');
}
}
}
function show_popup(id) {
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == "none") {
obj.style.display = "";
}
}
}
function hide_popup(id){
if (document.getElementById){
obj = document.getElementById(id);
if (obj.style.display == ""){
obj.style.display = "none";
}
}
}
Let me know if this solves what you are trying to achive. Just out of curiosity, why aren't you using jQuery here?

display alert when form is submitted

I need to display the alert saying thanx your msg is received but this doesnot works so please hel me out how to do.Is there coding error or what i coudnt get to it.i would pe pleased if someone helps me out.thankyou
<h4>Send Your Feedback Here.<p>
<form name ="register" action="contact.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="validate()">Send</button>
</p>
</form>
<script type="text/javascript">
function validate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y)
{
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="")
{
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="")
{
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="")
{
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="")
{
alert(msg);
}
else
{
<?php
//Get message data.
$name = $_POST['name'];
$message = $_POST['message'];
$email=$_POST['email'];
$ver = $_POST['ver'];
$rval = $_POST['rval'];
if($ver==$rval)
{
//Email it.
mail(
'example#example.com', //Where to send
"Contact form - $name", //Email subject
$message, //Message body
$email //email address
);
echo "<script type=\"text/javascript\">alert('Thank you form is submitted');</script>";
}
else
{
echo "<script type=\"text/javascript\">alert('Wrong captcha');</script>";
}
?>
}
}
You can't mix JavaScript and PHP like that. The PHP will be parsed on the served before the page is served up to the user. Including it inside of your JavaScript else block will have no effect, since the code will be run when the page is generated anyway.
You should look into the use of AJAX.
<script type="text/javascript">
function thevalidate()
{
var x = document.register.ver.value;
var y = document.register.rval.value;
var nameCheck = document.register.name.value,
emailCheck = document.register.email.value,
msgCheck = document.register.message.value;
var msg ="";
if(x!=y) {
msg+= "Sorry!! Captcha Mismached."+"\n";
}
if(nameCheck=="") {
msg+= "Dont you have a name????"+"\n";
}
if(emailCheck=="") {
msg+= "Enter email... how am I supposed to contact you"+"\n";
}
if(msgCheck="") {
msg+= "Dont you have any messages for me??"+"\n";
}
if(msg!="") {
alert(msg);
} else {
<?php
//You need to process data here..
?>
}
}
</script>
<h4>Send Your Feedback Here.<p>
<form name ="register" action="php/process.php" method="post" enctype="multipart/form-data">
Name<br>
<input type="text" name="name" size="30">
</p>
<p>
Email<br>
<input type="text" name="email" size="30"></p><p>
Message<br>
<textarea name="message" rows="5" cols="40"></textarea>
<p>
</p>
<p>
Security Check<br>
Sum of <?php $a = rand(0,9);
$b = rand(0,9);
echo $a . "+" . $b ;
$result = $a + $b ;
?> =
<input type="text" name="ver" /><input type="hidden" name="rval" value="<?php echo $result; ?>" />
<button type="button" onClick="thevalidate()">Send</button>
</p>
</form>

PHP questionnaire strategy

I am designing a questionnaire, the code I've written is a combination of JS and PHP. I have the questions in one page but I want to ask each question on a separate page and the consecutive questions should be asked according to the answer the user select. what is the best strategy to do that? do I need to include SQL as well?
and at the end the answers will be written in a text file
the code I have is:
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
if(empty($_POST['name']))
{
$errorMessage .= "<li>You forgot to enter your name!</li>";
}
$varName = $_POST['name'];
$varLand1 = $_POST['landscape1']; $varLand2 = $_POST['landscape2'];
$varCom = $_POST['comment'];
$varAppx = $_POST['appx'];
$clim = $_POST['landscape'];
$varMech = $_POST['mechanism'];
$varMechoth = $_POST['mech'];
if(empty($errorMessage))
{
$fs = fopen("$varName.txt" ,"a+");
fwrite($fs,$varName . "\n" . $varLand1 . ' ' .$varLand2 . "\n" . $clim . "\n" . $varAppx . "\n" . $varCom . "\n" . $varMech .$varMechoth);
fclose($fs);
header("Location: t-y.html");
exit;
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script scr="jss.js" type="text/javascript"></script>
<title>Questionnaire</title>
</head>
<body>
<FONT FACE="Times New RomanPS">
<H1>Questionnaire</H1>
<P>Please fill out this questionnaire:
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
<form action="index.php" method="post">
<p>
Name<br>
<input type="text" name="name" maxlength="50" value="<?=$varName;?>" />
</p>
<ul>
<p> 1 - Q1?
<p><input type="checkbox" name="landscape1" value="urban"> Urban<br>
<p><input type="checkbox" name="landscape2" value="non-urban"> non-Urban<br>
<p> 2 - Q2?<br>
<input type="radio" name="landscape" value="Dry"> Dry<br>
<input type="radio" name="landscape" value="Tropical"> Tropical<br>
<input type="radio" name="landscape" value="Moderate"> Moderate<br>
<input type="radio" name="landscape" value="Continental"> Continental<br>
<input type="radio" name="landscape" value="Polar"> Polar<br>
<p> 3 - Q3? <br>
<input type="radio" id="mecha" name="mechanism" value="sub" onclick="hideTextBox1()"/> Subsidence<br>
<input type="radio" id="mecha" name="mechanism" value="earth" onclick="hideTextBox1()"/> Earthquake<br>
<input type="radio" id="mecha" name="mechanism" value="volc" onclick="hideTextBox1()"/> Volcanic<br>
<input type="radio" id="mecha" name="mechanism" value="<?=$varMech;?>" onclick="displayTextBox1()"/> other<br>
<div id="otherTextBox1" style="display:none;visibility:hidden;">
<input type="text" name="mech" maxlength="20" value="<?=$varMech;?>">
</div>
<p> 4 - Q3?<br>
<input name="choice" id="choice4" type="radio" value="four" onclick="hideTextBox()"/><label for="choice4"> No </label><br>
<input name="choice" id="choice5" type="radio" value="other" onclick="displayTextBox()"/><label for="choice5"> Yes </label>
<br/>
<div id="otherTextBox" style="display:none;visibility:hidden;">
[mm/yr]<br><input type="text" name="appx" maxlength="3" value="<?=$varAppx;?>">
</div>
<br/>
<p> 5 - Q4
<p> 6 - Q5
<p> 7 - Q6
<p>
Comments:<br>
<textarea type="text" name="comment" cols=48 rows=4 maxlength="1000" value=" <?=$varComment;?>"></textarea>
</p>
<p><input type="reset"> <input type="submit" name="formSubmit" value="Submit" />
</ul>
<script>
function displayTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'block';
otherTextBox.style.visibility = 'visible';
}
function hideTextBox()
{
var objElement = document.getElementById('otherTextBox');
otherTextBox.style.display = 'none';
otherTextBox.style.visibility = 'hidden';
}
function validate()
{
var arrElements = document.getElementsByName('choice');
var objElement;
var boolContinue = false;
var objOtherText;
for(var i=0, _length=arrElements.length; i<_length; i++)
{
objElement = arrElements[i];
if(objElement.checked)
{
if(objElement.id == 'choice5')
{
objOtherText = document.getElementById('othertext');
if(strTrim(objOtherText.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else
{
alert('Ask user to complete the data.')
}
}
function displayTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'block';
otherTextBox1.style.visibility = 'visible';
}
function hideTextBox1()
{
var objElement1 = document.getElementById('otherTextBox1');
otherTextBox1.style.display = 'none';
otherTextBox1.style.visibility = 'hidden';
}
function validate1()
{
var arrElements1 = document.getElementsByName('mechanism');
var objElement1;
var boolContinue = false;
var objotherText1;
for(var i=0, _length=arrElements1.length; i<_length; i++)
{
objElement1 = arrElements1[i];
if(objElement1.checked)
{
if(objElement1.id == 'mecha')
{
objOtherText1 = document.getElementById('othertext');
if(strTrim(objOtherText1.value).length>0)
{
boolContinue = true;
break;
}
}
else
{
boolContinue = true;
break;
}
}
}
if(boolContinue)
{
alert('Continue, user completed the information.')
}
else<?=$varMech;?>
{
alert('Ask user to complete the data.')
}
}
/**
* Removes all white space characters from the string.
*
* #param: {String} String to trim.
*
* #return {String} Trimed string.
*/
function strTrim(strTrim)
{
return strTrim.replace(/^\s+|\s+$/g, '');
}
</script>
</form>
</FONT>
</body>
</html>
I don't think you would NEED to use SQL to do this. You should be able to use the $_SESSION to store the answers to previous questions and adjust the questions on the following pages accordingly.

Categories