Get content of an element contains a string and select it - javascript

I'm looking for a way to search for a string in a table rows by jquery and get all of that contents and select the element that have it to get the other pieces!
here is the html side:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Tel</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$allcontacts=$contact->getallcontacts("name",$_SESSION['username']);
if($allcontacts!=null)
foreach($allcontacts as $value){
?>
<tr>
<td class="contact-id">
<?php echo $value[0]; ?>
</td>
<td class="contact-name">
<?php echo $value[1]; ?>
</td>
<td class="contact-tell">
<?php echo $value[2]; ?>
</td>
<td class="contact-info">
<?php echo $value[3]; ?>
</td>
<td class="td-actions">
<a href="?IDD=<?php echo $value[0]." &owner=".$_SESSION['username'];?>">
<i class="glyphicon glyphicon-trash"></i>
</a>
<a href="#" class="eb" data-uid="<?php echo $value[0]; ?>" data-toggle="modal" data-target=".bs-example-modal-lg">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a href="#" onclick="" class="se">
<i class="glyphicon glyphicon-envelope"></i>
</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<input type="text" class="cs" /><input type="button" value="Search" class="csb"/>
here is the script side!
$(".csb").click(
function() {
var ss = $(".cs").val();
var farray = $("td:contains(ss)").toArray();
console.log(farray);
}
);
console gets me an empty array!

ok ive tried ur code, obiously without php, so i put plain info. maybe this will help u
$(".csb").click(function(){
var ss = $(".cs").val();
var farray = new Array(); //define array
$("tr").removeAttr("style"); //reset all
if(ss!=""){ //check if isnt empty
$("td:contains("+ss+")").each(function(){
$(this).parent().css("background","red"); //select found
//push to array
farray.push($(this).parent().find(".contact-id").html());
farray.push($(this).parent().find(".contact-name").html());
farray.push($(this).parent().find(".contact-tell").html());
farray.push($(this).parent().find(".contact-info").html());
});
}
else{
alert("put a text");
}
//result
$("code").html("value search: "+ss);
$("pre").html("id found: "+farray[0]+"<br>"+
"name found: "+farray[1]+"<br>"+
"tel found: "+farray[2]+"<br>"+
"info found: "+farray[3]);
});
this is the full code: https://jsfiddle.net/keejke5e/3/

You don't need to add .toArray() as $("td:contains(ss)") returns array. I think you need to check whether you getting $("td") element or not. As for I see, according to your code it should find it. So just check $("td") and $("td:contains(ss)") in your chrome console.

Related

show/hide icons in div in table row using jquery

I have a table, its is data displayed using foreach. one column have 3 icons, by default they are hidden. And also have checkbox. icons and checkbox are in every row. Now when select any checkbox, icons of all rows are appearing. Instead I want only one row icons should be displayed on selecting checkbox. Can somebody help please. thanks in advance. here is the code.
in view
<?php $sn= $this->uri->segment(4); foreach($companies as $company){ $sn++;?>
<tr class="parent" style="font-size:11px;color:#3D4061;border-bottom:1px solid #3d406136">
<td><input type="checkbox" class="text-center check_data mt-2" onchange="changevalue()"></td>
<td class="text-center" style=""><h6><?php echo $sn; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->company_name; ?></h6></td>
<td class="text-center" style=""><h6><?php echo $company->contact_no; ?></h6></td>
<?php if($company->activation_status == 1){?>
<td class="text-center" style=""><h6 class="text-success font-weight-bold" style="font-size:13px">Active</h6></td>
<?php } ?>
<?php if($company->activation_status == 0){?>
<td class="text-center" style=""><h6 class="text-danger font-weight-bold" style="font-size:13px">Inactive</h6></td>
<?php } ?>
<td class="text-center" style="">
<div class="status">
<i class="fa fa-edit"></i>
<?php if($company->activation_status == 0){?>
<i class="fa fa-dot-circle-o"></i>
<?php }else{ ?>
<i class="fa fa-exclamation-triangle"></i>
<?php } ?>
<i class="fa fa-trash-alt"></i>
</div>
</td>
<td ><i class="fa fa-chevron-down down" ></i></td>
</tr>
and script is
<script>
$('.status').hide();
function changevalue(){
if($(".check_data").is(":checked"))
$('.status').show();
else
$(".status").hide();
$('.cchild').hide();
}
</script>
you can also use .parent() and .find() methods to get specific row like that:
<input type="checkbox" function="changevalue(this)">
and your javacript must be like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parent().parent().find('.status').show();
else
$(elem).parent().parent().find('.status').hide();
}
This code can be simplified but it's a good starting example to understand parent-child usage of html elements. At this example first .parent() goes to <td> of checkbox element and second .parent() goes to <tr> element then it searches for .status class in it then hides it.
and you can simplfy it like that:
function changevalue(elem){
if($(elem).is(":checked"))
$(elem).parents("tr").find('.status').show();
else
$(elem).parents("tr").find('.status').hide();
}
function changevalue() {
var $this = $(this),
$status = $this.parents("tr").find(".status");
if ($this.is(":checked")) {
$status.show();
} else {
$status.hide();
}
}
You can give dynamic Ids to every checkbox and status div. Use your record's id may be companyId to create Ids like
<input type="checkbox" id="checkbox_('<?php echo $company->id; ?>')>
I don't know the syntax for php.
and then you can pass the current companyId in onchange="changevalue(companyId)"
and then your code will be like this
function changevalue(companyId){
if($("#checkbox" + companyId).is(":checked"))
$('#status' + companyId).show();
else
$("#status" + companyId).hide();
}

table pagination without reload the page -Bootstrap-

I have a table fetching its data from database
I want to make pagination for table but without refreshing the page
my table code:
<?php
<table id="table2" class="table table-hover table-mc-light-blue ">
<thead>
<tr>
<th>#</th>
<th>اسم المطرب</th>
<th>عدد الاغاني</th>
<th>تعديل</th>
</tr>
</thead>
<tbody class="searchable" >
<?php
$artistquery= mysqli_query($conn,"SELECT * FROM `artist` ORDER BY `artistID` DESC ");
$num=1;
$x=0;
while($listartist = mysqli_fetch_assoc($artistquery)){
$songquery= mysqli_query($conn,"SELECT * FROM `songs` WHERE `artist` = '$listartist[artistname]' ");
$songsnumber = mysqli_num_rows($songquery);
$x+=0.1;
echo'
<tr class="animated bounceIn " style=" animation-delay:'.$x.'s;">
<td data-title="#"></td>
<td data-title="اسم المطرب"></td>
<td data-title="عدد الاغاني"></td>
<td data-title=""></td>
</tr> ';}
?>
NOTE: I tried DataTables.js but i did know how to remove the filter and show labels.
is there any different way to do it ?
I dont fully comprehend your query so I'll stick to the pagination. Lets Say you want to show 10 items at a time and you are using next and prev as pagination buttons, you can render the first view using LIMIT 10 in your query or using array_slice($mysql_result,0,10). I have this downloaded json files containing zips (countries and code), that is what I used to test it. the next and prev totally perfect but it works.
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<?php
$mysql_result = (array) json_decode(file_get_contents('zips'));
if(isset($_GET['ajax'])){
header('content-type: application/json');
$_GET['offset'] = isset($_GET['offset'])?$_GET['offset']:0;
echo json_encode(array_slice($mysql_result,$_GET['offset'],10));
exit;
}
$ar = array_slice($mysql_result,0,10);//or add LIMIT 10 in sql query
?>
<table border="on" width="100%">
<tbody id="songartiststuff">
<?php foreach($ar as $k => $r)://initial render?>
<tr>
<td data-replace="code"><?=$r->code?></td>
<td data-replace="country"><?=$r->country?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<center>
<button data-next="10">Next</button>
<button data-prev="0">Prev</button>
</center>
<script src="jquery.js"></script>
<script>
$(()=>{
document.querySelector('[data-next]').addEventListener('click',function(){
move(this.dataset.next);
console.log(this.dataset.next);
this.setAttribute('data-next',parseInt(this.dataset.next) + 10);//add to next
var prv = document.querySelector('[data-prev]');
prv.setAttribute('data-prev',parseInt(prv.dataset.prev) + 10);//add to prev
})
document.querySelector('[data-prev]').addEventListener('click',function(){
move(this.dataset.prev);
console.log(this.dataset.prev);
this.setAttribute('data-prev',parseInt(this.dataset.prev) - 10);// remove form next
var nxt = document.querySelector('[data-next]');
nxt.setAttribute('data-next',parseInt(nxt.dataset.next) - 10);//remove from prev
})
function move(int){
var template = document.querySelector('tbody tr').cloneNode(true);//get a sample from tbody
$.get('table.php?ajax=true&offset='+int).success(function(data){
$(document.querySelector('tbody')).empty();
$.each(data,function(i,v){
let tp = tmp.cloneNode(true);//clone the template
tp.querySelector("[data-replace='code']").innerHTML = v.code;//replace code
tp.querySelector("[data-replace='country']").innerHTML = v.country;//replace country
document.querySelector('tbody').appendChild(tp);//append to tbody
})
});
}
});
</script>

Get clicked href variable from one page to another

Greeting everyone,
Currently i'm making a webpage that has the following functions:
When the administrator opens the page, admin will be seeing a form filled with these information from a database:
What this page does is that it shows how many video's each user has in the database and when the admin clicks on the desired user ID, a new page should open with the video's of that specific user ID. The " DONE" button is to return to the main page when the admin is done deleting video's.
Now, what I have done is that I've assigned an href link to the userID values that is being fetched from Database. The problem is that, I have no clue how to pass the selected value/string to the next page with href. I've tried with Session, but ended up getting the last variable processed in the WHILE loop instead of getting the clicked UserID. Below follows my php code of what I've done. Can anyone give me some tips on how to pass the clicked userID from one page to another with href, or is there another way to do this?
code= click here
ps: As everyone can see, my php coding needs some serious improvement. But i'm still trying to improve by doing these types of exercises.
<?php
include_once ("includes/db_connection.php");
$sql = "SELECT Users_UserID, count(Users_UserID) AS total FROM video GROUP BY Users_UserID";
$sql2="SELECT UserID, FirstName, LastName FROM users";
$result = $connection->query($sql);
$result2 = $connection->query($sql2);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="deleteSingleVideo" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete user video</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>First Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Last Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>User ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Amount of videos</strong></td>
</tr>
<?php
session_start();
if ($result->num_rows > 0) {
while (($row=$result->fetch_assoc())&& ($row2=$result2->fetch_assoc()) ) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF"></td>
<td bgcolor="#FFFFFF"><center><?php echo $row2['FirstName']; ?></center></td>
<td bgcolor="#FFFFFF"><?php echo $row2['LastName']; ?></td>
<td bgcolor="#FFFFFF"><center><a href="DeleteVideo.php" target="_blank"><?php echo $row['Users_UserID'];
$_SESSION['id']=$row['id'] ?></center></td>
<td bgcolor="#FFFFFF"><center><?php echo $row['total'];?></a></center></td>
</tr>
<?php
}
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="Done" type="submit" id="Done" value="Done" </td>
</tr>
<?php
$connection->close();
if(isset($_POST['Done'])){
header( "Location: Home.php" );
}
?>
</table>
</form>
</td>
</tr>
</table>
<?php
?>
this is not a good use of session
use get method to send such data :
append the id to href url --->href="<?php echo "DeleteVideo.php?id="$row['id'] ?>";
get data in the next page by accessing global variable ---> $_GET['id']
..
In the DeleteVideo.php your variable is $_GET['id']
use this code
and that id value get in xyz.php
$value=$_request['id'];
or
$value=$_Get['id'];

save link assign value as well as go to other page

I have a table where user can add data in it and I also have input field and save link. In my save link, if I click it.. I assign value to input field before it will go to other page. But when it go to the other page and I echo the value of inputfield, I got empty as in null value.
here's my code:
for table:
<table class="table " id="memberTB">
<thead>
<tr>
<th >First Name</th>
<th >Middle Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr id="first">
<td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td>
</tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow">
<span class="fa fa-plus"> Add new row</span>
</button>
</table>
<input type="text" name="list" id="list"/>
<br>
<a class="btn" id="savebtn">Save</button>
Reset
and for js:
$('#savebtn').click(function() {
var cells = 3; //number of collumns
var arraylist = []
var x=0;
$('tbody tr',$('#memberTB')).each(function(){
var cell_text = '';
for(var i = 0 ; i < cells ; i++){
if(i==2){
cell_text =cell_text+$(this).find('td').eq(i).text()+":";
}else{
cell_text =cell_text+$(this).find('td').eq(i).text()+",";
}
}
arraylist.push(cell_text);
});
document.getElementById("list").value =arraylist;
document.getElementById("savebtn").href="<?php echo site_url('test/save');?>";
}
I got nothing when I echo it in the test.php in the save(), like this:
echo $this->input->post('list');
You are simply redirecting the page. So you will not get any value from post. If you want to get the value by post method you need to submit the value with a form.
<form id='save_form' method="post" action="<?php echo site_url('test/save');?>">
//add your html codes
//<table ..... and others
<a class="btn" href="#" id="savebtn">Save</button> //add # to href for save button
</form>
Now your js
$('#savebtn').click(function() {
//js codes that you wrote
//just replace the following line
//document.getElementById("savebtn").href="<?php echo site_url('test/save');?>";
$('#save_form').submit();
}

img by changing it's src and is drawn by a dynamically provided source (mysql and php) with a Javascript

I have these scripts:
<?
/*//Disable error reporting
error_reporting(0);
*/
//Report runtime errors
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
//Report all errors
error_reporting(E_ALL);
//end of error reporting
?>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('select').on('change', function(e){
var selected_value = $(this).val();
var option_data = $(this).children('option[value="'+selected_value+'"]');
// get data values
var visanumber = option_data.data('visanumber');
var idnumber = option_data.data('idnumber');
var statusapp = option_data.data('statusapp');
var subdate = option_data.data('subdate');
// the photo
var accntvisaphotopath = option_data.data('accntvisaphotopath');
if(accntvisaphotopath == 'data-passport=') {
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', 'accntvisaphotopath');
$(this).closest('td').siblings().find('img.passportPath').attr('src', 'passportpath');
} else {
$(this).closest('td').siblings().find('img.passportPath').attr('src', 'passportpath');
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', 'accntvisaphotopath');
}
// set the values
$(this).closest('td').siblings().find('span.visanumber').text(visanumber);
$(this).closest('td').siblings().find('span.idnumber').text(idnumber);
$(this).closest('td').siblings().find('span.statusapp').text(statusapp);
$(this).closest('td').siblings().find('span.subdate').text(subdate);
});
</script>
</head>
<body>
<?
$con=mysqli_connect("localhost","xxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM visa ORDER BY idvisa");
?>
<div align="center">
<form name="contractInfo" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
<table border="1px" width="700">
<tr>
<td align="center" colspan="7"><b>Email:</b><input name="email" type="text" id="email"></td>
</tr>
<tr>
<th> <div align="center"> Applicant Name </div></th>
<th> <div align="center">Visa Number</div></th>
<th> <div align="center">ID Number </div></th>
<th> <div align="center">Employment Status</div></th>
<th> <div align="center"> Visa </div></th>
<th> <div align="center"> Passport </div></th>
<th> <div align="center"><font color="red">Elapse</div></th>
</tr>
<tr>
<td>
<select>
<? echo "<option value=\"\">Select Person:</option>";?><br>
<? while ($row=mysqli_fetch_array($result)) {
echo "<option value=".$row['idvisa']." data-visanumber=".$row['visanumber']." data-idnumber=".$row['idnumber']." data-statusapp='{$row['statusapp']}' data-accntVisaPhotoPath=".$row['accntVisaPhotoPath']." data-passport=".$row['passportPath']." data-subdate='{$row['subdate']}'>".$row['fName']." ".$row['lName']."</option>";
}
?>
</select>
<?//Additional var
//Time
$today = date("Y/m/d G:i:s");
$date= $row["subdate"];
$days = strtotime($today) - strtotime($date);
//End Time
?>
</td>
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
<td><span class="subdate"></span></td>
</span>
</tr>
<tr>
<td>
<select>
<?
mysqli_data_seek( $result, 0 );
echo "<option value=\"\">Select Person:</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value=".$row['idvisa']." data-visanumber=".$row['visanumber']." data-idnumber=".$row['idnumber']." data-statusapp='{$row['statusapp']}' data-accntVisaPhotoPath=".$row['accntVisaPhotoPath']." data-passport=".$row['passportPath']." data-subdate='{$row['subdate']}'>".$row['fName']." ".$row['lName']."</option>";
}
?>
</td>
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
<td><span class="subdate"></span></td>
</span>
</tr>
</table>
<br><br>
<input type="button" name="cancelvalue" value="CANCEL" onClick="self.close()">
<input name="reset" type="reset" value="Clear" height="14">
<input name="submit" type="submit" value="Send" height="14">
<br><br>
</form>
</body>
</html>
and may aim is to change it's src
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
I have tried to search in here but it seems I am too dumb in revising what I have found. I know, it is simple but I am new in handling custom data attributes and then have the Javascript populate it all BUT the image has caught me unprepared.
And my L A B is here.
I suggest use classes in this case, don't use ID because it will have multiple rows.
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></td>
<td align="center"><img class="passport" height="50" width="50"></td>
<td><span class="subdate"></span></td>
Then, just target that option based on the value you selected. Then extract those data attributes values according to selection.
<script type="text/javascript">
$(document).ready(function(){
$('select').on('change', function(e){
var selected_value = $(this).val();
var option_data = $(this).children('option[value="'+selected_value+'"]');
// get data values
var visanumber = option_data.data('visanumber');
var idnumber = option_data.data('idnumber');
var statusapp = option_data.data('statusapp');
var subdate = option_data.data('subdate');
// the photo
var accntVisaPhotoPath = option_data.data('accntvisaphotopath');
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', accntVisaPhotoPath);
var passportPath = option_data.data('passportpath');
$(this).closest('td').siblings().find('img.passportPath').attr('src', passportPath);
// set the values
$(this).closest('td').siblings().find('span.visanumber').text(visanumber);
$(this).closest('td').siblings().find('span.idnumber').text(idnumber);
$(this).closest('td').siblings().find('span.statusapp').text(statusapp);
$(this).closest('td').siblings().find('span.subdate').text(subdate);
});
});
</script>
Of course the path of the images is up to you since no PHP codes are found in your question, this is just an example.
Here is a working demo:
http://codepad.viper-7.com/GhH6Yh
thanks
Your get Image Path should return a image to show up, try this:
function getImagePath(){
return "https://www.google.com/images/srpr/logo11w.png";
}
Now, you need to add parameter to getImagePath function and and the functions should return the appropriate image url.

Categories

Resources