This script works fine in IE & FF not in safari 5. It appears not to intialize (ie nothing works). The Script will display one row of the table at a time hiding the others until next or previous is clicked. Original can be viewed on halifaxhype.com If anyone can make a suggestion I would appreciate it as I am not normally working with java script or Jquery or Safari. (java script followed by HTML below - due to posting restrictions anchor links and image links removed from the html)
JS - initial
$(document).ready(function () {
$('#myTable').paginateTable({ rowsPerPage: 1 });
});
JS - main
(function ($) {
$.fn.paginateTable = function(options) {
var settings = jQuery.extend({
rowsPerPage: 1, /* the number of rows that comprise a page */
nextPage: ".nextPage", /* selector for "Next Page" dom element. Click to change page. */
prevPage: ".prevPage", /* selector for "Previous Page" dom element. Click to change page. */
currentPage: ".currentPage", /* selector for "Current Page" dom element. Display only. */
totalPages: ".totalPages", /* selector for "Total Pages" dom element. Display only. */
pageNumbers: ".pageNumbers", /* selector for container for autogenerated page number links */
pager: ".pager",
pagernext: ".pagernext",
pagerprev: ".pagerprev", /* selector for container of all paging dom elements */
autoHidePager: true /* hides the pager (see selector above) if there is only a single page */
}, options || {});
return this.each(function(){
var table = $(this);
var pager = $(settings.pager);
var pagernext = $(settings.pagernext);
var pagerprev = $(settings.pagerprev);
var nextPage = pagernext.find(settings.nextPage);
var prevPage = pagerprev.find(settings.prevPage);
var currentPage = pager.find(settings.currentPage);
nextPage.click(function(){
var pageNum = getCurrentPage(currentPage.text());
displayPage(table, pageNum+1, settings);
return false;
});
prevPage.click(function(){
var pageNum = getCurrentPage(currentPage.text());
displayPage(table, pageNum-1, settings);
return false;
});
displayPage(table, getCurrentPage(currentPage.text()), settings);
});
};
function getCurrentPage(pageText){
var pageNum = parseInt(pageText,10);
if (isNaN(pageNum)){
pageNum = 0;
}
return Math.max(1, pageNum);
}
function displayPage(table, pageNum, settings){
pageNum = Math.max(1, pageNum);
if (settings.rowsPerPage > 0){
var rows = table.find("tbody tr");
var totalPages = Math.ceil(rows.size() / settings.rowsPerPage);
if (pageNum <= 1){
$(settings.pagerprev).hide();
}
if (pageNum > 1){
$(settings.pagerprev).show();
}
if (pageNum >= totalPages){
$(settings.pagernext).hide();
}
if (pageNum < totalPages){
$(settings.pagernext).show();
}
if (settings.autoHidePager && totalPages <= 1){
$(settings.pager).hide();
}
else if (totalPages > 0){
pageNum = Math.min(pageNum, totalPages);
var rowStartIndex = (pageNum - 1) * settings.rowsPerPage;
var rowEndIndex = pageNum * settings.rowsPerPage;
$.each(rows, function(index, row){
if (index >= rowStartIndex && index < rowEndIndex){
$(row).show();
}
else{
$(row).hide();
}
});
var pager = $(settings.pager);
pager.find(settings.currentPage).text(pageNum);
pager.find(settings.totalPages).text(totalPages);
var pageNumbers = pager.find(settings.pageNumbers);
if (pageNumbers.size() > 0){
pageNumbers.empty();
for(var i = 1; i <= totalPages; i++) {
pageNumbers.append("<a href='#' id='" + i + "'>" + i + "</a>");
}
pageNumbers.children('a').click(function(){
displayPage(table, $(this).attr("id"), settings);
return false;
});
}
}
}
}
})(jQuery);
HTML
<!-- Main Body (middle) -->
<table><tr>
<td style='padding-left: 0px; padding-right: 0px; height: 275px; ; width: 666px;' >
<!-- Table to Contain 1-Prev, 2-Events, 3-Next -->
<table border=0 bordercolor=orange width='100%' cellpadding='0' cellspacing='0'><tr>
<!-- 1-Prev -->
<td width='25' valign='middle' align='center'> <div class='pagerprev'>
<a href='#' alt='Previous' class='prevPage'> <PREV image link removed</div> </td>
<!-- 2-Events -->
<td>
<!-- Table for Events This is what Slides in and out-->
<table id="myTable" border=0 bordercolor=red width=100%><tbody>
<!--- Event loop#1 Event ID#52 --->
<tr><td style='padding-left: 15px; padding-right: 15px;' valign='top' width='508'><div class='eslider' align='left' style='float: left; width=200'>image</div><div id='eslider' align='right' style='float: right;width=300'><span style='font-family: Verdana; color: #ffffff; font-size: 23px; font-weight: bold;'>Bitter End</span><br><span style='font-family: Verdana; color: #D4D4D4; font-size: 18px;'>Martini Monday at The Bitter End!</span> <hr height='1' width='100%'><span style='font-family: Verdana; color: #D4D4D4; font-size: 12px;'> <p>Absolutely the best place to be on a Monday night in Halifax! Featuring a discounted martini menu and DJ Nigel Lutes. Disc<br><br>Mon, Jan 31, 2011 - All Day </div> </center></td></tr>
<!--end event-->
<!--- Event loop#2 Event ID#95 --->
<tr><td style='padding-left: 15px; padding-right: 15px;' valign='top' width='508'><div class='eslider' align='left' style='float: left; width=200'>image</div><div id='eslider' align='right' style='float: right;width=300'><span style='font-family: Verdana; color: #ffffff; font-size: 23px; font-weight: bold;'>Mexicali Rosa's</span><br><span style='font-family: Verdana; color: #D4D4D4; font-size: 18px;'>Double Margaritas! Only $6.00!</span> <hr height='1' width='100%'><span style='font-family: Verdana; color: #D4D4D4; font-size: 12px;'> <p>Every Monday!<br />- Double Margaritas! Only $6.00! (Taxes in)<br />- 32 oz. Canadian or Coors Light Draught - $8.99</p>
<br><br>Mon, Jan 31, 2011 - All Day </div> </center></td></tr>
<!--end event-->
<!--- Event loop#3 Event ID#54 --->
<tr><td style='padding-left: 15px; padding-right: 15px;' valign='top' width='508'><div class='eslider' align='left' style='float: left; width=200'>image</div><div id='eslider' align='right' style='float: right;width=300'><span style='font-family: Verdana; color: #ffffff; font-size: 23px; font-weight: bold;'>Economy Shoe Shop</span><br><span style='font-family: Verdana; color: #D4D4D4; font-size: 18px;'>Homemade Lasagna & House Salad only $9.00!</span> <hr height='1' width='100%'><span style='font-family: Verdana; color: #D4D4D4; font-size: 12px;'> Hungry? Stop by The Economy Shoe Shop for our "Feature Of The Day"! Only $9.00 all day long! Monday's Feature Of The Day: We<br><br>Mon, Jan 31, 2011 - 08:00</div> </center></td></tr>
<!--end event-->
<tbody>
</table>
<!-- END Table for Events -->
</td>
<!-- 3-Next -->
<td width='25' valign='middle' align='center'><div class='pagernext'>next link removed</div> </td>
</tr>
<tr valign="top"><td colspan="3" height="33" align='center'>
<div class='pager'>
<!-- bottom stuff to view events and profile more neatly this could be removed if <Div> code could be fixed see above -->
View Profile
Click Here For More Detailsbr><br>
<!-- End of bottom stuff to veiw events and profile more neatly-->
<font color='#ffffff' size='5'>
<span class='currentPage' ></span></font>
<font color='#ffffff' size='2'> of </font>
<font color='#ffffff' size='5'><span class='totalPages'></span></font>
</div>
</td></tr>
<!-- END Main Body (middle) -->
</table>
Your HTML is very broken. Validate your HTML first, then try again. I have attempted to reproduce your problem here, but see no problems with Safari.
Related
I have a tal template that draws a table, but the function that shows a cell header when hovering doesn't work.
This is my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div class="container"><input class="form-control" id="multi_host_filter" type="text" placeholder="Filter"></div>
<div class="container" tal:repeat="machine_result item.items()">
<button class="btn btn-info btn-sm btn-block btn-expand" type="button" data-toggle="collapse" data-target="#${machine_result[0]}_div" aria-expanded="false" aria-controls="${machine_result[0]}_div" tal:content="machine_result[0]"/>
<div class="collapse container" id="${machine_result[0]}_div">
<table class="table table-hover table-sm table-responsive table-bordered">
<tr tal:repeat="tuple machine_result[1].get('return')">
<th tal:condition="repeat['tuple'].index==0" tal:repeat="data tuple.split(';;')" tal:content="data"/>
<td class="td-hover" tal:condition="repeat['tuple'].index!=0" tal:repeat="data tuple.split(';;')" tal:content="data"/>
</tr>
</table>
</div>
</div>
</div>
<script>
$(document).ready(function(){
$("#multi_host_filter").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("table tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
$("td").on({
mouseenter: function(e){
var $cell = $(this);
var headerVal = $cell.closest("table").find("tr > th").eq($cell.index()).html();
var paragraph = '<p>' + headerVal + '</p>';
$('#floating_div').html(paragraph);
$('#floating-div').stop(true);
$('#floating_div').css({left: e.pageX, top: e.pageY});
$('#floating_div').width(150);
$('#floating_div').css('z-index', 4000);
$('#floating_div').height(40);
},
mouseleave: function(e){
$('#floating_div').css('z-index', -4000);
$('#floating-div').css('display', 'none');
},
});
</script>
I have already tried $('table').hover(function(){//something}
, function(){//something when leave}) but div is not hidden when i leave table
"#floating-div" is already created at index.html, and i can modify it from this script
Any idea?
When looking over your code, for the most part it seems to be exactly what you are trying to accomplish -- the table was a bit wonky in how it was formatted ( open and close THs and TDs <th>...</th> and <td>...</td> -- but I'm also not familiar with tal templates ).
But reducing your code to the minimums and reusing a lot of it, I generated the below solution.
The only other real edit is that I added in a mouseleave() event on the #floating_div, populating the div immediately underneath the cursor can cause cursor-confusion. Where it thought it was sitting on top of a <td> it is now suddenly sitting on top of a #floating_div. So, "leaving" the <td> doesn't work. This is because the cursor is now on top of something else and will leave that.
$("td").on({
mouseenter: function(e){
//console.log( 'in', this );
let output = $(this).closest("table").find("tr > th").eq($(this).index()).html();
$('#floating_div').html( output );
$('#floating_div').removeClass('hidden');
$('#floating_div').css({left: e.pageX, top: e.pageY});
},
mouseleave: function(e){
//console.log( 'out', this );
$('#floating_div').addClass('hidden');
},
});
$('#floating_div').mouseleave( function(){
$(this).addClass('hidden');
});
*{ margin: 0; padding: 0; font-family: Arial, sans-serif; }
table, td, th{ padding: 5px; border: solid 1px rgba( 0, 0, 0, 0.25); }
#floating_div{
position: absolute;
top: 0;
left: 0;
padding: 15px;
display: block;
background-color: rebeccapurple;
color: white;
pointer-events: none;
}
#floating_div.hidden{
display: none;
top: -1000px;
left: -1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>header 1</th>
<th>header 2</th>
</tr>
<tr>
<td>data 1</td>
<td>data 2</td>
</tr>
</table>
<div id="floating_div" class="hidden"></div>
I'm using Selenium and Chrome to write a script. I'm having trouble getting Selenium to select and click on two elements. Here's the element I'm trying to select:
HTML of Element 1:
<td class="menuItem" id="tWlans" style=""><a href="frameWlan.html"
id="cWlans" accesskey="W" onmouseover="highlight('Wlans')"
onmouseout="removeHighlight('Wlans')" onclick="selectTab('Wlans')"
onfocus="highlight('Wlans')" onblur="removeHighlight('Wlans')"
target="mainFrame"><u>W</u>LANs</a></td>
HTML of Element 2:
<td class="listNoPad">
<input type="TEXT" name="1.6.7.wlan_id" class="statictextboxlink"
onclick="editThisWlan(this.value,this.name)" readonly="" size="7" value="7">
</td>
I've tried selecting the element by id and by XPath, neither of which works.
function siteNavigate() {
sleep(4500);
driver.findElement(By.xpath('//*[#id="cWlans"]')).click();
//driver.findElement(By.id('cWlans')).click();
}
Thanks in advance for any help and suggestions.
Edit:
function helpAction(pageId, startpage) {
var baseHref = window.location.href;
var index = baseHref.indexOf("/screens");
baseHref = baseHref.substring(0, index);
var href = "/helpfiles/oweb/index.html";
var editWindow = window.open(baseHref + href, "editWindow", "left=100 top=50 menubar=no,toolbar=yes,width=800,height=600,status=yes,resizable=yes");
if (navigator.appName != "Netscape") {
editWindow.location.href = baseHref + href;
editWindow.location.reload(true);
}
editWindow.focus();
}
function feedbackAction() {
var URL = 'http://www.cisco.com/go/wireless-feedback';
var feedbackWindow = window.open(URL, "FeedbackWindow", "left=100 top=50 menubar=no,toolbar=no,scrollbars=yes,titlebar=yes,width=800,height=800,status=yes,resizable=yes");
feedbackWindow.focus();
}
function selectTab(tabName) {
// All this function does is update the value of the hidden field and call the updatePage() function
// Obtain object reference to hidden field
var fieldObj = document.getElementById("hSelectedTab");
// Store the new tab selection in the hidden field
fieldObj.value = tabName;
updatePage();
}
function highlight(tabName) {
//remove highlight for all the tabs
removeHighlightAll();
var highlightObj = document.getElementById("t" + tabName);
// Only highlight if srcElement is a tab object.
highlightObj.style.backgroundColor = "#25546B";
}
function removeHighlight(tabName) {
var highlightObj = document.getElementById("t" + tabName);
highlightObj.style.backgroundColor = "";
}
function removeHighlightAll() {
document.getElementById("tMonitor").style.backgroundColor = "";
document.getElementById("tWlans").style.backgroundColor = "";
document.getElementById("tSwitch").style.backgroundColor = "";
document.getElementById("tWireless").style.backgroundColor = "";
document.getElementById("tSecurity").style.backgroundColor = "";
document.getElementById("tManagement").style.backgroundColor = "";
document.getElementById("tCommands").style.backgroundColor = "";
document.getElementById("tHelp").style.backgroundColor = "";
document.getElementById("tFeedback").style.backgroundColor = "";
}
function updatePage() {
// Clear the current tab selection
removeSelection();
// Obtain object reference to hidden field
var fieldObj = document.getElementById("hSelectedTab");
// Retrieve the selected tab
var selectedTab = fieldObj.value;
// Highlight the selected tab
cellObj = document.getElementById("t" + selectedTab);
cellObj.className = "selected";
}
function removeSelection() {
removeHighlightAll();
// Brute force method to clear the tab selection
document.getElementById("tMonitor").className = "menuItem";
document.getElementById("tWlans").className = "menuItem";
document.getElementById("tSwitch").className = "menuItem";
document.getElementById("tWireless").className = "menuItem";
document.getElementById("tSecurity").className = "menuItem";
document.getElementById("tManagement").className = "menuItem";
document.getElementById("tCommands").className = "menuItem";
document.getElementById("tHelp").className = "menuItem";
document.getElementById("tFeedback").className = "menuItem";
}
function DisplayMsgIfAny() {
if (document.forms[0].err_flag.value == 1) {
alert(document.forms[0].err_msg.value);
} else if (document.forms[0].result_flag.value == 1) {
alert(document.forms[0].cmd_result.value);
}
document.forms[0].err_flag.value = 0;
document.forms[0].result_flag.value = 0;
document.forms[0].buttonClicked.value = 0;
}
//need to get image for the OEMS and change the logo image.
function getLogoImage() {}
A {
TEXT-DECORATION: none
}
#home_icon {
height: 12px;
}
A:link {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A:hover {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A:active {
COLOR: #000000;
TEXT-DECORATION: none
}
A:visited {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A.command {
COLOR: #ffffff;
TEXT-DECORATION: none
}
A.command:hover {
COLOR: #ff9100;
TEXT-DECORATION: underline
}
P {
FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
TD {
FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif
}
P {
FONT-SIZE: 11px;
MARGIN: 0px;
COLOR: #333366
}
TD {
FONT-SIZE: 12px
}
TD.menuItem {
PADDING-RIGHT: 10px;
PADDING-LEFT: 10px;
PADDING-BOTTOM: 4px;
PADDING-TOP: 5px;
BORDER-BOTTOM: #000000 5px solid;
width: 1%;
white-space: nowrap;
}
TD.selected {
PADDING-RIGHT: 10px;
PADDING-LEFT: 10px;
PADDING-BOTTOM: 4px;
COLOR: #000000;
PADDING-TOP: 5px;
BORDER-BOTTOM: #ff9100 5px solid;
width: 1%;
white-space: nowrap;
}
TD.space {
WIDTH: 50%;
}
.style2 {
COLOR: #ffffff
}
<script language="JavaScript" src="../servicescript41.js"></script>
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="updatePage(); DisplayMsgIfAny();">
<table width="100%" height="53" border="0" cellpadding="0" cellspacing="0">
<tbody>
<tr>
<td style="PADDING-BOTTOM: 4px" align="middle" background="../images/background_web41.jpg" width="180">
<img src="../images/cisco/cisco-logo-2007.gif" width="67" height="40" alt="logo" />
</td>
<td valign="bottom" background="../images/background_web41.jpg">
<table border="0" cellspacing="0" cellpadding="0" width="100%">
<tbody>
<tr>
<td class="menuItem" id="tMonitor" style=""><u>M</u>ONITOR</td>
<td class="selected" id="tWlans" style=""><u>W</u>LANs</td>
<td class="menuItem" id="tSwitch" style=""><u>C</u>ONTROLLER</td>
<td class="menuItem" id="tWireless" style="">W<u>I</u>RELESS</td>
<td class="menuItem" id="tSecurity" style=""><u>S</u>ECURITY</td>
<td class="menuItem" id="tManagement" style="">M<u>A</u>NAGEMENT</td>
<td class="menuItem" id="tCommands" style="">C<u>O</u>MMANDS</td>
<td class="menuItem" id="tHelp">HE<u>L</u>P</td>
<td class="menuItem" id="tFeedback" style=""><u>F</u>EEDBACK</td>
<td class="space"> </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<div style="position:absolute; right:0px; top:0px; margin: 3px 10px 0px 0px">
<p>Sa<u>v</u>e Configuration | <u>P</u>ing | <a class="command" href="#" accesskey="g" onclick="javascript:logoutAction();">Lo<u>g</u>out</a> | <u>R</u>efresh</p>
</div>
<form method="post" action="/screens/banner.html">
<input type="hidden" name="access_control" size="16" maxlength="15" value="1">
<input name="hSelectedTab" type="hidden" id="hSelectedTab" value="Wlans">
<input type="hidden" name="err_flag" size="16" maxlength="15" value="0">
<input type="hidden" name="err_msg" size="512" maxlength="511" value="">
<input type="hidden" name="result_flag" size="16" maxlength="15" value="0">
<input type="hidden" name="cmd_result" size="512" maxlength="511" value="Config Saved">
<input type="hidden" name="ping_address" size="50" maxlength="50" value="">
<input type="hidden" name="interfaceType" size="11" maxlength="11" value="">
<input type="hidden" name="buttonClicked" size="16" maxlength="15" value="0">
</form>
</body>
Edit 2:
Error message from Node.js:
NoSuchElementError: no such element: Unable to locate element: {"method":"css selector","selector":"*[id="cWlans"]"}
(Session info: chrome=61.0.3163.100)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 10.0.15063 x86_64)
at WebDriverError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:27:5)
at NoSuchElementError (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:192:5)
at Object.checkLegacyResponse (C:\Selenium\node_modules\selenium-webdriver\lib\error.js:546:15)
at parseHttpResponse (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:509:13)
at doSend.then.response (C:\Selenium\node_modules\selenium-webdriver\lib\http.js:441:30)
at process._tickCallback (internal/process/next_tick.js:109:7)
From: Task: WebDriver.findElement(By(css selector, *[id="cWlans"]))
at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
at thenableWebDriverProxy.findElement (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:1014:17)
at siteNavigate (C:\Selenium\byot.js:29:8)
at sleep.then (C:\Selenium\byot.js:21:5)
From: Task: WebElement.click()
at thenableWebDriverProxy.schedule (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:807:17)
at WebElementPromise.schedule_ (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2010:25)
at WebElementPromise.click (C:\Selenium\node_modules\selenium-webdriver\lib\webdriver.js:2092:17)
at siteNavigate (C:\Selenium\byot.js:29:37)
at sleep.then (C:\Selenium\byot.js:21:5)
Ok, I apologize in advance. I didn't realize initially that the page had several iframes nested inside the page. To make a very long story short, the frames ended up being the problem the whole time. The site was set up with four frames, some of which changed depending on context and some that essentially stayed static after the initial login. The hardest part was knowing which frame to switch to, and keeping track of which context I was currently focused in on.
Here's what I ended up with:
const {Builder, By, until} = require('selenium-webdriver');
var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
driver.get('http://sitetonavigate.com');
driver.manage().window().maximize();
driver.findElement(By.name('bSubmit ')).click();
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
// Wait until Chrome is fully loaded to launch AutoIT login script
sleep(4500).then(() => {
autoIT();
});
function autoIT() {
var child_process = require('child_process');
var workerProcess = child_process.execFile("C:\\Selenium\\autoITscript.exe");
sleep(2500).then(() => {
siteNavigate();
});
}
function siteNavigate() {
driver.switchTo().frame("banner");
driver.findElement(By.id('cWlans')).click();
//Select correct WLAN
sleep(2500).then(() => {
driver.switchTo().defaultContent();
driver.switchTo().frame("mainFrame");
driver.switchTo().frame("content");
driver.findElement(By.xpath('/html/body/form/table[3]/tbody/tr[8]/td[2]/input')).click();
});
}
You can use:
Element1 :
driver.findElement(By.id('tWlans')).click();
Element2 :
driver.findElement(By.name('1.6.7.wlan_id')).click();
You are clicking on the TD because it has the ID, tWlans. You (presumably) want to click on the A tag contained within. I would suggest the CSS selector, #tWlans > a. The code is below. I added a wait but it may or may not be needed.
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#tWlans > a"))).click();
As for the second element, it wasn't in your full HTML posted so I'm not sure if it's unique but you can try these couple CSS selectors:
input[name='1.6.7.wlan_id']
input[onlick^='editThisWlan']
How can I use the simplePagination.js jQuery plugin with server side? I have a lot of divs loading with my page (not a table) and I am paginating those 'divs'. But, there will be cases that I will get a lot of things to paginate (like 2500+) and my page gets slow. This is my code now:
$("#pagination").pagination({
items: numItems,
itemsOnPage: perPage,
cssStyle: "light-theme",
// This is the actual page changing functionality.
onPageClick: function(pageNumber) {
// We need to show and hide `tr`s appropriately.
var showFrom = perPage * (pageNumber - 1);
var showTo = showFrom + perPage;
// We'll first hide everything...
items.hide()
// ... and then only show the appropriate rows.
.slice(showFrom, showTo).show();
}
});
And this is my page with all the divs loaded:
As you can see, I have a search option:
But everytime I search something, all the divs are reloaded, and the pagination is made again.
I want to know if its possible to change this code to not load all the content in client-side but something like if I select the content from server side. The divs are loaded by a SQL command, so, maybe I can use the functions of each page number to load each page correctly with only 20 itens and later I can do something about the search box.
EDIT
That is my html code (in php):
<html lang="pt-br">
<head>
<link rel="stylesheet" href="assets/css/simplePagination.css">
<script src="assets/js/jquery.simplePagination.js"></script>
<script type="text/javascript">
$(function(){
var keywordInput = document.querySelector("input[name='keyword']");
function performMark() {
$(".content.panel").show();
// Read the keyword
var keyword = keywordInput.value;
$('.content').removeClass('hidden');
$('.content:not(:contains(' + keyword + '))').addClass('hidden');
/* Tentar refazer paginação */
var items = $(".content.panel").not(".hidden");
var numItems = items.length;
var perPage = 16;
// Only show the first 2 (or first `per_page`) items initially.
items.slice(perPage).hide();
$("#pagination").pagination({
items: numItems,
itemsOnPage: perPage,
cssStyle: "light-theme",
// This is the actual page changing functionality.
onPageClick: function(pageNumber) {
// We need to show and hide `tr`s appropriately.
var showFrom = perPage * (pageNumber - 1);
var showTo = showFrom + perPage;
// We'll first hide everything...
items.hide()
// ... and then only show the appropriate rows.
.slice(showFrom, showTo).show();
}
});
};
// Listen to input and option changes
keywordInput.addEventListener("input", performMark);
});
</script>
<script type="text/javascript">
$(function() {
var items = $(".content.panel").not(".hidden");
var numItems = items.length;
var perPage = 16;
// Only show the first 2 (or first `per_page`) items initially.
items.show();
items.slice(perPage).hide();
// Now setup the pagination using the `.pagination-page` div.
$("#pagination").pagination({
items: numItems,
itemsOnPage: perPage,
cssStyle: "light-theme",
// This is the actual page changing functionality.
onPageClick: function(pageNumber) {
// We need to show and hide `tr`s appropriately.
var showFrom = perPage * (pageNumber - 1);
var showTo = showFrom + perPage;
// We'll first hide everything...
items.hide()
// ... and then only show the appropriate rows.
.slice(showFrom, showTo).show();
}
});
function checkFragment() {
// If there's no hash, treat it like page 1.
var hash = window.location.hash || "#page-1";
// We'll use a regular expression to check the hash string.
hash = hash.match(/^#page-(\d+)$/);
if(hash) {
// The `selectPage` function is described in the documentation.
// We've captured the page number in a regex group: `(\d+)`.
$("#pagination").pagination("selectPage", parseInt(hash[1]));
}
};
// We'll call this function whenever back/forward is pressed...
$(window).bind("popstate", checkFragment);
// ... and we'll also call it when the page has loaded
// (which is right now).
checkFragment();
});
</script>
<!--link href="assets/css/table.css" rel="stylesheet"-->
</head>
<body onload="myFunction()">
<div class="container">
<div id="loader"></div>
<div style="display:none;" id="myDiv" class="animate-bottom">
<div class="input-group input-group-lg" style="margin-bottom: 15px;">
<span class="input-group-addon glyphicon glyphicon-search" id="sizing-addon1" style="position: initial;"></span>
<input name="keyword" type="text" class="form-control" placeholder="Pesquisar" aria-describedby="sizing-addon1" onload="performMark()">
</div>
<div id="pagination" style="margin-bottom: 5px;"></div>
<div class='row centered'>
<?php
$sql = "SELECT * FROM USU_TDriCad";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (($row = oci_fetch_array($stid, OCI_BOTH)) != false) {
$CodDri = 'test';
$CodDri = (isset($row['USU_CODDRI']) ? $row['USU_CODDRI'] : '');
echo '<div class="content warning">
<div class="content panel panel-warning">
<div class="panel-heading highlight">
<h3 class="panel-title">' . $StrLoc . '</h3>
</div>
<div class="panel-body warning highlight" style="padding: 2px">
' . $CodDri . '
</div>
<div class="panel-body warning highlight" style="padding: 2px; font-size: 16px">
<div class="col-xs-6">1000</div>
<div class="col-xs-6">#008</div>
</div>
</div>
</div>';
}
oci_free_statement($stid);
?>
</div>
</div>
</div>
</body>
</html>
Thanks
I will offer my solution.
var
search = $("#search"),
control = $("#pagination"),
table = $("#table tbody tr"),
pageParts = null,
perPage = 2;
search.on("keyup", function() {
var value = $(this).val().toLowerCase();
table.filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
updPagination();
});
control.pagination({
itemsOnPage: perPage,
cssStyle: "light-theme",
onPageClick: function(pageNum) {
var start = perPage * (pageNum - 1);
var end = start + perPage;
if (pageParts) {
pageParts.hide()
.slice(start, end).show();
}
}
});
function updPagination() {
pageParts = table.filter(function() { return $(this).css("display") !== 'none' });
pageParts.slice(perPage).hide();
control.pagination('selectPage', 1);
control.pagination('updateItems', pageParts.length);
}
updPagination();
table {
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
border: 1px solid #cbcbcb;
}
td,
th {
border-left: 1px solid #cbcbcb;
border-width: 0 0 0 1px;
font-size: inherit;
margin: 0;
overflow: visible;
padding: 0.5em 1em
}
td:first-child,
th:first-child {
border-left-width: 0;
}
thead {
background-color: #e0e0e0;
color: #000;
text-align: left;
vertical-align: bottom;
}
<link rel="stylesheet" href="https://cdn.bootcss.com/simplePagination.js/1.6/simplePagination.min.css">
<input id="search" type="text" placeholder="Search for..">
<table id="table">
<thead>
<tr>
<td>ID</td>
<td>Name</td>
</tr>
<tbody>
<tr>
<td>1</td>
<td>test 1</td>
</tr>
<tr>
<td>2</td>
<td>test 2</td>
</tr>
<tr>
<td>3</td>
<td>test 3</td>
</tr>
<tr>
<td>4</td>
<td>test 4</td>
</tr>
<tr>
<td>5</td>
<td>test 5</td>
</tr>
</tbody>
</table>
<div id="pagination"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/simplePagination.js/1.6/jquery.simplePagination.min.js"></script>
Through jsoup I'm able to retrieve the Registration Date data but unable to get second column value 31/12/2009. Instead it returns empty string. I tried all possible ways.
All the table rows are extracting correctly.
<tr>
<td style="width: 30%; font-weight: bold; background-color: #d7e8ff; ">
<span style="font-size: 10pt"> Registration Date</span></td>
<td style="margin-bottom: 1px; padding-bottom: 1px; background
color:lemonchiffon;">
<span id="ContentPlaceHolder1_636042629082042500">الخميس 31/12/2009</span>
<span id="ContentPlaceHolder1_iInstalldate"></span></td>
</tr>
Here is the java code I'm using:
Element table = doc.select("TABLE").get(2);
Elements table1=table.select("table[border=1]"); // to select particular
//table
Elements rows=table1.select("tr");
for (int i = 0; i < rows.size(); i++) {
Element row = rows.get(i);
Elements cols=row.select("td");
for (Element col : cols) {
if (!(col.text().equals("")))
Log.e("test", col.text()+cols.size());
}
}
Here is the output but only values in first column not the second one:
Registration Date ,
Account Type ,
Current Account Status ,
Total Account Credit ,
Used Credit ,
Valid Credit ,
Credit Expiry Date
Now Here is the Sample Source of this page table with following Rows
<tr>
<td style="width: 30%; font-weight: bold; background-color: #d7e8ff; ">
<span style="font-size: 10pt">Registration Date</span></td>
<td style="margin-bottom: 1px; padding-bottom: 1px; background-color:
lemonchiffon;">
<span id="ContentPlaceHolder1_636045303384071212">الخميس 31/12/2009</span>
<span id="ContentPlaceHolder1_iInstalldate"></span></td>
</tr>
<tr>
<td style="width: 30%; font-weight: bold; background-color: #d7e8ff;
">Account Type</td>
<td style="margin-bottom: 1px; padding-bottom: 1px; background-color:
lemonchiffon;">
<span id="ContentPlaceHolder1_636045303384071212">1 Mbps---فضي</span>
<span id="ContentPlaceHolder1_iAcctType"></span></td>
</tr>
Here is the code i am using to access the web page
loginForm=Jsoup.connect("http://adsl.yemen.net.ye/en/user_main.aspx")
.data("ctl00$ContentPlaceHolder1$loginframe$Password", "MAMAM")
.data("ctl00$ContentPlaceHolder1$loginframe$LoginButton", "Sign In")
.data("__LASTFOCUS", "")
.data("__EVENTTARGET", "")
.data("__EVENTARGUMENT","")
.userAgent("Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML,
like Gecko) Chrome/51.0.2704.103 Safari/537.36")
.cookies(loginForm.cookies())
.followRedirects(false)
.method(Connection.Method.POST)
.execute();
You can do it in this way:
package com.github.davidepastore.stackoverflow38415236;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
* Stackoverflow 38415236 answer.
*
*/
public class App {
public static void main(String[] args) {
String html = "<table><tr>\r\n"
+ " <td style=\"width: 30%; font-weight: bold; background-color: #d7e8ff; \">\r\n"
+ " <span style=\"font-size: 10pt\">Registration Date</span></td>\r\n"
+ "\r\n"
+ " <td style=\"margin-bottom: 1px; padding-bottom: 1px; background-color: \r\n"
+ " lemonchiffon;\">\r\n"
+ "\r\n"
+ " <span id=\"ContentPlaceHolder1_636045303384071212\">الخميس 31/12/2009</span>\r\n"
+ " <span id=\"ContentPlaceHolder1_iInstalldate\"></span></td>\r\n"
+ " </tr>\r\n"
+ " <tr>\r\n"
+ " <td style=\"width: 30%; font-weight: bold; background-color: #d7e8ff; \r\n"
+ " \">Account Type</td>\r\n"
+ " <td style=\"margin-bottom: 1px; padding-bottom: 1px; background-color: \r\n"
+ " lemonchiffon;\">\r\n"
+ "\r\n"
+ "<span id=\"ContentPlaceHolder1_636045303384071212\">1 Mbps---فضي</span>\r\n"
+ "<span id=\"ContentPlaceHolder1_iAcctType\"></span></td>\r\n"
+ "</tr></table>";
Document doc = Jsoup.parse(html);
Element table = doc.select("table").first();
Elements trs = table.select("tr");
for (Element tr : trs) {
Elements td = tr.select("td");
Element firstTd = td.first();
Element secondTd = td.get(1);
System.out.println(firstTd.text() + " --- " + secondTd.text());
}
}
}
The output is:
Registration Date --- الخميس 31/12/2009
Account Type --- 1 Mbps---فضي
Use selectors to target the elements directly and then extract their text.
Document doc = Jsoup.parse(htmlContent);
Elements rows = doc.select("table[border=1] tr");
for (Element row : rows) {
String key = row.select("td:first-child").text();
String value = row.select("td:nth-child(2) span:first-child").text();
System.out.println("key=" + key + " value=" + value);
}
Output
key=Registration Date value=31/12/2009
key=Account Type value=1 Mbps---
I am relatively new to AngularJs and I am having trouble implementing a Fixed Header on my table. I am using a modified version of a library I am utilizing on other parts of my application with no problem however on this specific table it is not working. I even tried having two separate tables one for the head and one for the body but since the can be dynamic with Angular and a Maximize, this does not work.
js code:
<div id="test"
class="panel-body" style="height: 222px; overflow-y: scroll;">
<table id="data-sources-table" class="table table-striped drag-drop" fixed-header-custom >
<thead>
<tr>
<th style="position: relative">TestProperty</th>
<th style="position: relative" ng-repeat="ds in model.dataSamples"
style="line-height: 16px; vertical-align: top;">
<span tooltip="{{ds.dsName}}"
tooltip-placement="top">
{{ds.dsName.slice(0, 20)}}
</span>
<button class="btn-graphic-only btn-remove" type="button"
ng-show="ds"
ng-model="singleModel"
tooltip="Test data sample"
tooltip-placement="left"
ng-click="removeDs($index)">
</button>
</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="(property, linkedDs) in model.properties">
<td ng-class="{'narrow-column': $first}"
ng-style="highlightIfInDetails(model.properties[property])">
<span>
<ul style="margin-bottom: 0px; list-style-type: none; padding: 0px;">
<li dnd-draggable="ds.dsProfile[property]"
dnd-effect-allowed="copy"
dnd-copied="dragEnd(property, ds.dsProfile[property])"
dnd-selected="dropzoneModels.selected = ds.dsProfile[property]">
<label class="btn-property" style="font-size: 100%;">
{{property}}
</label>
<button class="btn-graphic-only btn-remove" type="button"
ng-model="singleModel"
tooltip="Remove property from schema"
tooltip-placement="right"
ng-click="removeProperty(property)">
</button>
<div ng-show="modifySchemaMode === true">
<!--keep the following on the same line to prevent spaces between values-->
{{model.properties[property]["main-type"]}}<span
ng-show="model.properties[property]['main-type']">:{{model.properties[property]["detail"]["detail-type"]}}</span>
</div>
</li>
</ul>
</span>
</td>
<td ng-repeat="ds in model.dataSamples"
ng-style="highlightIfInDetails(ds.dsProfile[property])">
<span class="btn-property">
<label class="btn-property"
style="font-size: 100%; font-weight: normal;
-webkit-user-select: none; -moz-user-select: none;
-ms-user-select: none;"
unselectable="on"
single-click="showInDetails1(ds, property, false)"
ng-dblclick="showInDetails2(ds, property);">
<div ng-show="ds.dsProfile[property]['original-name']">
<label style="font-size: 100%;">{{ds.dsProfile[property]['original-name']}}</label>
</div>
<!--keep the following on the same line to prevent spaces between values-->
{{ds.dsProfile[property]["main-type"]}}<span
ng-show="ds.dsProfile[property]['main-type']">:{{ds.dsProfile[property]["detail"]["detail-type"]}}</span>
<span class="btn-merge-indicator"
ng-show="ds.dsProfile[property]['merged-into-schema']">
</span>
</label>
<span class="btn-use-check"
ng-show="ds.dsProfile[property]['used-in-schema']">
</span>
<br>
<select name="altNameSelected" id="altNameSelected"
ng-options="option.name for option in ds.dsProfile[property]['match-names'].availableOptions track by option.id"
ng-model="ds.dsProfile[property]['match-names'].selectedOption"
ng-show="ds.dsProfile[property]['match-names'].availableOptions.length > 0"
ng-change="changeMatchedProperty(ds, property)">
</select>
</span>
</td>
</tr>
</tbody>
</table>
</div>
library:
/**
* AngularJS fixed header scrollable table directive
* #author Jason Watmore <jason#pointblankdevelopment.com.au> (http://jasonwatmore.com)
* #version 1.2.0
*/
(function () {
angular
.module('anguFixedHeaderTableCustom', [])
.directive('fixedHeaderCustom', fixedHeaderCustom);
fixedHeaderCustom.$inject = ['$timeout'];
function fixedHeaderCustom($timeout) {
return {
restrict: 'A',
link: link
};
function link($scope, $elem, $attrs, $ctrl) {
var elem = $elem[0];
// wait for data to load and then transform the table
$scope.$watch(tableDataLoaded, function(isTableDataLoaded) {
if (isTableDataLoaded) {
transformTable();
}
});
function tableDataLoaded() {
// first cell in the tbody exists when data is loaded but doesn't have a width
// until after the table is transformed
var firstCell = elem.querySelector('tbody tr:first-child td:first-child');
return firstCell && !firstCell.style.width;
}
function transformTable() {
// reset display styles so column widths are correct when measured below
angular.element(elem.querySelectorAll('thead, tbody, tfoot')).css('display', '');
// wrap in $timeout to give table a chance to finish rendering
$timeout(function () {
// set widths of columns
angular.forEach(elem.querySelectorAll('tr:first-child th'), function (thElem, i) {
var tdElems = elem.querySelector('tbody tr:first-child td:nth-child(' + (i + 1) + ')');
var tfElems = elem.querySelector('tfoot tr:first-child td:nth-child(' + (i + 1) + ')');
var columnWidth = tdElems ? tdElems.offsetWidth : thElem.offsetWidth;
if (tdElems) {
tdElems.style.width = columnWidth + 'px';
}
if (thElem) {
thElem.style.width = columnWidth + 'px';
}
if (tfElems) {
tfElems.style.width = columnWidth + 'px';
}
});
// set css styles on thead and tbody
angular.element(elem.querySelectorAll('thead, tfoot')).css('display', 'block');
angular.element(elem.querySelectorAll('tbody')).css({
'display': 'block',
'height': $attrs.tableHeight || 'inherit',
'overflow': 'auto'
});
// reduce width of last column by width of scrollbar
var tbody = elem.querySelector('tbody');
var scrollBarWidth = tbody.offsetWidth - tbody.clientWidth;
if (scrollBarWidth > 0) {
// for some reason trimming the width by 2px lines everything up better
scrollBarWidth -= 2;
var lastColumn = elem.querySelector('tbody tr:first-child td:last-child');
lastColumn.style.width = (lastColumn.offsetWidth - scrollBarWidth) + 'px';
}
});
}
}
}
})();