Validating a form created via php with javascript - javascript

I have a PHP form.
The form elements are created based off the user's selection which is in a dropdown menu.
What I am trying to accomplish is loop through that form and validate the values of two elements with the id's of "action" and "amt".
Now, I should mention the form which I am trying to validate can have x amount of elements because it needs to be based on the users needs. When I call my validate function it does check the id's and alerts the value, however, it alerts the value of the first input element with the id "amt" three/multiple times.
This is bad as because I need to perform some computation and the duplicate entries would cause an error in the the computation.
Here is my script
<script type="text/javascript">
function validate(){
var i;
var passtest = 0;
var test = "";
var form = document.getElementById("myForm");
alert("Enter function");
for( i = 0; i < form.elements.length; i++){
if(form.elements[i].id === "action" && form.elements[i].value === "Debit" || form.elements[i].value === "Credit"){
test = form.elements[i].value;
// Alerts action
alert(test);
if(document.getElementById("amt").value !=""){
// Get the value from the input element id amt
test = document.getElementById("amt").value;
// Alerts value from id amt
alert(test);
//passtest = 1;
}
else{
document.getElementById("amtTD").innerHTML = "Check Amounts";
return false;
}
alert("End of if stmt");
}
else{
// If it is not id action or id amt just Alert value if any
test = form.elements[i].value;
alert(test);
}
}
///****** END OF FOR LOOP ****** ///
if(passtest === 1){
return true;
}
else{
alert("Submission failed");
return false;
}
}
</script>
Here Is the php code that which displays the form
<form name='transaction' id="myForm" onsubmit="return validate()" action='' method='post'>
<?php
if (isset($_POST['add'])) {
if (isset($_POST['acctN'])) {
echo "<table class='table' id='myRow'' style=''>";
echo "<thead>";
echo "<tr>";
echo "<th>Account Name</th>";
echo "<th>Action</th>";
echo "<th>Amount</th>";
echo "</tr>";
echo "</thead>";
foreach ($_POST['acctN'] as $name) {
$query = "SELECT * FROM ChartOfAccounts WHERE AccountName = '$name'";
$results = mysqli_query($cxn, $query) or die(mysqli_error($cxn));
$row = mysqli_fetch_assoc($results);
echo "<tbody>";
echo "<tr>";
echo "<td class ='col-md-6'><select name='account[]' class='form-control' style=''><option>" . $row['AccountName'] . "</option></select></td>";
echo "<td class ='col-md-2'><select name='debOrCred[]' id='action' class='form-control' style=''>
<option value='Debit'>Debit</option>
<option value='Credit'>Credit</option>
</select></td>";
echo "<td class ='col-md-2'> <input type='text' name='amount[]' class='form-control' id='amt' style=''/> <span id ='amtTD' style='color:red;'> </span></td>";
echo "<td class ='col-sm-2'>$</td>";
echo "<td class ='col-sm-2'><button type='button' onclick='removeCell()' class='btn btn-danger'value='Remove' name='".$row['AccountName']."'>Remove</button></td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
}
echo "<label style='margin-left:7px;'>Documentation</label>";
echo "<textarea name='src-doc' class='form-control' rows ='4' cols='50' placeholder='Description' style='max-width:575px; margin-left:8px;' ></textarea>";
echo "<div style='padding:10px;'>";
echo "<label>Source</label>";
echo "<input type='file' name='fileToUpload' id='fileToUpload'>";
echo "</div>";
echo "<input type='submit' class='btn btn-primary' value='Submit' name='subTrans' style='margin-top:7px; margin-left:8px; '/>";
}
?>
</form>
Thank you all that help and provide input.

Related

Updating mySQL table with user interface - PHP

[Sample Look]
I'm trying to make an interface where you can edit/add/remove fields of a mySQL database. This is how it looks visually, and I have all the functionality on the client side working.
My question is: How can I pass any edits/adds/removals to the server side? I'll include a link for my JSFiddle.
And the code below will show how I currently great the table.
<?php
$servername = "localhost";
$username = "lalalal";
$password = "lalalal";
$link = mysqli_connect("localhost", "lalala", "lalala", "lalala");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sqlStart = "SELECT `Name`, `EXT`, `Returning Time`, `Returning Date`, `Out`, `Reset`, `Booked` FROM `lalala`";
if($result = mysqli_query($link, $sqlStart)){
if(mysqli_num_rows($result) > 0){
echo "<table id = contactTable>";
echo "<tr id = row1>";
echo "<th id = sortTable onclick=sortTable(0)>Name ↕</th>";
echo "<th style = width:100px;>EXT</th>";
echo "<th style = width:300px;>Returning Time</th>";
echo "<th style = width:300px;>Returning Date</th>";
echo "<th style = width:70px;>Out</th>";
echo "<th style = width:100px;>Reset</th>";
echo "<th style = width:600px;>Booked</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
$currentCheck = $row['Out'];
if ($currentCheck == 0) {
echo "<tr>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
if ($currentTime == 0) {
echo "<td> <form> <input type = 'time', id = 'timePickChange'> </form> </td>";
} else {
echo "<td> <form> <input type = 'time', id = 'timePickChange' value =" . $currentTime . "> </form> </td>";
}
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = 'datePickChange' value =" . $currentDate . "> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)'> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
} else if ($currentCheck == 1) {
echo "<tr style = 'background-color: #E2E9FD'>";
echo "<td>" . $row['Name'] . "</td>";
echo "<td>" . $row['EXT'] . "</td>";
$currentTime = $row['Returning Time'];
echo "<td> <form> <input type = 'time', id = timePickChange disabled> </form> </td>";
$currentDate = $row['Returning Date'];
echo "<td> <form> <input type = 'date', id = datePickChange disabled> </form> </td>";
echo "<td> <form onclick = 'checkIfOutRow(this)'> <input type = 'checkbox', onclick = 'checkIfOutValue(this)' checked> </form> </td>";
echo "<td> <button onclick = 'clearForm(this)', id = buttonClear>Reset</button> </td>";
echo "<td> <textarea rows = '1', cols = '60'> </textarea> </td>";
}
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sqlStart. " . mysqli_error($link);
}
?>
Depending on your data validation model, you might want to control the inputs value client side before posting them to your back-end.
AFAIK, you're already adding/editing/removing your contacts on the client side, so If I understand correctly, when your user should click on Edit/Remove & confirm , it would be a confirmation of what the user has done in the browser, this doesn't really change much apart from the fact that otherwise you might need dedicated buttons/row (or any other bindable events).
For these operations what you could do is proceed to bulk delete / edit, and this could be easily done by filtering out in your JS all the modified/deleted data and sending it to your back end PHP with Ajax/jQuery in the form of a stringified array.
As for insertion operation you'd submit them at the same time you add them to your table, by executing a POST operation.
And it could be done with something like this :
$.ajax({
method: "PUT",
url: "some.php",
data: JSON.stringify(myUpdatedDataInAnArray)
// you might need to stringify your array to ensure format ?
})
.done(function( msg ) {
alert( "Data Updated: " + msg );
});
In your back end php, you'd listen for POST/PUT/DELETE methods with something like that :
if (isset($_POST['add'])){
do your thing
}
if (isset($_PUT['updated'])){
//Since you're sending a stringified array, you must parse it with
$myArray = json_decode($_PUT['updated']);
do your thing
}
if (isset($_DELETE['deleted'])){
do your thing
}
I say Ajax because using a traditional POST/PUT/DELETE form would result in refreshing the page.
Here are some useful refs :
JS JSON Stringify and JSON Parse
PHP : JSON DECODE and JSON Encode
Ajax docs
Ajax Examples

form reset button is not working after submitting the form to itself in php

here is my js code
<script type="text/javascript">
function resetForm(formID)
{
var myForm = document.getElementById(formID);
for (var i = 0; i < myForm.elements.length; i++)
{
if ('submit' != myForm.elements[i].type && 'reset' != myForm.elements[i].type)
{
myForm.elements[i].checked = false;
myForm.elements[i].value = '';
myForm.elements[i].selectedIndex = 0;
}
}
}
</script>
here is my php code,
echo "<form class='navbar-form' id='formID' method='POST' action=''>";
$sqluser="SELECT DISTINCT username FROM user ORDER BY username ASC";
$resultuser=mysqli_query($conn,$sqluser);
if(isset($_POST['from_date']))
echo "<div class='form-group' style='margin-right:5px;'><input id='from_date' name='from_date' type='date' data-date-inline-picker='true' value='".$_POST['from_date']."'/></div>";
else
echo "<div class='form-group' style='margin-right:5px;'><input id='from_date' name='from_date' type='date' data-date-inline-picker='true' /></div>";
if(isset($_POST['from_date']))
echo "<div class='form-group' style='margin-right:5px;'><input id='to_date' name='to_date' type='date' data-date-inline-picker='true' value='".$_POST['to_date']."'/></div>";
else
echo "<div class='form-group' style='margin-right:5px;'><input id='to_date' name='to_date' type='date' data-date-inline-picker='true' /></div>";
echo "<div class='form-group' style='margin-right:5px;'><select id='username' name='username' style='width:170px;height:33px;'>";
if(isset($_POST['username']) && $_POST['username'] == "-- Username --")
echo "<option selected='selected'>-- Username --</option>";
else
echo "<option >-- Username --</option>";
while($ro1=mysqli_fetch_array($resultuser))
{
if(isset($_POST['username']) && $_POST['username'] == $ro1['username'])
echo "<option selected='selected' value='".$ro1['username']."'>".$ro1['username']."</option>";
else
echo "<option value='".$ro1['username']."'>".$ro1['username']."</option>";
}
echo "</select>";
echo "</div>";
echo "<div class='form-group' style='margin-right:5px;'><input name='reset' type='reset' onclick='resetForm('formId'); return false;' /></div>";
echo "<div class='form-group' style='margin-right:5px;'><input type='submit' value='submit'></div>";
echo "</form>";
on clicking the submit button, the form is submitted to the same page and result will be displayed below the form. i'm displaying the user inout values in the form , even after submitting. now,i want a reset button to clear all the input fields.after submitting the form, but the reset button is working before submission and it isn't working after submission.
The form id passed on Reset button's onclick function is incorrect.
Change resetForm('formId'); to resetForm('formID');
Alternatively, you can eliminate the need for custom function and let type=reset do its job.
Change your reset button from
<input name='reset' type='reset' onclick='resetForm('formId'); return false;' />
to
<input name='reset' type='reset' value='Reset'/>
Input Type Reset Reference Link
you don't have to write that much code just place a reset but in for
after form submitted click this button using jquery
<button type="reset" id="rest" value="Reset">Reset</button>
$("#rest").click();
in java script , add date in switch cases.
<script type="text/javascript">
function resetForm(form) {
// clearing inputs
var inputs = form.getElementsByTagName('input');
for (var i = 0; i<inputs.length; i++) {
switch (inputs[i].type) {
// case 'hidden':
case 'text':
inputs[i].value = '';
break;
case 'radio':
case 'checkbox':
inputs[i].checked = false;
case 'date':
inputs[i].value='mm/dd/yyyy';
}
}
// clearing selects
var selects = form.getElementsByTagName('select');
for (var i = 0; i<selects.length; i++)
selects[i].selectedIndex = 0;
// clearing textarea
var text= form.getElementsByTagName('textarea');
for (var i = 0; i<text.length; i++)
text[i].innerHTML= '';
return false;
}
</script>

How to verify only one checkbox is selected from checkbox list

Here i am retriving data from database and i am doing insert,update and delete of data using checkbox.My problem is when i click more than two checkbox than also i am moving to update.php page but what i actually want is that when i click on update button first it will check that only one checkbox is selected from list if not than alert message should display like select only one checkbox. please help.Thanks in advance
Here i have put my code.
<!DOCTYPE html>
<html>
<head>
<title>Insert Update Delete</title>
</head>
<body>
<form name="dataform" id="data" action="" method="get">
<?php
$connection = mysql_connect("localhost", "root", "");
$db = mysql_select_db("db_new", $connection);
$query=mysql_query("select * from student_info");
echo "<table>";
while($row=mysql_fetch_array($query))
{
echo "<tr>";
echo "<td>"; ?> <input type="checkbox" id="box" name="num[]" class="other" value="<?php echo $row["id"];?>" /> <?php echo "</td>";
echo "<td>"; echo $row["roll_no"]; echo "</td>";
echo "<td>"; echo $row["name"]; echo "</td>";
echo "<td>"; echo $row["division"]; echo "</td>";
echo "<td>"; echo $row["std"]; echo "</td>";
echo "<td>"; echo $row["gender"]; echo "</td>";
echo "<td>"; echo $row["subject"]; echo "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="insert" value="insert"/>
<input type="submit" name="update" value="update"/>
<input type="submit" name="delete" value="delete"/>
</div>
</form>
<?php
if(isset($_GET["insert"]))
{
$box = $_GET['num'];
$count =count($box);
if ($count == 0){
header('Location:insert.php');
}
elseif($count == 1){
header('Location:data.php');
}
}
?>
<?php
if (isset($_GET['update'])){
$box = $_GET['box'];
$count =count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:update.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
echo $id;
header("location:update.php?id=".$id);
}
}
}
?>
<?php
if (isset($_GET['delete'])) {
$box = $_GET['num'];
$count = count($box);
if($count == 0) {
header('Location:data.php');
}elseif($count == 1){
header('Location:data.php');
}
if(!empty($_GET['num'])) {
foreach($_GET['num'] as $id) {
mysql_query("delete from student_info where id = $id");
}
}
}
?>
</body>
</html>
You could use a radio button for this instead of a checkbox.
see sample here
Use Radio Instead of CheckBox
Or if you must use a checkbox do this:
$('input.example').on('change', function() {
$('input.example').not(this).prop('checked', false);
});
I would use a radio button, however I don't know your situation so here's a solution using jQuery. You want to select all of the checkboxes that are checked then see if the length of that array is greater than one. Here's the javascript code you'll need and a jsbin if you want to look at it.
http://jsbin.com/qakuzajaza/edit?js,output
$("#submitbutton").click(function() {
var count = $("input[type=checkbox]:checked").length;
if (count > 1) {
alert("Only 1 can be selected");
} else {
// submit data
}
});
1. Try this, it will not allow you to check only one checkbox at a time.
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var chks = document.getElementById('#ckeckboxlistId').getElementsByTagName('INPUT');
for (i = 0; i < chks.length; i++) {
chks[i].checked = false;
}
if (chks.length > 1)
$(this)[0].checked = true;
});
});
The approaches are more or less similar. Try this:
submitForm(); //according to an event you prefer (click some button or anchor , no button over $ .ajaks.
function submitForm(){
var tag = document.getElementById("tdForm");
var chkbx = $(tag).find("input[type='checkbox']:checked").length;
if (chkbx !== 0) {
if (chkbx > 1) {
alert("more then 1");
}else{
alert("form submited"); //$(tag).submit();
}
}else{
if (chkbx === 0) {
alert("nothing cecked");
}
}
};
Tested works for me. Hope it helps!
While I think the radio buttons or previous validation, and interception of errors on the rules for completing the form, are much more affordable.

