JavaScript alert on click event if no checkboxes are checked - javascript

Every thing works normally except when I check all the rows and try to delete them with a button.
I put an alert in the delete button which tests if any rows are checked, so when I click the button and no boxes are checked, it shows the alert.
Also when all the boxes are checked how do I change it or where do I put it?
I am new to JavaScript and php.
Or can I change it to a delete confirmation alert!
Here is my code .
<script>
function checkUncheckAll(){
var chks = document.getElementsByName("ck");
if(document.getElementById("ck_All").checked)
{
$("#delete_link").on("click" , deleteSelectedRows);
for( i = 0;i < chks.length;i++)
document.getElementsByName("ck")[i].checked = true;
}
else {
for( i = 0;i < chks.length;i++)
document.getElementsByName("ck")[i].checked = false;
document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
}
}
function selectUnselect(checked){
if(!checked)
document.getElementById("ck_All").checked = false;
else {
document.getElementById("delete_link").onclick = function(){deleteSelectedRows();};
var chks = $("input[name='ck']");
var all_checked = true;
for(i=0;i<chks.length;i++)
if(chks[i].checked)
continue;
else {all_checked = false; break;}
if(all_checked)
document.getElementById("ck_All").checked = true;
}
}
function deleteSelectedRows(){
var cks = $("input[name='ck']");
var checked = [];
for(i = 0;i<cks.length;i++)
if(cks[i].checked)
checked.push(cks[i].parentNode.parentNode.id);
var jsonob = JSON.stringify(checked);
$.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
for(i=0;i<checked.length;i++)
$("#" + checked[i]).fadeOut('slow' , function(){$(this).remove();});
});
}
</script>
<a id="delete_link" onclick="alert('Aucune case n est cochée')">Supprimer</a>
<br><br>
<?php
$con = new mysqli('localhost' , 'root' , 'etud' , 'responses');
echo "<div id='divtable'>";
echo '<table class="table" >';
echo '<tr id="throws">
<th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
<th>Nom</th>
<th>Email</th>
<th>Sujet</th>
<th>Messages</th>
<th>Date Creation</th>';
// if (isset($_POST['date'])& isset($_POST['btncherche'])) {
error_reporting(E_PARSE);
$datechoosen=$_POST['date'];
$result = $con->query("select * from tb_cform where datecreation='".$datechoosen."'");
while($row = $result->fetch_assoc())
echo '<tr id="' . $row['id'] . '">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>' . $row["u_name"] .'</td>
<td> '. $row["u_email"] . '</td>' .
'<td>' . $row["subj"] . '</td>' .
'<td>' . $row["message"] . '</td>' .
'<td>' . $row["datecreation"] . '</td>' .
'</tr>';
echo '</table>';
echo "</div>";
/* }else{
echo "veuillez choisir la date S.V.P !";
}*/
?>
When I click the delete button the alert keeps showing no matter what the condition is, help me please!

