Basically I have a page that displays a seating plan using check boxes. These check boxes can be ticked to represent the seat being booked. I also have a text input where names are entered for the bookings, these forms are then posted to the next page to work out what check boxes are selected and save them in the database. This is some of the code:
title>School Hall</title>
<script>
function confirmReservation() {
var selectedList = getSelectedList('Confirm Reservation');
if (selectedList) {
if (confirm('Do you want to CONFIRM this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=0;
document.forms[0].statusB.value=1;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function cancelReservation() {
var selectedList = getSelectedList('cancel Reservation');
if (selectedList) {
if (confirm('Do you want to CANCEL this Reservation : ' + selectedList + '?')) {
document.forms[0].statusA.value=1;
document.forms[0].statusB.value=0;
document.forms[0].previousPage.value='schoolHall';
document.forms[0].action='bookingQueries.php';
document.forms[0].submit();
} else {
clearSelection();
}
}
}
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else {
return selectedList;
}
}
function validateForm()
{
var x=document.forms["0"]["fname"].value;
if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body topmargin="0" leftmargin="0" rightmargin="0" >
<table>
<tr><td width="100%" align="left" id='table-2'>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="hidden" name="previousPage" value=""/>
<input type="hidden" name="statusA" value=""/>
<input type="hidden" name="statusB" value=""/>
</tr>
<table>
<tr><td width="100%" align=left" id='table-2'>
<INPUT Type="BUTTON" VALUE="Home Page" ONCLICK="window.location.href='/final/homePage.php'" align='lef'>
<INPUT Type="BUTTON" VALUE="Bookings" ONCLICK="window.location.href='/final/schoolHallBookings.php'">
<?php
// Connection
$con = mysql_connect("localhost","root","");
if(!con)
{
die('Could not connect:' . mysql_error());
}
mysql_select_db("systemDatabase",$con); // Connection to DB
echo '<br>';
echo '<font face="Trebuchet MS" color="Black" size="9" >School Hall </font>';
$query = "SELECT * from schoolHall order by rowId, columnId"; // Create Select Query
$result = mysql_query($query); // Retrieve all data from query and hold in $result
$prevRowId = null;
$seatColor = null;
$tableRow = false;
echo "<table align='center' id='table-2'"; // Create table
while (list($rowId, $columnId, $status, $updatedby, $firstName, $lastName) = mysql_fetch_row($result)) // Itterates through fetched data
{
if ($prevRowId != $rowId)
{
if ($rowId != 'A')
{
echo "</tr></table></td>";
echo "\n</tr>";
}
$prevRowId = $rowId;
echo "\n<tr><td align='center'><table class='center' border='1' cellpadding='15' cellspacing='8' align='center' id='table-2' ><tr>";
}
else
{
$tableRow = false;
}
if ($status == 0)
{
$seatColor = "lightgreen"; // Available
}
else
{
$seatColor = "red"; // Booked
}
echo "\n<td bgcolor='$seatColor' align='center'>";
echo "$rowId$columnId";
if ($status == 0 || ($status == 1)) {
echo "<input type='checkbox' name='seats[]' value='$rowId$columnId' align='center'></checkbox>"; // Create Checkboxes giving value RowId, ColumnId
}
}
echo "</tr></table></td>";
echo "</tr>";
echo "</table>";
// Con close
mysql_close();
?>
<table width='100%' border='0'>
<tr><td align='right'>
First Name: <input type="text" name="fname">
Last Name: <input type="text" name="lname">
</td>
<td><td align='left'>
</td>
<td><td align ='right'>
<input type='button' value='Confirm Reservation' onclick='confirmReservation()'/>
</td></tr>
<tr>
<td><td align='left'>
</td>
<td><td align='left'>
</td>
<td align='right'>
<input type='button' value=' Cancel Reservation' onclick='cancelReservation()'>
</td>
</table>
</td></tr>
<tr><td width="100%" align="center">
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
<table border="1" cellspacing="6" cellpadding="4" align="center">
<tr>
<td bgcolor='lightgreen'>Available</td>
<td bgcolor='red'>Unavailable</td>
</tr>
</table>
</td></tr>
<tr><td> </td></tr>
<tr><td width="100%" align="center">
</td></tr>
</table>
</body>
Is there any way i can incorporate validation with my current code? I need the names text checked to make sure there is actually a name entered. This needs to happen before the next page is accessed. Any ideas?
Try first add ids to your text input:
<table width='100%' border='0'>
<tr>
<td align='right'>
First Name: <input type="text" id="fname" name="fname"/>
Last Name: <input type="text" id="lname" name="lname"/>
</td>
<td>
<td align='left'>
function getSelectedList(actionSelected) {
// get selected list
var obj = document.forms[0].elements;
var selectedList = '';
for (var i = 0; i < obj.length; i++) {
if (obj[i].checked && obj[i].name == 'seats[]') {
selectedList += obj[i].value + ', ';
}
}
var fname = document.getElementById('fname');
var lname = document.getElementById('lname');
// no selection error
if (selectedList == '') {
alert('Please select a seat ');
return false;
} else if (actionSelected.beginsWith('Confirm') && (fname .value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(fname))) {
alert('Please Enter valid first name.');
return false;
} else if (actionSelected.beginsWith('Confirm') && (lname.value.replace(/^\s+|\s+$/g, '').length == 0 || /[0-9]/.test(lname))) {
alert('Please Enter valid last name.');
return false;
} else {
return selectedList;
}
}
Working example
http://jsfiddle.net/
The below example demonstrates how you can pass a value to the function checkInput and it will determine whether or not it is a valid input - the function uses jQuery but you can do it whthout jQuery too.
Demo HTML:
<form>
<input id="first-name" value="some value" />
<input id="last-name" value="" />
</form>
JS Function (goes with HTML demo):
function checkInput(fieldID){
var isValid = true;
if($("#" + fieldID).val() == ''){
isValid = false;
}
return isValid;
}
$(document).ready(function(){
if(!checkInput("first-name")){
alert("error found with first name");
}
if(!checkInput("last-name")){
alert("error found with last name");
}
});
Related
I have a form with a table with dynamic fields and dynamic rows. So initially the table contains one row with two fields, when I fill them both and click Enter, a jquery function will create a new row below.
When time comes to Submit the form, I am checking if there is any empty field, and if there is any it displays an error BUT the problem is here, it clears all fields. How can I still keep them when submitting?
Here is the HTML:
<form action="" method="post">
<button type="submit" class="btn" name="add_device">Add devices</button>
<?php foreach ($dev_type_results as $row) {
} ?>
<table id="ble_table" class="table table-bordered table-striped" cellspacing="0" width="100%">
<tr>
<th>No.</th>
<th>Serial no.</th>
<th>IMEI</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="serial_no[]" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>" /></td>
<td><input type="text" class="inputs lst" name="imei[]" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']); } ?>" /></td>
</tr>
</table>
</form>
jquery function :
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
<?php foreach ($dev_type_results as $row) {
}
html += '<td><input type="text" class="inputs" name="serial_no[]' + i + '" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>"/></td>';
html += '<td><input type="text" class="inputs lst" name="imei[]' + i + '" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']);} ?>"/></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
event.preventDefault();
}
});
Below for brevity I will just post the PHP code where I validate:
if (count(array_filter($_POST['serial_no'])) < count($_POST['imei'])) {
array_push($errors, "Found empty field in Serial no. column");
}else{
//call function to post to database
}
I have tried already by using global variables but it doesn't work. What else can I try?
You could add ids to the inputs and use javascript to find it and change it's content.
var Input_1 = document.getElementById(Input_1 - id);
var Input_2 = document.getElementById(Input_2 - id);
var Val_1;
var Val_2;
var completed = false;
var i = $('table tr').length;
$(document).on('keyup', '.lst', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
html = '<tr>';
html += '<td>' + i + '</td>';
html += '<td><input type="text" class="inputs" name="serial_no[]' + i + '" value="<?php if (isset($_POST['
serial_no '])) { echo htmlspecialchars($_POST['
serial_no ']);} ?>
"/></td>';
html += '<td><input type="text" class="inputs lst" name="imei[]' + i + '" value="<?php if (isset($_POST['
imei '])) { echo htmlspecialchars($_POST['
imei ']);} ?>"/></td>';
html += '</tr>';
$('table').append(html);
$(this).focus().select();
i++;
}
});
$(document).on('keydown', '.inputs', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13) {
completed = true
var index = $('.inputs').index(this) + 1;
$('.inputs').eq(index).focus();
event.preventDefault();
Input_1.value = Val_1;
Input_2.value = Val_2;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<button type="submit" class="btn" name="add_device">Add devices</button>
<?php foreach ($dev_type_results as $row) {
} ?>
<table id="ble_table" class="table table-bordered table-striped" cellspacing="0" width="100%">
<tr>
<th>No.</th>
<th>Serial no.</th>
<th>IMEI</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" class="inputs" name="serial_no[]" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>" /></td>
<td><input type="text" class="inputs lst" name="imei[]" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']); } ?>" /></td>
</tr>
</table>
</form>
<?php
if (count(array_filter($_POST['serial_no'])) < count($_POST['imei'])){
array_push($errors, "Found empty field in Serial no. column");
}else{
//call function to post to database
}
?>
Here is my question 'if(!empty($_POST['btn_editinventory]))' is working but if i click on btndeleteinventory it will also execute the codes in my btneditinventory. Anyone knows how will i correct my condition in my controller if you have two buttons in the view like this:
<input type="button" value="Edit" name="btn_editinventory" id="btn_editinventory" onclick="validate_editinventory();"/>
<input type="button" value="Delete" name="btn_deleteinventory" id="btn_deleteinventory" onclick="validate_deleteinventory();"/>
Thank you in advance for your help! :)
Here is my view
<link rel="stylesheet" type="text/css" href="<?php echo base_url('assets/css/mystyle.css') ?>">
<div id="content">
<form action="edit_delete_others2" method="POST" id='frm_otherequips2' name="frm_otherequips2">
<fieldset id="edit_other">
<legend>Inventory Details</legend>
<table>
<tr>
<?php $otherequips = $other2->Equipment;
$otherdesc = $other2->ItemDescription;
$otherID = $other2->ID;
$otherserialnum = $other2->SerialNumber;
?>
<td>Equipment</td>
<?php // if(isset($other)) { ?>
<td><input type="text" id="txt_editotherequip" name="txt_editotherequip" value="<?php echo $otherequips // echo (isset($other->Equipment) AND $other->Equipment) ? $other->Equipment:''; ?>"/></td>
<td>Item Description</td>
<td><input type="text" id="txt_editotherdesc" name="txt_editotherdesc" value="<?php echo $otherdesc // echo (isset($other->ItemDescription) AND $other->ItemDescription) ? $other->ItemDescription:''; ?>"/></td>
<td style="visibility: hidden;"><input type="text" id="txt_editotherID" name="txt_editotherID" value="<?php echo $otherID //echo (isset($other->ID) AND $other->ID) ? $other->ID:''; ?>"/></td>
</tr>
<tr>
<td>Serial Number</td>
<td><input type="text" id="txt_editotherserialnum" name="txt_editotherserialnum" value="<?php echo $otherserialnum // echo (isset($other->SerialNumber) AND $other->SerialNumber) ? $other->SerialNumber:''; ?>"/></td>
<?php // } ?>
</tr>
<tr>
<td><input type="button" id="btn_editother" name="btn_editother" value="Edit" onclick="validate_edit_otherequip();"/></td>
<td><input type="button" id="btn_deleteother" name="btn_deleteother" class="btn_deleteother" value="Delete" onclick="validate_delete_otherequip();"/></td>
</tr>
</table>
</fieldset>
</form>
</div>
here is my javascript:
<script>
function validate_edit_otherequip(){
if(document.getElementById('txt_editotherequip').value === ""){
alert('Please Input Equipment!');
return false;
}
else if(document.getElementById('txt_editotherdesc').value === ""){
alert('Please Input Item Description');
return false;
}
else if(document.getElementById('txt_editotherserialnum').value === ""){
alert('Please Input Serial Number');
return false;
}
else{
var y;
if(confirm("Are you sure you want to save updated data?") === true){
var y = document.forms['frm_otherequips2'].submit();
}
else if(confirm("Are you sure you want to save updated data?") === false){
return false;
}
}
}
function validate_delete_otherequip(){
var x;
if(confirm("Are you sure you want to delete this data?") === true){
var x = document.forms['frm_otherequips2'].submit();
}
else if(confirm("Are you sure you want to delete this data?") === false){
return false;
}
}
and here is my controller:
public function edit_delete_others2($id){
$data_other['other2'] = $this->inventory_model->other_search($id);
$this->load->view('homeview');
$this->load->view('frm_otherequips2', $data_other);
$this->load->view('footer_view');
}
I don't know how to have a condition in buttons.
As far as your two buttons have a name attribute, it's pretty easy to handle in your Controller
public function edit_delete_others2($id){
if($this->input->post('btn_editinventory')) {
// Do your edit stuff
} elseif($this->input->post('btn_deleteinventory')) {
// Do your delete stuff
}
}
The button is never send in the post when you don't click on it, this is why it works
I have an an ajax drop down box that if selected adds another field to a form, this works but this new field doesn't get submitted with the form. Any suggestions?
findTest.php called via ajax
<?php
$work = ($_GET['work']);
if ($work == "Work1") {
?>
<tr>
<td>New work1<input name="newWork1" size="20" type="text"/></td>
</tr> <?
} elseif ($work == "Work2") {
?>
<tr>
<td>New work<input name="newWork" size="20" type="text"/></td>
</tr><?
} elseif ($work == "Work3") {
?>
<tr>
<td>No work today</td>
</tr><?
}?>
Test.php
<?php
$page = '';
$answer = null; //clean start.
$Comments = $_POST['Comments'];
$new = $_POST['new'];
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message <?= $_POST['Comments'] ?>
and <?= $_POST['new'] ?> or this should be
work2 <?= $_POST['newWork'] ?></p>
<? } ?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp = false;
try {
xmlhttp = new XMLHttpRequest();
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e1) {
xmlhttp = false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL = "findTest.php?work=" + workId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function () {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML = req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right">Work Done:</td>
<td><select name="WorkDone" tabindex="14"
onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td><p id="workdiv">New Work<input name="newWork" size="20"
type="text"/></td>
</tr>
<tr>
<td width="200" align="right">Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40"
rows="4"><?= $_POST[Comments] ?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit"
class="button" value="Submit">
</td>
</tr>
</tr>
</table></form>
UPDATE: new code.
findTest.php called via ajax
<?php
if (isset($_GET['work'])) {
$work= $_GET['work'];
if ($work == "Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
}?>
And Test.php
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork = $_POST['newWork1']; } else {
$newWork = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
?>
<script language="javascript" type="text/javascript">
// Roshan's Ajax dropdown code with php
// This notice must stay intact for legal use
// Copyright reserved to Roshan Bhattarai - nepaliboy007#yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getWorkDone(workId) {
var strURL="findTest.php?work="+workId+"&new1="+"&$new";
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('workdiv').innerHTML=req.responseText;
} else {
alert("1 There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<table id="meters" width="800" border="0" cellspacing=0 cellpadding=2>
<form name="meters" method="POST" action="test.php">
<tr>
<td width="200" align="right" >Work Done:</td>
<td><select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="">Select</option>
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Work3">Work3</option>
<option value="Other">Other</option>
</select>
</td>
</tr>
<tr >
<td ></td>
<td ><p id="workdiv">New Work<input name="newWork" size="20" type="text" /></td>
</tr>
<tr>
<td width="200" align="right" >Comments:</td>
<td><textarea name="Comments" tabindex="40" cols="40" rows="4" ><?=$_POST[Comments]?></textarea></td>
</tr>
<tr>
<td colspan="7" align="center"><input type="submit" name="Submit" class="button" value="Submit">
</td>
</tr>
</tr>
</table>
</form>
UPDATE edit double up and correct $newWork to $newWork1
<?php
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a'; }
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a'; }
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";}
?>
This now shows n/a but not the value of newWork1
You have very modified the original question, I can only respond to what was previously.
The important part is also findTest.php
from this script you replace your
document.getElementById('workdiv').innerHTML=req.responseText;
So how does findTest.php know about $_POST['newwork1']
<td>New work1<input name="newWork1" ... value="<?=$_POST['newwork1']?>" /></td>..
This must come via a GET / POST, but in your GET there ist only
strURL="findTest.php?work="+workId;
Only 1 GET variable named $_GET['work'].
and you use this variable (without test)
$work=$_GET['work'];
And then you mixed the request from $_GET to $_POST['newwork1']
so why not use your select value to get it all together.
Test.php
...
<select name="WorkDone" tabindex="14" onchange="getWorkDone(this.value)">
<option value="Work1">Work1</option>
<option value="Work2">Work2</option>
<option value="Noworktoday">No work today</option>
<option value="Other">Other</option>
</select>
...
findTest.php
if (isset($_GET['work'])) {
//for example : $work == "Work1"
$work=$_GET['work'];
if ($work=="Noworktoday") {
echo "<tr><td>No work today</td></tr>";
} else {
echo "<tr><td>New ".$work."<br>";
echo "<input name=\"new".$work."\" type=\"text\"";
echo " size=\"20\" value=\"new".$work."\" />";
echo "</td></tr>";
}
//<tr><td>New Work1<input name="newWork1" type="text" size="20" value="newWork1" /></td></tr>
Update:
You can not see your values because you did'nt echo them
and you have to test all $_POST
$page = '';
$answer = null; //clean start.
if (isset($_POST['Comments'])) {
$Comments = $_POST['Comments']; } else {
$Comments = 'n/a';
}
if (isset($_POST['newWork1'])) {
$newWork1 = $_POST['newWork1']; } else {
$newWork1 = 'n/a';
}
....
and so on for all possible values
echo your variables
if (isset($_POST['Submit'])) {
?>
<p align="center" id="infomessage">Test message = <? echo $Comments; ?>
and = <? echo $newWork1; ?> or this should be
work2 = <? echo $newWork; ?></p>
<? } ?>
Update:
I can not see the actual code, you need a if (isset ... for all possible variables . In my example I have described only two possibilities. You need also e.g.
if (isset($_POST['newWork2'])) { ...
if (isset($_POST['newOther'])) { ...
and so on !! And make only asimple output.
if (isset($_POST['Submit'])) {
echo "message = ".$Comments."<br>";
echo "newWork1 = ".$newWork1."<br>";
echo "newWork2 = ".$newWork2."<br>";
echo "newOther = ".$newOther."<br>";
}
and put it logical together
This is illogical Work2 assigned to newWork !!!
I have this code of PHP:
<form action="modificaPriorita.php" method="post">
<table>
<tr id="format-tabelle">
<th></th>
<th><span class="format-celle">TITLE</span></th>
<th><span class="format-celle">TYPE</span></th>
</tr>
<?php
$res = GestioneSegnalazione::showSegnalazioni();
function drawTable($res) {
$title = $res[0];
$idAuthor = $res[1];
$type = $res[2];
for ($i = 0; $i < $num; $i++) {
print "<tr class='row'>
<td align='center' valign='middle'> <input type='radio' name='radio' value='$title[$i],$idAuthor[$i]'/> </td>
<td align='center' valign='middle'><span class='format-celle'> $title[$i]</span></td>
<td align='center' valign='middle'><span class='format-celle'> $type[$i]</span></td>
?>
</table>
<br>
<input type="submit" name="show" value="Show" class='freshbutton-orange' id='show-submit-segnalazione'/>
<?
if (isset($_POST['show'])) {
if ($_POST[radio] == "") {
echo("<SCRIPT JavaScript'>window.alert('Select one segnalazione to show');window.location.href='showSegnalazione.php#close'</SCRIPT>");
}
}
?>
If i select one item in radio button and i press the button 'show' it works, it goes to the other page "modificaPriorita.php" with two parameters: title, idAuthor
My problem is if i press the 'show' button without select one item in radio button, it would show me the error 'Select one segnalazione to show', but it goes to the new page ("modificaPriorita.php") without parameters. what can i do to have this error message?
You don't need to wait for your form to post before you can check to see if they selected a radio button. You can use javascript with the onsubmit listener like so:
<form action="modificaPriorita.php" method="post" onsubmit="return validateForm();">
<table>
<tr id="format-tabelle">
<th></th>
<th><span class="format-celle">TITLE</span></th>
<th><span class="format-celle">TYPE</span></th>
</tr>
<?php
$res = GestioneSegnalazione::showSegnalazioni();
function drawTable($res) {
$title = $res[0];
$idAuthor = $res[1];
$type = $res[2];
for ($i = 0; $i < $num; $i++) {
print "<tr class='row'>
<td align='center' valign='middle'> <input type='radio' name='radio' value='$title[$i],$idAuthor[$i]'/> </td>
<td align='center' valign='middle'><span class='format-celle'> $title[$i]</span></td>
<td align='center' valign='middle'><span class='format-celle'> $type[$i]</span></td>
</tr>";
}
}
?>
</table>
<br>
<input type="submit" name="show" value="Show" class='freshbutton-orange' id='show-submit-segnalazione'/>
</form>
<script>
function validateForm() {
var radios = document.getElementsByName('radio');
var checked = false;
for (var i = 0, length = radios.length; i < length; i++) {
if (radios[i].checked) {
checked = true;
break;
}
}
if (checked) {
return true;
} else {
alert('Select one segnalazione to show');
return false;
}
}
</script>
So what happens in this code is right before the form gets submitted runs the validateForm() function we set up. In that function it checks to see if a radio button is selected. If it is then the function returns true which allows the form to post. If it doesn't find a radio button selected it does the alert window and then returns false which prevents the form from posting. I hope this helps.
<head>
<title> Add User page</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<form name='f2' action="insert_ac.php" method="post" >
<script src="validation.js" type="javascript/text"></script>
</head>
<body onload="firstfocus();">
<table align="center" border="0" cellpadding="3" cellspacing="1">
<tr>
<td> First Name</td><td > : </td>
<td> <input type='text' name='fname' id='fid' size="50" style="background-color:#abcddd; height:18px;" value='' maxlength="100" onblur="fname_validation(5,12);"> </td>
</tr>
<tr>
<td> Last Name</td><td> : </td>
<td> <input type='text' name='lname' id='lid' size="50" style="background-color:#abcddd; height:18px; "value='' maxlength="100" onblur="lname_validation(5,12);"> </td>
</tr>
<tr>
<td> Gender</td><td> : </td>
<td> <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td> Phone Number</td><td> : </td>
<td> <input type='number_format' name='phone' id='phno'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="allnumeric();"></td>
</tr>
<tr>
<td> Work Experiance</td><td> : </td>
<td><select name="exp" onblur="expselect();">
<option > Select One</option>
<option selected="" value="Default"> Select One </option>
<option value="F"> Fresher </option>
<option value="E"> Experiance</option>
</select></td>
</tr>
<tr>
<td>User Name</td><td>:</td><td> <input type='txt' name='uname' id='uid'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="userid_validation(5,10);"> </td>
</tr>
<tr>
<td>Password</td><td>:</td><td> <input type='password' name='pwd' id='pid' size="50" style="background-color:#abcddd; height:18px; " value=''onblur="passid_validation(7,12);"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td width="84"><input name="enter" class="btn_login" type="submit" value="Submit" onsubmit="alert('Data stored successfully');"/> <input name="cancle" class="btn_login" type="reset" value="Cancle" /></td>
</tr>
</table>
</form>
</body>
</html>
I included the external javascript file using script tag but the validations are not working.
This is my external javascript code which was saved as validation.js and i am unable to find errors in it please help me.
// After form loads focus will go to first name field.
function firstfocus()
{
var fname = document.f2.fname.focus();
return true;
}
// This function will validate First name
function fname_validation(mx,my)
{
var fname = document.f2.fname;
var fname_len = fname.value.length;
var letters = /^[A-Za-z]+$/;
if (fname_len == 0 || fname_len >= my || fname_len < mx)
{
alert("First Name should not be empty / length be between "+mx+" to "+my);
fname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Last Name
document.f2.lname.focus();
return true;
}
}
}
// This function will validate Last name
function lname_validation(mx,my)
{
var lname = document.f2.lname;
var lname_len = lname.value.length;
var letters = /^[A-Za-z]+$/;
if (lname_len == 0 || lname_len >= my || lname_len < mx)
{
alert("Last Name should not be empty / length be between "+mx+" to "+my);
lname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Phone Number
document.f2.phone.focus();
return true;
}
}
}
// This function will validate Phone Number.
function allnumeric()
{
var phone = document.f2.phone;
var numbers = /^[0-9]+$/;
if(phone.value.match(numbers))
{
// Focus goes to next field i.e. Experiance.
document.f2.exp.focus();
return true;
}
else
{
alert('Phone Number must have numeric characters only');
phone.focus();
return false;
}
}
// This function will select Experiance.
function expselect()
{
var exp = document.f2.exp;
if(exp.value == "Default")
{
alert('Select your Experiance from the list');
exp.focus();
return false;
}
else
{
// Focus goes to next field i.e. Username Code.
document.f2.uname.focus();
return true;
}
}
// This function will validate User Name.
function allLetter()
{
var uname = document.f2.uname;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
// Focus goes to next field i.e. Password.
document.f2.pwd.focus();
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
// This function will validate Password.
function passid_validation(mx,my)
{
var passid = document.registration.passid;
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
}
try to change <script type="javascript/text"> to <script type="text/javascript">
and double check the reference of your js file. Also, put an alert check to determine if it is really going through the firstFocus() function.
You have to reference the .js if its not in the same folder as html
EDIT
function fname_validation(mx,my)
{
is missing a closing bracket!
I changed the java script file and now i can find validations in my form...
Thanks for your help..
here i am sharing my code...
HTML code
<form name='f1' action="insert_ac.php" method="post" onSubmit="return validateForm();" >
<tr>
<td height="25" height="25" colspan="2" bgcolor="#EC6921" class="form_heading">Add User Form</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> First Name:</td>
<td bgcolor="#FFFFFF"> <input type='text' name='fname' id='fid' size="50" style="height:18px;" value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Last Name:</td>
<td bgcolor="#FFFFFF" > <input type='text' name='lname' id='lid' size="50" style=" height:18px; "value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Gender:</td>
<td bgcolor="#FFFFFF" > <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Phone Number:</td>
<td bgcolor="#FFFFFF" > <input type='number_format' name='phone' id='phno'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Work Experiance:</td>
<td bgcolor="#FFFFFF" ><select name="exp" >
<option selected="" value="Default"> Select One </option>
<option value="Fresher"> Fresher </option>
<option value="Experiance"> Experiance</option>
</select></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">User Name:</td><td bgcolor="#FFFFFF"> <input type='txt' name='uname' id='uid'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">Password:</td><td bgcolor="#FFFFFF"> <input type='password' name='pwd' id='pid' size="50" style=" height:18px; " value=''></td>
</tr>
</table>
<table align="center">
<tr>
<td ><input name="enter" class="btn_login" type="submit" value="Submit" align="center"><input name="cancle" class="btn_login" type="reset" value="Cancle" valign="right" /></td>
</tr>
</table>
</div>
</div>
</div>
</form>
</body>
</html>
Here is my java script file which is working fine....
var RE = /^.+#.+\..{3}$/;
var RE1 = /^[a-zA-Z]+$/;
var RE2 = /^[0-9]{10}$/;
var RE3 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
function validateForm()
{
if (document.f1.fname.value == "")
{
window.alert("first name should NOT BE empty");
document.f1.fname.focus();
return false;
}
else
if (RE1.test(document.f1.fname.value) == false)
{
alert("Invalid first name\n\
");
return false;
}
else
if (document.f1.fname.value.length < 3)
{
window.alert("Firstname must have atleast Three characters");
document.f1.fname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Lastname should not be empty");
document.f1.lname.focus();
return false;
}
else
if (RE1.test(document.f1.lname.value) == false)
{
alert("Invalid last name");
return false;
}
else
if (document.f1.lname.value.length < 4)
{
window.alert("Lastname must have atleast four characters");
document.f1.lname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Last name should not be empty");
document.f1.lname.focus();
return false;
}
else
if (document.f1.phone.value == "")
{
window.alert("phne no should NOT BE empty");
document.f1.phone.focus();
return false;
} else
if (RE3.test(document.f1.phone.value) == false)
{
alert("Invalid phone number");
document.f1.phone.focus();
return false;
}
else
if (document.f1.exp.selectedIndex == 0)
{
window.alert("please select work experiance ");
return false;
}
else
if (document.f1.uname.value == "")
{
window.alert("UserName should not be empty");
document.f1.uname.focus();
return false;
}
else
if (RE1.test(document.f1.uname.value) == false)
{
window.alert("Invalid userName ");
document.f1.uname.focus();
return false;
}
else
if (document.f1.pwd.value == "")
{
window.alert("password should not be empty");
document.f1.pwd.focus();
return false;
}
else
if (document.f1.pwd.value.length < 6)
{
window.alert("password must have atleast six characters");
document.f1.pwd.focus();
return false;
}
else
{
window.alert("User has been added successfully.");
return true;
}
}