Select checkbox is not working with javascript - javascript

I've a html checkbox which select all checkbox after click. But unfortunately it's not working. What's the problem in here ?
javascript Code:
<script language="JavaScript">
function toggle(source) {
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}</script>
Php code:
echo "<table width='100%' cellpadding='0' cellspacing='0'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact Name</b></td>";
echo "<td class='tdhead' valign='top' width='100'><b>Contact
Number</b>";
echo '<input type="checkbox" onClick="toggle(this)" /> Toggle
All<br/>';
echo "</tr>";
while($row = mysqli_fetch_array($result))
{
$gid = $row['gid'];
$contact_name = $row['contact_name'];
$contact_no = $row['contact_no'];
echo "<tr>";
echo "<td class='tdhead2' valign='top'>$contact_name</td>";
echo "<td class='tdhead2' ><input type='checkbox' value='$gid' name='contact_no[]''
/> $contact_no</td>";
echo "</tr>";
}
echo "</table>";

The name on each of your elements is: contact_no[] but in your JS code, you getElementsByName('contact_no') - add [] to the getElementsByName call.

for a safety, you should handle event object like code below
<script type="text/javascript">
function toggle(evt) {
evt = window.event || evt;
var source = evt.srcElement || evt.currentTarget
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
</script>

<script language="JavaScript">
function toggle(source)
{
checkboxes = document.getElementsByName('contact_no');
for(var i=0, n=checkboxes.length;i<n;i++)
{
contact_no[i].checked = source.checked;
}
}
</script>

One another solution, you can add Id attribute on the main check box from which you want to perform select all action and make the same as class attribute of other check boxes.
E.g.
$(document).ready(function(){
$('.selectall').change(function({
var id = $(this).attr('id');
if ($(this)is(":checked")) {
$("." + id).attr('checked','checked');
} else {
$("." + id).attr('checked','');
}
}))
})
I hope this code helps you

Related

Retrieve the filtered data from HTML table and format it into array

I've been working on a function in a PHP system where I can filter the records and then export it to Excel that has a template using PHPSpreadSheet. My problem is that I don't know how to retrieve the filtered records as said in the title above. I think I'm missing something here in my code. This is my code in fetching the records from database into table.
<?php
$conn = mysqli_connect("localhost", "root", "", "db_ims");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM tbl_par";
$result = mysqli_query($conn, $sql);
echo "<table id='myTable'>";
echo "<thead><tr><th>Article</th>
<th>Description</th>
<th>Property Number</th>
</tr></thead>";
echo "<tbody>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['article'] . "</td>";
echo "<td>" . $row['description'] . "</td>";
echo "<td>" . $row['propertyNumber'] . "</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
// Close the database connection
mysqli_close($conn);
?>
<form action="" method="POST">
<input type="text" id="myInput" onkeyup="filterTable()" placeholder="Search...">
<input type="submit" id="generate" name="generate" value="Submit">
</form>
This is my code in filtering the records:
<script>
function filterTable() {
// Declare variables
var input, filter, table, tr, td, i, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td");
for (var j = 0; j < td.length; j++) {
txtValue = td[j].textContent || td[j].innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
} else {
tr[i].style.display = "none";
}
}
}
}
</script>
Lastly, this is the code in exporting the filtered table into excel using PHPSpreadSheet:
<?php
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
if (isset($_POST['generate'])) {
$spreadsheet = IOFactory::load('Template.xls');
//This is the part where I don't know what to put.
$data = array();
$worksheet = $spreadsheet->getActiveSheet();
$row = 10; // Start inserting data from row 10
foreach ($data as $item) {
$worksheet->setCellValue('A'.$row, $item['article']);
$worksheet->setCellValue('B'.$row, $item['description']);
$worksheet->setCellValue('C'.$row, $item['propertyNumber']);
// ...
$row++;
}
$writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
$writer->save('exported_file.xlsx');
}
?>
I tried every possible way that I know but still didn't got my expected result.
If you want to submit the values you need to echo the table inside the form and have something to submit - a hidden field for example - then you can add disabled to the fields you do not want to submit
const hide = txtValue.toUpperCase().indexOf(filter) === -1 : true : false;
tr[i].style.display = hide ? "none" : "";
tr[i].querySelector("[type=hidden]").disabled = hide;
I strongly suggest you use AJAX here instead.