One thing I must point out is that it is best to keep your click event handlers out of your HTML and bundled with the rest of your JavaScript, see Why is using onClick() in HTML a bad practice?.
Please see my working example on JSFiddle: https://jsfiddle.net/fL91x2am/23/
Working code:
<script>
function deleteSelectedRows(){
var cks = $("input[name='ck']");
console.log(cks.length);
var checked = [];
// Add ids of checked messages to checked array
for(i = 0;i<cks.length;i++){
if(cks[i].checked){
checked.push(cks[i].parentNode.parentNode.id);
}
}
// AJAX delete POST
var jsonob = JSON.stringify(checked);
$.post("deletecom.php" , {rows_to_be_deleted:jsonob} , function(data){
for(i=0;i<checked.length;i++){
// hide deleted messages row if delete POST successful
$("#" + checked[i]).fadeOut('slow' , function(){
$(this).remove();
});
}
});
}
function checkUncheckAll(){
// var chks = all checkboxes
var chks = document.getElementsByName("ck");
// if select all checkbox is checked
if(document.getElementById("ck_All").checked) {
for( i = 0;i < chks.length;i++ ){
document.getElementsByName("ck")[i].checked = true;
}
} else {
for(i = 0;i < chks.length;i++){
document.getElementsByName("ck")[i].checked = false;
}
}
};
function selectUnselect(checked){
if(!checked){
document.getElementById("ck_All").checked = false;
} else {
document.getElementById("delete_link").onclick = function(){
deleteSelectedRows();
};
var chks = $("input[name='ck']");
var all_checked = true;
for(i=0;i<chks.length;i++){
if(chks[i].checked){
continue;
} else {
all_checked = false;
break;
}
}
if(all_checked){
document.getElementById("ck_All").checked = true;
}
}
}
// Here we use jQuery's document ready event listener to add the click event listener to #delete_link.
$(document).ready(function(){
$('#delete_link').on('click', function(){
// (jQuery syntax) - check if number of checked inputs with name attribute of 'ck' is zero
if($('input[name="ck"]:checked').length === 0){
alert('Please select an item!');
} else {
// or confirm if the user really wants to delete
var warning = confirm("Are you sure you want to delete?");
if (warning == true) {
deleteSelectedRows();
}
}
});
})
</script>
<a id="delete_link">Supprimer</a>
<br><br>
<div id="divtable"><table class="table">
<tr id="throws">
<tr><th><input id="ck_All" type="checkbox" onchange="checkUncheckAll()" />Select</th>
<th>Nom</th>
<th>Email</th>
<th>Subject</th>
<th>Messages</th>
<th>Date Creation</th></tr>
<tr id="1">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>Name</td>
<td>Email</td>' .
<td>Subject</td>
<td>Lorem ipsum dolor</td>
<td>2017-01-01</td>
</tr>
<tr id="2">
<td><input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" /></td>
<td>Name</td>
<td>Email</td>' .
<td>Subject</td>
<td>Lorem ipsum dolor</td>
<td>2017-01-01</td>
</tr>
</table>
</div>

Related

Logical Operators doesn't work in javascript and about node counts by input value