javascript alert on checkbox value

I have checkboxes whose value attribute is coming from database.I want the user to always check the checkboxes having same value if he does not then alert using javascript.I tried to do this using the following javascript code but no use
<script>
function ck()
{
var x,item,f;
list=document.getElementById("yo");
f=list[0].value;
for(index=1;index<list.length;++index)
{
item=list[index];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>
Below is the PHP code for checkbboxes
<?php
$flag1=-1;
$conn = mysqli_connect("localhost", "root","","discvr");
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
$time_id=$j;
$sql="select status from final where location = '$location' AND date='".$cur_date."' AND time_id=$time_id";
$query=mysqli_query($conn,$sql);
if(!$query)
{
$status=0;
echo "Hi";
}
else
{
if($row=mysqli_fetch_array($query))
{
//echo "hi";
$status=$row['status'];
}
else
$status=0;
//echo $time_id;
}
if($i==0)
echo "<td><input type='checkbox' id='yo' name=time[] value=".$j." value='".$status."' onclick='ck()' > $status </td>";
else
echo "<td><input type='checkbox' id='yo' name=time".$i."[] value=".$j." value='".$status."' onclick='ck()' >$status</td>";
}
echo "</tr>";
}
?>
give unique id's to each checkbox even you are not using them.
Note: on your page id's should be unique.
try like this:
use your connection and other this ,it is for demo.
<?php
for($i = 0; $i < 150; $i++) {
echo "<tr>";
$cur_date=date("Y-m-d");
echo "<td>Noida Sector ".($i+1)."</td>";
$location="Noida Sector ".($i+1);
for($j=1;$j<=8;$j++)
{
if($i==0)
echo "<td><input type='checkbox' id='yo$i' name=time[] value=".$j." value='".$status."' onclick='ck(this.value)' > $status </td>";
else
echo "<td><input type='checkbox' id='yo$i' name=time".$i."[] value=".$j." value='".$status."' onclick='ck(this.value)' >$status</td>";
}
echo "</tr>";
}
?>
javascript:
<script>
function ck(value)
{
var x,item,f;
list= document.getElementsByTagName("input");
f=value;
console.log(f);
for(i=1;i<list.length;++i)//change your logic here don't know what you are trying here
{
item=list[i];
x=item.value;
if(x!=f)
{
alert("Wrong type checkboxes selected!");
break;
}
}
}
</script>

loop list of input checkbox and get values

I am trying to get a table of names checked,
and send this array to a PHP page.
But I dont know how, I began by this code:
$(".ok").click(function(){
$("input[type='checkbox']:checked").each(function() {
var tt = $(this).val();
alert(tt);
});
});
echo "<table>";
foreach ($result as $data) {
echo "<tr>";
echo "<td><input type='checkbox' value='$data[0]' /></td><td>$data[0]</td>";
echo "</tr>";
}
echo "</table>";
Try..
$(".ok").click(function(){
//check if any are checked and if so redirect..
if($("input[type='checkbox']:checked").length > 0)
window.location.href = 'page.php?'+$("input[type='checkbox']:checked").serialize();
});
then in page.php..
$result = $_GET;
if(count($result)){
foreach($result as $data){
echo "<tr>";
echo "<td><input type='checkbox' value='$data' /></td><td>$data</td>";
echo "</tr>";
}
}

Categories

Resources