how to append data using ajax posts and datatables are not working?

Hello there am trying to get the data from database using ajax posts but i didn't get any data properly. first column data is splinting in another columns(Member names are coming in image field and info field). Image also shared please check that. And also datatables are not working while fetching the data using Ajax. Help me out from this problem...
Thanks & Regards
<body>
<label>Party</label>
<select id='partydropdown' name='partydropdown' onchange="partyFunction();">
<option>--select a party--</option>
<?php
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
?>
<option value="<?php echo $row["Id"];?>">
<?php echo $row["PartyName"];?>
</option>
<?php }}?>
</select>
<div id="showhide"></div>
</body>
<script type="text/javascript">
function partyFunction(){
debugger;
$("#showhide").empty();
$("#showhide").html('');
$("#showhide").append("<table class='table table-bordered text-center table-responsive' border='1px' id='example'>"+
"<tr>"+
"<th>PartyMemberName</th>"+
"<th>Image</th>"+
"<th>Info</th>"+
"</tr>"+
"<tbody id='partyBody'>"+
"</tbody>"+
"</table>"
);
$postdata = {};
$postdata["Id"]=$("#partydropdown").val();
console.log($("#partydropdown").val());
$.post('test_data.php',$postdata,function (data) {
debugger;
console.log(data);
console.log(data["data"][0].candiateName);
$("#partyBody").empty();
$("#partyBody").html('');
console.log(data["data"]);
console.log(data["data"].length);
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
$("#partyBody").append("<tr>"+
"<td id='resdata"+i+"'></td>"+
"<td id='resdata1"+i+"' ></td>"+
"<td id='resdata2"+i+"'></td>"+
"</tr>");
$("#resdata"+i).text(data["data"][i].candiateName);
$("#resdata1"+i).append("<img id='photo"+i+"'>");
$("#resdata2"+i).text(data["data"][i].Background);
$("#photo"+i).attr('src', 'http://aptsvotes.com/wp-content/themes/apts2019/img'+data["data"][i].Photo );
}
}
});
};
</script>
here is the test_data.php code
<?php
include_once "conn.php";
include_once "voterdbclass.php";
session_start();
$tbl_name2="Parties";
$dbObj = new Database1();
$values1 = array("all");
$querys = "SELECT c1.CandidateName,c1.Photo,c1.Background ,c1.Type FROM aptsv1_votes.Parties p1 LEFT JOIN aptsv1_votes.Candidates c1 ON c1.CurrentPartyId = p1.Id where p1.Id ='" . $_POST['Id'] . "' limit 21";
$res = $dbObj->SelectRecord($tbl_name2,$values1,"","$querys");
$data=array();
$i=0;
while ($rs = $res->fetch_array(MYSQLI_ASSOC)) {
$data[$i]['candiateName']=$rs['CandidateName'];
$data[$i]['Photo']=$rs['Photo'];
$data[$i]['Background']=$rs['Background'];
$i++;
}
$json_array= array(
"data" =>$data
);
echo json_encode($json_array);
?>
for(var i=0; i<data["data"].length; i++){
if(data["data"][i].candiateName != null){
var imge = data["data"][i].Photo;
var name = data["data"][i].candiateName;
var bg = data["data"][i].Background;
$("#partyBody").append("<tr>"+
"<td id='resdata" + i + "'>" + name+"</td>"+
"<td id='resdata1" + i + "' ><img id= 'photo" + i + "' src='http://aptsvotes.com/wp-content/themes/apts2019/img'" + imge+"></td>"+
"<td id='resdata2" + i + "'>" + bg+"</td>"+
"</tr>");
}
}
You have to parse JSON data into the first script. While ajax result you posting with json_encode, I found missing
var data = $.parseJSON(data);
console.log(data["data"].length);
into code
$.post('test_data.php',$postdata,function (data) {
// debugger;
console.log(data);
var data = $.parseJSON(data); // Add this line in your code and verify
console.log(data["data"].length);
Thank you!

get checkbox attribute using javascript (array)

Hello guys i want to get the attribute of my checkbox. The checkbox was an array so i want to get the attribute of the checked checkboxes and put it on the textbox anf separate it with comma.
Here's my php/html
$query = $db->select('owners_information',array('*'),$con);
foreach($query as $q){
//echo $q['lastname'];
$output .= '
<tr>
<td>'.$q["firstname"].'</td>
<td>'.$q["middlename"].'</td>
<td>'.$q["lastname"].'</td>
<td>'.$q["land_area"].'</td>
<td><input type="text" value="'.$q["OCPC_ID"].'" name="ocid[]">
<input type="checkbox" value="'.$q["land_area"].'" name="checkval[]" attr="'.$q["OCPC_ID"].'"></td>
</tr>
';
}
if($query > 0){
echo '<input type="text" name="textval" id="textval">';
echo '<br><input type="text" name="ocpc_id" id="ocpc_id">';
echo '<input type="button" name="merge" id="merge" value="Merge" onclick="mergeFunc()">';
echo '<input type="button" name="addNew" id="addNew" value="Add New RPU" onclick="addMerge()" style="display:none;">';
echo $output;
}else{
echo "No data found";
}
And here's my javascript
function mergeFunc() {
var checkboxes = document.getElementsByName('checkval[]');
var cd = document.getElementsByName("checkval[]");
var val_id = "";
for (var l=0, n=cd.length;l<n;l++)
{
if (cd[l].checked)
{
val_id += ","+cd[l].attr;
}
}
if (val_id) val_id = val_id.substring(1);
alert(val_id);
var vals = "";
for (var i=0, n=checkboxes.length;i<n;i++)
{
if (checkboxes[i].checked)
{
vals += ","+checkboxes[i].value;
}
}
if (vals) vals = vals.substring(1);
$('#ocpc_id').val(val_id);
$('#textval').val(vals);
$('#merge').hide();
$('#addNew').show();
}
i want to get the attribute of the checkbox named checkval[]. I want to get what's inside the attr array. I hope you could help me guys.
Try this
document.getElementById('btn').addEventListener('click',function(){
var checkboxes = document.getElementsByName('checkval[]');
var input = document.getElementsByName('ocid[]');
var checkval = '';
var checkid = '';
for(var i=0;i<checkboxes.length;i++) {
if(checkboxes[i].checked){
i==0 ? checkval += checkboxes[i].value : checkval += ","+checkboxes[i].value;
i==0 ? checkid += input[i].value : checkid += ","+input[i].value;
}
}
console.log(checkval+" "+checkid);
});
See the demo
var val_id = "";
for (var l=0, n=cd.length;l<n;l++)
{
if (cd[l].checked)
{
val_id += ","+cd[l].getAttribute("attr");
}
}
if (val_id) val_id = val_id.substring(1);
I've change val_id += ","+cd[l].attr; to val_id += ","+cd[l].getAttribute("attr");
Thanks for your time guys.

Sort multiple categorys by values with AJAX

I am trying to sort data that pulls with an ajax get request, how do i get all the checked categories instead of only the one pressed, would be nice to get both 2/3 if both are checked?
Currently I insert a number in the database under "kategori" and they should be sorted through these numbers?
how do i get both queries in the url?
Example here : http://xch07.wi2.sde.dk/sandbox/SQL/
HTML
<form>
<input class="kategorier" type="checkbox" value="1">Kat 1<br>
<input class="kategorier" type="checkbox" value="2">Kat 2 <br>
<input class="kategorier" type="checkbox" value="3">Kat 3
</form>
<br>
<div id="txtHint">Person info will be listed here...
</div>
JS/AJAX
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(let i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
showUser(this.value);
});
};
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","index.php?page=getuser&kategori="+str ,true);
xmlhttp.send();
}
}
PHP
$kategori = intval($_GET['kategori']);
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori = $kategori ";
$result = $dbCon->query($sql);
echo "<table>
<tr>
<th>Id</th>
<th>Navn</th>
<th>Efternavn</th>
<th>email</th>
<th>Kategori</th>
</tr>";
while($row = $result->fetch_object()) {
$id = $row->id;
$navn = $row->navn;
$efternavn = $row->efternavn;
$email = $row->email;
$kategori = $row->kategori;
echo "<tr>";
echo "<td>" . $id . "</td>";
echo "<td>" . $navn . "</td>";
echo "<td>" . $efternavn . "</td>";
echo "<td>" . $email . "</td>";
echo "<td>" . $kategori . "</td>";
echo "</tr>";
}
echo "</table>";
<script type="text/javascript">
window.onload = function () {
var kategorier = document.getElementsByClassName("kategorier");
var kategorierLength = kategorier.length;
for(var i=0; i < kategorierLength ;i++){
kategorier[i].addEventListener('click', function(){
var checked = '';
for (var k = 0; k < kategorierLength; k++) {
if (checked) {
var separator = ',';
} else {
var separator = '';
}
if (kategorier[k].checked) {
checked += separator+kategorier[k].value;
}
}
alert(checked);
if (checked) {
showUser(checked);
}
});
}
}
After that you need to change your query and use IN statement like below.
$kategori = $_GET['kategori'];
mysqli_select_db($dbCon,"ajax_demo");
$sql="SELECT * FROM db_test WHERE kategori IN ($kategori)";
$result = $dbCon->query($sql);