I'm trying to make node counter by id, node name, and attribute name&value!
Here I would like to check if every is empty then show "HERE IS NO VALUE OF YOU ENTERED".
here in the end of I try to use <&&> but it doesn't work!
also is that impossible to use just tag instead of in the end of the code? when i tried, it show eror :(
** I have no idea of how to count attribute name&value number..**
I'm realy begginer of javascript ! thank you in advance guys!!
this is my form html.
function javascript_click() {
/* 자바스크립트 id값 찾기 */
if (document.getElementById("value1").value) {
var val = document.getElementById("value1").value;
if (document.getElementById(val)) {
//var myNodelist = document.getElementById("val").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 노드명 찾기 */
else if (document.getElementById("value2").value) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
}
/* 자바스크립트 attribute 찾기 */
/* 자바스크립트 속성명&값 찾기 */
else if (
document.getElementById("value3").value &&
document.getElementById("value4").value
) {
var val2 = document.getElementById("value2").value;
if (document.querySelector(val2)) {
// alert(val2);
var myNodelist = document.querySelectorAll(val2);
document.getElementById("cnt").innerHTML += "선택하신 노드는 " + val2 + " 이며 노드갯수는 " + myNodelist.length + "개 입니다. By javascript<br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}
} else if (
(document.getElementById("value1").value &&
document.getElementById("value2").value &&
document.getElementById("value3").value &&
document.getElementById("value4").value) == 0
) {
document.getElementById("cnt").innerHTML += "THERE IS NO VALUE OF YOU ENTERED<br>";
}
}
<form action="">
<table class="tg" id="tg">
<tr>
<td>id</td>
<td><input type="text" id="value1"></td>
</tr>
<tr>
<td>node name</td>
<td><input type="text" id="value2"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
<tr>
<td>attribute</td>
<td><input type="text" id="value3"></td>
</tr>
</table>
<div id="cnt"></div>
</form>
<div class="button">
<button id='btn_javascript' onclick="javascript_click();">자바스크립트</button>
</div>
You may do validation like this:
if (document.getElementById("value1").value!=='') {
let val1 = document.getElementById("value1").value;
document.getElementById("cnt").innerHTML += "선택하신아이디는 " + val1 + " 이며 id갯수는 1개입니다.By javascript <br>";
} else {
document.getElementById("cnt").innerHTML += "wrong value of ID <br>";
}

How to bind table id to DOM in ajax success function

In my project, I want to do something when checkbox is clicked.
Here is my code which works OK:
<script>
window.onload=function()
{
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
alert("xietest");
}
},false);
}
</script>
<div class="easyui-panel" id="pp" >
<table class="uTb" id="uTId" cellspacing="0" style="100%" >
<tr>
<td ><input type="checkbox" id="Jack"/>Jack</td>
</tr>
</table>
</div>
And "xietest" can be appeared in page successfully when checkbox is clicked;
But actually the content of pp easyui-panel is from ajax , like:
<script>
...
$.ajax({
.......
success:function(data){
var drfV='<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV=drfV+'<tr><td ><input type="checkbox" value="'+data.name+'"/>'+data.name+'</td>';
drfV=drfV+'</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
}
});
....
window.onload=function()
{
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
alert("xietest");
}
},false);
}
</script>
<div class="easyui-panel" id="pp"></div>
Now It works fail, "xietest" can not show like before.
I know that table id uTId should not be found in DOM as it was loaded after window onload.
But I don't know how to bind table id uTId to DOM, Who can help me?
As you said, you can't declare an event for unloaded dom element yet. You should handle all success events and define the event after. So, you could use setInterval to apply it.
var ajax1Success = true;
var ajax2Success = true;
success: function(data) {
var drfV = '<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV = drfV + '<tr><td ><input type="checkbox" value="' + data.name + '"/>' + data.name + '</td>';
drfV = drfV + '</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
//Declare the event
ajax1Success = true;
}
success: function(data) {
var drfV = '<table class="uTb" id="uTId" cellspacing="0" style="100%" >';
drfV = drfV + '<tr><td ><input type="checkbox" value="' + data.name + '"/>' + data.name + '</td>';
drfV = drfV + '</tr></table>';
$('#pp').html("");
$('#pp').append(drfV);
//Declare the event
ajax2Success = true;
}
var t = window.setInterval(function () {
var ajaxSuccess = ajax1Success || ajax2Success;
if (ajaxSuccess == true) {
clearInterval(t);//Clear the interval after at least one ajax call have been succeeded
var uTId = document.getElementById('uTId');
uTId.addEventListener("click", function (ev) {
if (ev.target.getAttribute("type") == "checkbox") {
alert("xietest");
}
});
}
}, 1000);

Trouble looping through data in HTML using JavaScript

I am using javaScript to go through 149 input type number fields and I am having problems getting it to work. I have conditions set that if the value of those number fields are negative, float, or 0 it will return an error message using
alert(" Error Message");
I am iterating through my input type's through a for loop like the following
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var i; var x = 0; var s; var val; var test;
for (i = 1; i < 150; i++) {
s = '' + i; //converts i into string
val = document.getElementById(s).value; //Puts string value into val
test = +val; //Converts val into number
//Error Checking
}
I have tried this code on smaller input type = number fields (such as 10), and all of my error flags work, but whenever I use my needed number 149 (set to 150 because I want it to do one less than 150) I do not receive any error messages or activity from my funciton.
Check the following example .
//For Demo Puropse
for(i=1;i<300;i++){
var node = document.createElement("input");
node.id=i
node.value=i
document.getElementById("stage").appendChild(node)
}
function checkValues(){
for(i=1;i<300;i++){
elemValue = document.getElementById(i).value
if(! isInteger(elemValue) || ! elemValue){
alert("Error ! : " + elemValue + "#" + i)
return;
}
}
alert("Passed")
}
function isInteger(x) {
return x % 1 === 0;
}
<button onclick="checkValues()">Check</button>
<br/>
<div id="stage"></div>
So here is my code. I am reading from a data base that I did not want to display the credentials too. In my code you will see a comment that has the comment question. Is there a way that I can just use php to get the product number and the quantity so that I can use it in form.php. It is a post method, but as the question says I am fairly new to this coding language. Hopefully this code snippet will tell you more about what I am actually trying to accomplish.
<form action="form.php" method="post">
<table cellpadding="6">
<tr>
<th>Description</th>
<th>Price</th>
<th>Weight</th>
<th>Image</th>
<th>Quantity</th>
</tr>
<!-- PHP LANGUAGE -->
<?PHP
$sql = "SELECT * FROM parts";
$q = $conn->query($sql) or die("ERROR: " . implode(":", $conn->errorIndo()));
while( $row = $q->fetch(PDO::FETCH_ASSOC))
{
echo '<tr>' .
'<td>' . $row['description'] . '</td>' .
'<td>' . $row['price'] . '</td>' .
'<td>' . $row['weight'] . '</td>' .
'<td> <img src="' . $row[pictureURL] .'" alt="' . $row[number] . '" style="width:50px;height:50px;">' .
'<td> <input type="number" id= "'. $row[number] . '" value="0">' .
'</td>' . '</tr>';
}
echo "</table>";
?>
</table> <br>
<input type="button" id="submit" value="Submit" />
</form>
<script>
var i; var x = 0; var s; var val; var test; var array = [];
$('form').submit(function(){{
var value = $(this).val();
for (i = 1; i < 5; i++) {
s = '' + i; //stores i as string
//getsElement id val string and stores into val
val = document.getElementById(s).value;
test = +val; //Converts string into tester int for error checking
if tester < 0 { alert("Must enter in one product!"); return;}
//CHECKS FOR FLOATS IN Quantity FIELD
else if (Math.floor(test) != Math.ceil(test)) { alert("Cannot have float quantities!"); return; }
else {
//My attempt at coding a block that captures the product
//Number, and the quantity selected. Is there a way
/* QUESTION */
array.push(i); array.push(x)
}
}
if (x == 0) { alert("Must have at least one product quantity to continue!"); return; }
else { alert("good!"); }
}}
</script>
</body>
</html>

POST Ajax request

I'm working on an old project that wasn't developed by me at first. I need to make an Ajax request so that the values contained in the fields (more on that later) be sent to a php script which will then return their values into the correct td.
Here is the JavaScript/jQuery code.
$(function ()
{
$('form').on('submit', function (e)
{
e.preventDefault();
$.ajax
({
type: 'post',
url: 'envoi_dispo_semaine.php',
data: $('form').serialize(),
success: function ()
{
alert('Le planning a été mis à jour.');
}
});
});
jQuery(document).ready(function date()
{
Date.prototype.getWeek = function() {
var onejan = new Date(this.getFullYear(),0,1);
var today = new Date(this.getFullYear(),this.getMonth(),this.getDate());
var dayOfYear = ((today - onejan +1)/86400000);
return Math.ceil(dayOfYear/7)
};
var today = new Date();
var t = today.getWeek();
})
jQuery(document).ready(function()
{
jDispo = {};
jCharge = {};
jSolde = {};
var d = 0;
var c = 0;
var s = 0;
jQuery('.DISPO').each(function()
{
jDispo[d] = jQuery(this).val();
d++;
});
jQuery(".CHARGE").change(function()
{
var totalCharge = 0;
if(jQuery(".CHARGE").length > 0)
{
jQuery(".CHARGE").each(function()
{
jCharge[c] = jQuery(this).val();
c++;
totalCharge = totalCharge + jQuery(this).val();
});
}
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function()
{
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
});
});
$(document).ready(function()
{
if ($("#tab_projets table tbody tr:eq(2) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(2) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(5) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(5) td:contains('-')").css('font-color', 'black');
}
if ($("#tab_projets table tbody tr:eq(8) td:contains('-')").length)
{
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('background', '#CCFF00');
$("#tab_projets table tbody tr:eq(8) td:contains('-')").css('font-color', 'black');
}
});
});
And here is check_charges.php:
<?php
include('connexion_db.php');
$charge = $_POST['charge'];
$dispo = $_POST['dispo'];
$solde = $_POST['solde']; //I'll need this one later on.
$res = $dispo - $charge;
echo $res;
?>
I also have some php code that allows me to generate a table (it's in the same file as the javascript):
<thead>
<?php
echo " <td colspan=2>Semaine n°</td>
<td>Retard</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
echo "<form action=\"envoi_dispo_semaine.php\" method=\"post\">
<td>
<input type=\"hidden\" name=\"semaine_id\" value=\"".$i."\" />".$i."</td>";
}
?>
</thead>
<tbody>
<?php
foreach($users as &$myUser)
{
echo " <tr class=".$myUser.">
<td width=66% rowspan=3><input type=\"hidden\" name=\"login\" value=\"".$myUser."\" onblur=\"updateCharge\"/>".$myUser."</td>
<td width=34%>Disponibilité</td>
<td rowspan=3></td>
";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query = requete_is_plancharges($req);
$row = mysql_fetch_row($query);
$affichageDispo = $row[0];
if ($affichageDispo == "")
{
$affichageDispo = 3;
}
echo "
<td>
<input class=\"DISPO\" type=\"number\" name=\"disponibilite[]\" value=".$affichageDispo." min=\"0\" max=\"5\" step=\"0.5\" class=\"input\"/>
</td>
";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Charge</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$reqTache = "
SELECT tache_id
FROM Tache
WHERE ebi_id = ".$ebi."
AND demande_id = ".$demande."
AND action_id = ".$action;
$resultatTache_id = requete_is_plancharges($reqTache);
$maTache = mysql_fetch_object($resultatTache_id);
$req_Charge = "
SELECT COUNT(charge) as charge_tache
FROM Charge_par_tache
WHERE tache_id =".$maTache->tache_id.
" AND semaine_id =".$i.
" AND login = '".$myUser."'";
$resultat_requete_Charge = mysql_fetch_object(requete_is_plancharges($req_Charge));
if ($resultat_requete_Charge->charge_tache > 0)
{
$req = "
SELECT Charge_par_tache.charge
FROM Charge_par_tache, Tache
WHERE Charge_par_tache.tache_id = Tache.tache_id
AND Tache.ebi_id = ".$ebi."
AND Tache.demande_id = ".$demande."
AND Tache.action_id = ".$action."
AND Charge_par_tache.login = '".$myUser."'
AND Charge_par_tache.semaine_id = ".$i;
$Charge = mysql_fetch_object(requete_is_plancharges($req));
} else
{
$Charge->charge = "";
}
echo " <input type = \"hidden\" name = \"tache_id\" value=".$maTache->tache_id.">
<td class=\"CHARGE\">";
$query = requete_is_plancharges($req);
$row = mysql_fetch_array($query);
$affichageCharge = $row[0];
echo " <input class=\"CHARGE\" type=\"number\" name=\"charge[]\" value=".$Charge->charge." min=\"0\" step=\"0.5\"/>
</td>";
}
echo"
</tr>
<tr class=".$myUser.">
<td width=34%>Solde</td>";
for ($i=$numerosemaine; $i <= $numerosemaine + $longueurAff; $i++)
{
$req1 = "
SELECT charge FROM Charge_par_tache WHERE login = '".$myUser."' AND semaine_id = ".$i;
$req2 = "
SELECT Nb_max_jours FROM Dispo_par_semaine WHERE login = '".$myUser."' AND semaine_id = ".$i;
$query1 = requete_is_plancharges($req1);
$row1 = mysql_fetch_row($query1);
$query2 = requete_is_plancharges($req2);
$row2 = mysql_fetch_row($query2);
$solde=$row2[0]-$row1[0];
echo "<td class=\"SOLDE\"><input type=\"hidden\" class=\"SOLDE\" value=".$solde."/> ".$solde."</td>";
}
?>
</tr>
<?php
}
?>
</tbody>
</table>
<p><input type="submit" name="submit" value="Mise à jour"></p>
</form>
The problem is that I can't seem to retrieve $res. I'm just starting Ajax so I really don't know what to do, and couldn't find the answer on the Internet as I use a js array to store my values.
If I understand your problem you want to get the response value of "check_charges.php", that it is the $res value, isn't it? The value will be returned in the first parameter of success function of your ajax.
Your code:
jQuery('.SOLDE').each(function()
{
jSolde[s] = jQuery(this).val();
$.ajax(
{
type:'post',
url:'check_charge.php',
data:{charge : jCharge[s],solde : jSolde[s],dispo : jDispo[s],action:"update_site"},
success: function(data)
{
// Store where you want the data value
alert('res value: ' + data);
$('jSolde[s]').empty();
$('jSolde[s]').append();
$('.ajax').html($('.ajax input').val());
$('.ajax').removeClass('ajax');
}
});
s++;
});
I hope I have helped you.

how to handle scroll up and scroll down with ajax request?

Here I am uploading this link http://harvey.binghamton.edu/~rnaik1/myForm.html where you can see how my scroll up n down button is working in javascript but now I am working with Ajax request to a php script on the server to retrieve all of the data from the database table.
Here is the link for the work i have done:http://harvey.binghamton.edu/~rnaik1/myScrollform.html
Everything is working fine for me except scroll up and scroll down button.
Once you add 5 records in a list after entering 6th record it will show latest 5 records.
I want to make the scrollup and down button working for myScrollform.html in the same way as in myForm.html. Any help would be helpful to me and appreciated.
Here is my code:
<html>
<head>
<title>My Scrolling Data Form</title>
<script src="./jquery-1.11.0.min.js"></script>
</head>
<body bgcolor="silver">
<center><h1>My Scrolling Data Form</h1>
<div id="scrollbar">
<input type="button" name="up" id="scrollup" value="Scroll Up" >
<input type="button" name="up" id="scrolldown" value="Scroll Down">
</div>
<div id="mydata" style="height: 200px; overflow-y: scroll">
Currently we have no data
</div>
<hr>
<div id="addformdata">
<form name="addForm" >
To add data to the list, fill in the form below and click on "Add"
<br>
<td><input type="text" id="name" name="namei" value=""></td>
<td><input type="text" id="ssn" name="ssni" value="" ></td>
<td><input type="text" id="date" name="birthi" value="" ></td>
<td><input type="text" id="currency" name="xxxxi" value=""></td>
<input type="button" name="add" value="Add" onclick="validateForm(); return false;">
</form>
</div>
</center>
</body>
</html>
<script type="text/javascript">
// Arrays to store values
var name_Array=new Array();
var ssn_Array=new Array();
var date_Array=new Array();
var currency_Array=new Array();
var Index = 0;
var first = 0;
var last = 0;
var scrolled = 0;
var random_Array=new Array();
$(document).ready(function(){
fetchdata();
$("#scrollup").on("click" ,function(){
// alert('hi');
// scrolled=scrolled+100;
$("#mydata").animate({
scrollTop: 0
}, 800);
});
$("#scrolldown").on("click" ,function()
{
// console.log($elem.height());
$("#mydata").animate({
scrollTop: 5000
}, 800);
});
});
function deleteRecord(id)
{
if(confirm('Are you Sure you Want to delete this record')){
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "delete",
"id": id
},
success:function(data)
{
fetchdata()
console.log('success');
}
});
}
}
function fetchdata()
{
// var scrolled=0
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"action": "fetch"
},
success:function(data)
{
$("#mydata").html('')
$("#mydata").html(data);
console.log('success');
}
});
}
function validateForm()
{
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
var error = "";
//Name validation
if(name.value=="")
{
//Check for empty field
name.focus();
error = "Please Enter Name\n";
}
else
{ //format specifier
var letters = /^[a-zA-Z_ ]+$/;
//Check for format validation
if(!name.value.match(letters))
{
name.focus();
error = error + "Name contains only characters and spaces\nPlease Renter Name\n";
}
}
//Date validation
if(date.value=="")
{
//Check for empty field
date.focus();
error = error + "Please Enter Date\n";
}
else
{ //format specifier
var date_regex = /^((((0[13578])|([13578])|(1[02]))[\/](([1-9])|([0-2][0-9])|(3[01])))|(((0[469])|([469])|(11))[\/](([1-9])|([0-2][0-9])|(30)))|((2|02)[\/](([1-9])|([0-2][0-9]))))[\/]\d{4}$|^\d{4}$/;
//check for format validation
if(!date.value.match(date_regex))
{
date.focus();
error = error + "Date must be in mm/dd/yyyy format\nPlease Renter Date\n";
}
}
//SSN validation
if(ssn.value=="")
{
//check for empty field
ssn.focus();
error = error + "Please Enter SSN\n";
}
else
{
//format specifier
var numbers = /^\d{3}((-?)|\s)\d{2}((-?)|\s)\d{4}$/g;
//check format validation
if(!ssn.value.match(numbers))
{
ssn.focus();
error = error + "SSN must be in xxx-xx-xxxx format\nPlease Renter SSN\n";
}
}
//Currency validation
if(currency.value=="")
{
//check for empty field
currency.focus();
error = error + "Please Enter Currency\n";
}
else
{
//format specifier
var pattern = /^(\$)\d+(\.\d{1,3})?$/g ;
//check for format validation
if(!currency.value.match(pattern))
{
currency.focus();
error = error + "Currency must be in $xx.xxx format\nPlease Renter Currency\n";
}
}
if(error)
{
alert(error);
return false;
}
else
{
var name = document.getElementById("name").value;
var ssn = document.getElementById("ssn").value;
var date = document.getElementById("date").value;
var currency = document.getElementById("currency").value;
console.log(name)
adduser(name,ssn,date,currency);
return true;
}
}
function insertToList()
{
// call a function to validate the fields
var valid_function = validateForm();
if(valid_function == false)
{
return false;
}
else
{
//get the entered values from fields
var name = document.getElementById("name");
var ssn = document.getElementById("ssn");
var date = document.getElementById("date");
var currency = document.getElementById("currency");
// push the values in the array
name_Array.push(name.value);
ssn_Array.push(ssn.value);
date_Array.push(date.value);
currency_Array.push(currency.value);
// generate and push random number in the array to search the record in array and then delete that record.
random_Array.push(Math.floor((Math.random()*100)+1));// http://stackoverflow.com/questions/8610635/how-do-you-use-math-random-to-generate-random-ints
//function to insert values to list
InsertValues();
// clear the fields after each add
clearFields();
alert("Record is successfully added to above list.");
// set focus back on the name field
name.focus();
}
}
function clearFields()
{
document.getElementById("name").value = "";
document.getElementById("ssn").value = "";
document.getElementById("date").value = "";
document.getElementById("currency").value = "";
}
// function to add to the list
function InsertValues()
{
var temp = 1,temp1 = 1,index = 0,i=0;
index = name_Array.length - 5;
for(i=0;i< name_Array.length;i++)
{
// when only first 5 entries are added to the list
if(name_Array.length>5)
{
// skip the first values so that only top 5 are shown in the list
if(temp>s)
{
if(temp1==5)
{
last = i;
}
else if(temp1==1)
{
first = i;
Index = i;
}
if(temp1<=5)
{
//initialise values of fields to the list
var str = "name" + temp1;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp1;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp1;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp1;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp1;
document.getElementById(str).value = random_Array[i];
}
temp1++;
}
}
else
{
var str = "name" + temp;
document.getElementById(str).value = name_Array[i];
str = "ssn" + temp;
document.getElementById(str).value = ssn_Array[i];
str = "birth" + temp;
document.getElementById(str).value = date_Array[i];
str = "xxxx" + temp;
document.getElementById(str).value = currency_Array[i];
str = "random" + temp;
document.getElementById(str).value = random_Array[i];
}
temp++;
}
}
// Delete a record from the list
function delete_a_Record(record)
{
var remove = 0,i=0,j=1;
var name = document.getElementById("name" + record.value);
var delRecord = document.getElementById("random" + record.value);
if(name.value)
{
remove = 1;
}
// check for the existence of record
if(remove == 1)
{
if(confirm("Click on 'OK' to delete the record\n"))
{
while(i < random_Array.length)
{
if(delRecord.value==random_Array[i])
{
// if yes then remove that record from list
name_Array.splice(i, 1);
ssn_Array.splice(i, 1);
date_Array.splice(i, 1);
currency_Array.splice(i, 1);
random_Array.splice(i, 1);
}
i++;
}
// make entire list empty
while(j <= 5)
{
var str = "name" + j;
document.getElementById(str).value = "";
str = "ssn" + j;
document.getElementById(str).value = "";
str = "birth" + j;
document.getElementById(str).value = "";
str = "xxxx" + j;
document.getElementById(str).value = "";
str = "random" + j;
document.getElementById(str).value = "";
j++;
}
//call this function again to insert values in the list
InsertValues();
record.checked = false;
}
}
else
{
alert("Nothing to delete in this record.");
record.checked = false;
}
}
// function to perform scrollUp n scrollDown
function handleScrolling(type)
{
var j,k,temp2 = 1;
// perform scroll only when there are more than 5 records in the list
if(name_Array.length>5)
{ // scroll up
if(type==1)
{
first--; // decrement the pointer to see upper records
if(first>=0)
{
for (j = first; j < name_Array.length; j++) // its showing top most record from jth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[j];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[j];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[j];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[j];
str = "random" + temp2;
document.getElementById(str).value = random_Array[j];
temp2++;
}
}
else
{
alert("Top of the list is reached\n");
first++;// increment the pointer to see lower records
}
}
else // scroll down
{
// increment the start point to see lower records if any
first++;
if(first<=Index)
{
for (k = first; k < name_Array.length; k++) //its showing bottom most record in the list from kth position
{
var str = "name" + temp2;
document.getElementById(str).value = name_Array[k];
str = "ssn" + temp2;
document.getElementById(str).value = ssn_Array[k];
str = "birth" + temp2;
document.getElementById(str).value = date_Array[k];
str = "xxxx" + temp2;
document.getElementById(str).value = currency_Array[k];
str = "random" + temp2;
document.getElementById(str).value = random_Array[k];
temp2++;
}
}
else
{
alert("Bottom most record is reached\n");
first--;//decrement the pointer to see upper records if any
}
}
}
else
{
alert("Scrolling strikes for records more than 5\n");
return false;
}
}
function adduser(name,ssn,date,currency)
{
$.ajax({
url:"insdel.php",
type:'POST',
data: {
"name": name,
"ssn": ssn,
"date": date,
"currency": currency,
"action": "add"
},
success:function(data){
console.log('success');
fetchdata();
}
});
}
</script>
//php file
<?php
extract($_POST);
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error($con));
}
//mysql_select_db("ripal");
mysql_select_db("test");
//$sql = "SELECT * FROM user WHERE id = '" . $q . "'";
if ($action == 'add') {
$sql = "INSERT INTO myform(name,ssn,date,income)VALUES('" . mysql_real_escape_string($name) . "','" . mysql_real_escape_string($ssn) . "','" . mysql_real_escape_string($date) . "','" . mysql_real_escape_string($currency) . "')";
// echo $sql;
mysql_query($sql);
echo mysql_insert_id();
} else if ($action == 'fetch') {
$sql = "select * from myform";
// echo $sql;
$result = mysql_query($sql);
$str = '<form name="myForm">
<table width="page">
<tr>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td align="center"></td>
<td></td>
</tr>';
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$ssn = $row['ssn'];
$date = $row['date'];
$currency = $row['income'];
$str.='<tr>
<td><input type="radio" id="' . $id . '" name="del" onclick="deleteRecord(this.id);"></td>
<td><input readonly type="text" value="' . $name . '" id="name1" name="name"></td>
<td><input readonly type="text" value="' . $ssn . '" id="ssn1" name="ssn"></td>
<td><input readonly type="text" value="' . $date . '" id="birth1" name="birth"></td>
<td><input readonly type="text" value="' . $currency . '" id="xxxx1" name="xxxx"><input type="hidden" name="random1" id="random1"></td>
</tr>';
}
}
$str.=' <tr>
<td colspan="5" id="scrollCount" align="center" style="padding-top:10px;"> </td>
</tr>
</table>
</form>';
if (mysql_num_rows($result) == 0) {
echo 'No data in Our Database please add one or more';
} else {
echo $str;
}
} else if ($action = 'delete') {
$sql = "DELETE from myform WHERE id=$id";
// echo $sql;
$result = mysql_query($sql);
echo $result;
}
mysql_close($con);

Categories

Resources