How to get $_POST working with my editable jquery table?

I have this editable html table that I've got working, so you can click the cells and edit the text, however I can't get it to post the values as well.
I know there's a problem with the 5 lines of code under the comment on script.js
test.php
<h2><u>Edit</u></h2>
<form action="ajax/name.php" name="edit_template_form" id="edit_template_form" method="post">
<?php print "<table border=\"1\" class=\"editableTable\">
<tr>
<th>Template Name</th>
<th>Template Description</th>
</tr>";
foreach($res as $row){
$temp_description = $row['template_description'];
echo "<tr>";
echo "<td id=\"edit_name\" name=\"edit_name\">". $row['template_name']. "</td>";
echo "<td id=\"edit_template\" name=\"edit_template\">". nl2br($temp_description). "</td>";
echo "<tr/>";
}
print "</table>"; ?>
</form>
<div id="template_edit"></div>
name.php
if (isset($_POST['edit_template'])) {
$template_edit = $db->escape($_POST['edit_template']);
$user = $db->escape($user);
$db->update('templates', array('template_description' => $template_edit), 'AND userID="'.$user.'"');
echo $_POST['edit_template'];
}
if (isset($_POST['edit_name'])) {
$template_name = $db->escape($_POST['edit_name']);
$user = $db->escape($user);
$db->update('templates', array('template_name' => $template_name), 'AND userID="'.$user.'"');
echo $_POST['edit_name'];
}
script.js
$(function () {
$("td").dblclick(function () {
var OriginalContent = $(this).text();
$(this).addClass("cellEditing");
$(this).html("<input type='text' value='" + OriginalContent + "' />");
$(this).children().first().focus();
$(this).children().first().keypress(function (e) {
if (e.which == 13) {
//POST values
var edit_template = $('#edit_template').val();
var edit_name = $('#edit_name').val();
$.post('ajax/name.php', {edit_name: edit_name, edit_template: edit_template}, function(data) {
$('div#template_edit').text(data);
});
var newContent = $(this).val();
$(this).parent().text(newContent);
$(this).parent().removeClass("cellEditing");
}
});
$(this).children().first().blur(function(){
$(this).parent().text(OriginalContent);
$(this).parent().removeClass("cellEditing");
});
});
});

Categories