I have a table that shows items and the current inventory. Next to each row of inventory, I have a checkbox and a textbox.
The webpage shows the current inventory and gives options for removing selected stock from inventory. So basically checking out items from stock.
I'd like to be able to pass both the selected item and the inputted amounts to be removed from stock via jQuery but I am having trouble finding the best way to 'serialize' both the checkbox and the text input.
I've tried a number of strategies based off other SO questions, but I only seem to be able to grab either the checked box value or all of the text input values but not the checked box value and only the input value of the checked box.
What I am trying to get:
Checked Apple & entered 5: box=Apple&amt=5
What I've tried (seen in on('submit') function):
What I am getting when using var details = $('input[name="box"]:checked').serialize();:
Checked Apple & entered 5: box=Apple
What I am getting when using var details = $('#checkout_form').serialize();
or
var details = $('input[id="amt"]').serialize();
:
Checked Apple & entered 5: Apple=5&Banana=&Corn=&Deli%20Sandwich=&....
Here is the jQuery code for displaying the table from JSON data and for passing the data to PHP:
var url = 'get_students.php';
var $list = $('#inventory');
$(document).ready(function() {
$.ajax({
type: 'POST',
url: url,
data: {
command: 'get_inventory',
},
beforeSend: function() {
$list.html('<div id="load" class="spinner-border text-muted"></div>');
},
success: function(data) {
console.log(data);
DISPLAY_INVENTORY(data);
$('#load').remove();
},
fail: function() {
$list.html('Could not get data ...');
},
});
});
function DISPLAY_INVENTORY(JSON_DATA) {
var COL_NAMES = ['Select', 'Item', 'Inventory', 'Amount'];
var data = jQuery.parseJSON(JSON_DATA);
var $TABLE_OBJ = $('<table class="table table-striped" >');
$TABLE_OBJ.attr('id', 'student_table');
$list.append($TABLE_OBJ);
// $(output).append($TABLE_OBJ);
//Print a table header
var $ROW_OBJ = $('<tr>');
var $THEAD = $('<thead class="thead-light">');
$THEAD.append($ROW_OBJ);
$TABLE_OBJ.append($THEAD);
for (var j = 0; j < COL_NAMES.length; j++) {
var $TB_HEADER = $('<th>');
$TB_HEADER.html(COL_NAMES[j]);
$ROW_OBJ.append($TB_HEADER);
}
$TBODY = $('<tbody>');
//Print rows
for (var i = 0; i < data.length; i++) {
if (i == data.length - 1) {
$TABLE_OBJ.append($TBODY);
}
$ROW_OBJ = $('<tr>');
$TBODY.append($ROW_OBJ);
$BOX_OBJ = $('<input name="box" class="form-control ml-4" type="checkbox">');
$ROW_OBJ.append($BOX_OBJ);
//Print columns
$.each(data[i], function(key, value) {
// if (i % 2 == 0) {
// var ITEM_NAME = value;
// }
if (key === 'item') {
rowItemName = value;
}
$COL_OBJ = $('<td>');
$INP_OBJ = $('<input id="amt" class="text-center form-control" type="text" size="3">');
if (!$INP_OBJ.attr('name') || !($BOX_OBJ.attr('value'))) {
$INP_OBJ.attr('name', rowItemName);
$BOX_OBJ.attr('value', rowItemName);
// $INP_OBJ.attr('id', ITEM_NAME);
}
// $INP_OBJ.attr('name', ITEM_NAME);
// $INP_OBJ.attr('id', ITEM_NAME);
$COL_OBJ.html(value);
$ROW_OBJ.append($COL_OBJ);
});
$ROW_OBJ.append($INP_OBJ);
}
}
// add form to checkout
$('#checkout_form').on('submit', function(e) {
e.preventDefault();
// var details = $('#checkout_form').serialize();
// var details = $('input[name="box"]:checked', 'input[id="amt"]').serialize();
// var details = $('input[name="box"]:checked').serialize();
var details = $('input[id="amt"]').serialize();
console.log(details);
//Update the info into database table
$.post(url, {
command: 'update_inventory',
log_data: details,
},
function(data, status) {
console.log('Data: ' + data + '\nStatus: ' + status);
//$status.html(status + ": " + data);
});
});
Here is the JSON data if needed:
[{"item":"Apple","amount":"10"},
{"item":"Banana","amount":"11"},
{"item":"Corn","amount":"12"},
{"item":"Deli Sandwich","amount":"5"},
{"item":"Egg Plant","amount":"12"},
{"item":"French Fries","amount":"15"},
{"item":"Green Beans","amount":"21"},
{"item":"Hamburgers","amount":"7"},
{"item":"Ice Cream","amount":"3"},
{"item":"Jell-O","amount":"12"},
{"item":"Kiwi","amount":"8"},
{"item":"Lima Beans","amount":"32"},
{"item":"Mashed Potatoes","amount":"11"},
{"item":"Noodle Soup","amount":"54"},
{"item":"Orange","amount":"10"},
{"item":"Pear","amount":"5"},
{"item":"Quinoa","amount":"4"},
{"item":"Raisins","amount":"12"},
{"item":"String Cheese","amount":"16"},
{"item":"Tomato Soup","amount":"23"},
{"item":"Unsalted Nuts","amount":"19"},
{"item":"Vienna Sausage","amount":"24"},
{"item":"Wheat Bread","amount":"15"},
{"item":"Xavier Soup","amount":"17"},
{"item":"Yogurt","amount":"11"},
{"item":"Zucchini","amount":"12"}]
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<!-- ------------------------------------- -->
<!-- LOAD EXTERNAL STYLES -->
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<!-- Fonts and Icons -->
<link href="vendor/fontawesome-free/css/all.min.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/octicons/8.5.0/build.css">
<link rel="icon" href="https://txwes.edu/media/twu/style-assets/images/favicon.ico" type="image/x-icon">
<!-- ------------------------------------- -->
<style>
html,
body {
height: 100%
}
body {
background: url('img/bg.jpg');
}
.container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.fas {
color: black !important
}
</style>
<title>Checkout</title>
</head>
<body>
<!-- Header -->
<div class="jumbotron text-center h-auto " style="background: rgba(244, 226, 66,0.5); border-bottom: 5px outset rgb(244, 226, 66);">
<img src="img/ramlogo3.png" alt="ramlogo">
</div>
<div class="container">
<div class="jumbotron text-center">
<h1>Checkout</h1>
<form id="checkout_form" method="post">
<div id="inventory" class="text-center border border-primary rounded p-3" style="overflow-y:scroll; overflow-x:hidden; height:400px;"></div><br>
<button class="btn btn-primary" type="submit" name="button">Checkout</button>
</form>
</div>
</div>
</body>
<script type="text/javascript">
...see above...
</script>
</html>
Please let me know if any more explanation is needed, thank you for the help!
To serialize your data in a single row you can try this code:
var details = $('input[name="box"]:checked').closest("tr").find("input").serialize();
Related
How can i select multiple pictures. right now i'm able to get pictures single-single but i want to get multiple. how can i do that?
What i tried:-
$(function() {
$(document).on('change', '.caFileBtn', function() {
console.log(imagePath);
var files = this.files
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imagePath = URL.createObjectURL(file);
}
var imageElement = `
<div>
<img src="${imagePath}" />
</div>
`;
$('.ca-photos-area').show();
$('.ca-photos-area').prepend(imageElement);
$(this).val('');
});
});
.ca-photos-area {
display: flex;
}
.ca-photos-area img {
width: 90px;
height: 90px;
margin: 5px;
border: 1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div class="btn btn-primary btn-block">
<input type="file" Multiple="Multiple" class="caFileBtn" />
<i class="fas fa-image"></i>
</div>
<div class="col-md-12">
<div class="ca-photos-area mt-3">
</div>
</div>
Answer will be appreciated
While html tags and attributes are case-insensitive it's best practice to use lowercase. Though, attribute values are case-sensitive. So, you must define multiple in lowercase:
<input type="file" multiple="multiple" class="caFileBtn" />
<!-- Must be in lowercase --- ^^ -->
<!-- Otherwise, it's still single type -->
Or, you could also have defined attribute only:
<input type="file" multiple class="caFileBtn" />
The above answer seems to be wrong in the case of multiple attribute as it accepts boolean and using it case-insensitive also meant to be multiple.
Here's the working javascript code that will select all selected images:
$(function() {
$(document).on('change', '.caFileBtn', function() {
console.log(imagePath);
var files = this.files
var imageElement = [];
for (var i = 0; i < files.length; i++) {
var file = files[i];
var imagePath = URL.createObjectURL(file);
imageElement.push( `
<div>
<img src="${imagePath}" />
</div>`);
}
for (var i=0; i<imageElement.length; i++){
$('.ca-photos-area').prepend(imageElement[i]);
}
$('.ca-photos-area').show();
$(this).val('');
});
});
Issue
The majority of the statements within handler were outside the for loop. BTW I removed the reset statement: $(this).val('') because the tag would always display: "no files selected..." whether there were files selected or not. Without the reset you get a list of the file names selected.
Demo
$('.caFileBtn').on('change', function() {
const self = $(this)[0];
const files = self.files;
let imagePath, imageTag;
for (let i = 0; i < files.length; i++) {
let file = files[i];
imagePath = URL.createObjectURL(file);
imageTag = `<figure><img src="${imagePath}"></figure>`;
$('.ca-photos-area').prepend(imageTag);
}
});
.ca-photos-area {
display: flex;
}
.ca-photos-area img {
width: 90px;
height: 90px;
margin: 5px;
border: 1px solid #ccc;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.13.0/css/all.css" rel="stylesheet" crossorigin="anonymous">
<label class="btn btn-primary btn-block">
<input class="caFileBtn" type="file" multiple="multiple">
<i class="fas fa-image"></i>
</label>
<section class="col-md-12">
<article class="ca-photos-area mt-3"></article>
</section>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/js/bootstrap.min.js"></script>
HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"/>
<link rel="stylesheet" type="text/css" media="all" href="css/animate.min.css"/>
<link href="http://fonts.googleapis.com/css?family=Lobster" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"/>
<link rel="stylesheet" href="css/thisProject.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
<h1 class="text-primary">Wiki Article Search</h1>
<div>
<input type="text" id="input"/>
<button id="search">Search</button>
<a id="random" class="btn btn-primary" target="_blank" href="http://en.wikipedia.org/wiki/Special:Random">Press For Random</a>
</div>
</br>
<div id="bodyDiv">
</div>
<script src="wikiViewer.js"></script>
</body>
</html>
JavaScript:
(function(){
var searchBtn = document.getElementById('search');
//var body = document.getElementsByTagName('body')[0];
var input = document.getElementById("input");
var bodyDiv = document.getElementById('bodyDiv')
$(document).ready(function(){
searchBtn.addEventListener('click', searchWiki);
function searchWiki(){
bodyDiv.innerHTML = "";
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch='
if (input.value === ""){
return;
}
var searchTerm = input.value.replace(/\s/g, '%20');
url = url + searchTerm + '&callback=?';
$.getJSON(url, domMod); //change fileName to be whatever we wish to search
function domMod(json){ //what to do with dom based on json file NOTE WE NEED TO FIRST CHECK ANDREMOVE PREVIOUS SEARCH CONTENT
var entry;
if (!json.hasOwnProperty('query')){
return;
}
if (!json.query.hasOwnProperty('pages')){
return;
}
json = json.query.pages;
var keys = Object.keys(json);
var keysLength = keys.length;
for (var i = 0; i < keysLength; i++){
entry = json[keys[i]];
var outterDiv = document.createElement('div');
outterDiv.className = "entry";
var imageDiv = document.createElement('div');
imageDiv.className = "entryImg";
var entryDiv = document.createElement('div');
entryDiv.className = "entryTxt";
outterDiv.appendChild(imageDiv);
outterDiv.appendChild(entryDiv);
entryDiv.innerHTML = '<h2>' + entry.title + '</h2>' + '<p>' + entry.extract + '</p>'
if (entry.hasOwnProperty('thumbnail')){ //add image to our imageDiv child of entryDiv
imageDiv.style.backgroundImage = "url('" + entry.thumbnail.source + "')"
}
var br = document.createElement('br');
bodyDiv.appendChild(outterDiv); //appendChild to the Body
bodyDiv.appendChild(br);
}
}
}
});
}())
CSS:
input{
width:180px;
}
.entry{
width:90%;
margin-left:auto;
margin-right:auto;
height: 140px;
}
.entryTxt{
margin-left: 5px;
}
.entryImg{
width:125px;
height:125px;
margin-right: 5px;
background-repeat: no-repeat;
background-size: contain;
background-position: center;
float:left;
}
#bodyDiv{
width: 100%;
height: 1600px;
}
The javascript code runs through each return object that a wikipedia API returns based on a user's search term. It then puts the image in a div with class "entryImg" and the entry text in a div called "entryTxt". It then puts each of these in a div labeled outterDiv which is appended to the div already in my HTML with id "bodyDiv." My question is, in each outterDiv why are the picture and the text divs so close to each other regardless of how much I change the margins. I put 5px on the texts left margin and 5 px on the picture divs right margin as can be seen and the change isn't appearing in the browser. Why is this and how can I fix it?
based on your javascript code the generated html would be
<div id="bodyDiv">
<div class="entry">
<div class="entryImg"></div>
<div class="entryTxt">
<h2>lorem ipsum</h2>
<p>lorem ipsum</p>
</div>
</div>
</div>
and, with your css, you ca increase the space between image and text by
increasing margin-right on .entryImg
.entryImg {
margin-right: 10px;
}
or, by increasing margin-left on .entryTxt after adding overflow: hidden; on it.
.entryTxt {
margin-left: 10px;
overflow: hidden;
}
check this fiddle
I am trying to get some data from the server. I am displaying it in the form of a list. The list is getting displayed nicely. However, when the user clicks a list-item; the user should see the contents related to that particular list item in a modal. How to do I go about it?
Here is my code:
<!DOCTYPE>
<html>
<head>
<title>Pagination tutorial</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="stylesheet" href="https://bootswatch.com/yeti/bootstrap.min.css" type="text/css">
<style>
#pagination div { display: inline-block; margin-right: 5px; margin-top: 5px }
#pagination .cell a { border-radius: 3px; font-size: 11px; color: #333; padding: 8px; text-decoration:none; border: 1px solid #d3d3d3; background-color: #f8f8f8; }
#pagination .cell a:hover { border: 1px solid #c6c6c6; background-color: #f0f0f0; }
#pagination .cell_active span { border-radius: 3px; font-size: 11px; color: #333; padding: 8px; border: 1px solid #c6c6c6; background-color: #e9e9e9; }
#pagination .cell_disabled span { border-radius: 3px; font-size: 11px; color: #777777; padding: 8px; border: 1px solid #dddddd; background-color: #ffffff; }
</style>
</head>
<body>
<div id="articleArea"></div> <!-- Where articles appear -->
<!-- Where pagination appears -->
<div id="pagination">
<!-- Just tell the system we start with page 1 (id=1) -->
<!-- See the .js file, we trigger a click when page is loaded -->
<div></div>
</div>
<script type="text/javascript" src="//code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="tuto-pagination.js"></script>
</body>
</html>
My javascript code is as follows:
$('document').ready(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
});
$('#pagination').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="loader-small.gif" alt="" />'); // Display a processing icon
var data = {page: page, per_page: 4}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
console.log('Ajax sent');
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'tuto-pagination.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
var displayData='';
for (var i = 0; i < data.articleList.length; i++) {
var gotData = data.articleList[i];
displayData += '<div class="well well-sm">' + gotData.profile_id + '. <b>' + gotData.first_name + '</b><p>' + gotData.surname + '</p></div>';
$('body').on('click','.well well-sm',function(){
var list = gotData;
openModal(list,data);
});
function openModal(list,data){
$('#myModal .modal-title').html(list.html());
$('#myModal .modal-body').html(data);
$('.modalTrigger').trigger('click');
}
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>First</span></div><div class="cell_disabled"><span>Previous</span></div>';
else pagination += '<div class="cell">First</div><div class="cell">Previous</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage) pagination += '<div class="cell_disabled"><span>Next</span></div><div class="cell_disabled"><span>Last</span></div>';
else pagination += '<div class="cell">Next</div><div class="cell">Last</span></div>';
$('#pagination').html(pagination); // We update the pagination DIV
},
error: function() {
}
});
return false;
});
When you are fetching the information from back-end, create the list as shown in the code below, show only first 4 fields, and add a class hidden to the rest of the 26 fields. Construct the list item as you want it to be. Here I have used p tags inside div.well, where first p-tag is shown and rest of the p-tags are hidden.
Now whenever a user clicks on a div-well (that is a list) I am getting the html data from within it and removing the .hidden class from the p-tags. You can also similarly try having your own html structure(have it in a way so that it is easier to manipulate it).
displayData += '<div class="well well-sm"><p>' + gotData.profile_id + '. <b>' + gotData.first_name + '</b>' + gotData.surname + '</p>';
displayData += '<p class="hidden">'+gotData.address+'</p>'+'<p class="hidden">'+gotData.gender+'</p>'+'<p class="hidden">'+gotData.dob+'</p>';
displayData += '</div>';
Then whenever a user clicks on the list item, fetch the data from the list and show it in a modal, this way you don't have to create multiple div's.
$(function(){
$('body').on('click','div.well.well-sm',function(){
var list = $(this);
var data=list.html();
$('#myModal .modal-title').html('User Information');
$('#myModal .modal-body').html(data);
$('#myModal .modal-body p').removeClass('hidden');
$('.modalTrigger').trigger('click');;
});
});
.margin-top-md{
margin-top: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.1/css/bootstrap.min.css">
<div class="container-fluid">
<div class="well well-sm margin-top-md">
<p>1. John White</p>
<p class="hidden">Country: UK</p>
<p class="hidden">DOB: 29 July</p>
<p class="hidden">Gender:M</p>
</div>
<div class="well well-sm margin-top-md">
<p>4. Ray</p>
<p class="hidden">Country: IN</p>
<p class="hidden">DOB: 29 Aug</p>
<p class="hidden">Gender: M</p>
</div>
<div class="well well-sm margin-top-md">
<p>3. Nick Cole</p>
<p class="hidden">Country: US</p>
<p class="hidden">DOB: 29 Sep</p>
<p class="hidden">Gender:M</p>
</div>
</div>
<button type="button" class="btn btn-primary btn-lg hidden modalTrigger" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
$(function() {
$("#pagination a").trigger('click'); // When page is loaded we trigger a click
$('#pagination').on('click', 'a', function(e) { // When click on a 'a' element of the pagination div
var page = this.id; // Page number is the id of the 'a' element
var pagination = ''; // Init pagination
$('#articleArea').html('<img src="loader-small.gif" alt="" />'); // Display a processing icon
var data = {page: page, per_page: 4}; // Create JSON which will be sent via Ajax
// We set up the per_page var at 4. You may change to any number you need.
console.log('Ajax sent');
$.ajax({ // jQuery Ajax
type: 'POST',
url: 'tuto-pagination.php', // URL to the PHP file which will insert new value in the database
data: data, // We send the data string
dataType: 'json', // Json format
timeout: 3000,
success: function(data) {
var displayData='';
for (var i = 0; i < data.articleList.length; i++) {
var gotData = data.articleList[i];
displayData += '<div class="well well-sm"><p>' + gotData.profile_id + '. <b>' + gotData.first_name + '</b>' + gotData.surname + '</p>';
displayData += '<p class="hidden">'+gotData.address+'</p>'+'<p class="hidden">'+gotData.gender+'</p>'+'<p class="hidden">'+gotData.dob+'</p>';
displayData += '</div>';
// Pagination system
if (page == 1) pagination += '<div class="cell_disabled"><span>First</span></div><div class="cell_disabled"><span>Previous</span></div>';
else pagination += '<div class="cell">First</div><div class="cell">Previous</span></div>';
for (var i=parseInt(page)-3; i<=parseInt(page)+3; i++) {
if (i >= 1 && i <= data.numPage) {
pagination += '<div';
if (i == page) pagination += ' class="cell_active"><span>' + i + '</span>';
else pagination += ' class="cell">' + i + '';
pagination += '</div>';
}
}
if (page == data.numPage){
pagination += '<div class="cell_disabled"><span>Next</span></div><div class="cell_disabled"><span>Last</span></div>';
}
else {
pagination += '<div class="cell">Next</div><div class="cell">Last</span></div>';
}
$('#articleArea').html(displayData);//replacing img with data
$('#pagination').html(pagination); // We update the pagination DIV
}
},
error: function() {
//your code
}
});
return false;
});
$('body').on('click','div.well well-sm',function(){
var list = $(this);
$('#myModal .modal-title').html('User Information');
$('#myModal .modal-body').html(list.html());
$('#myModal .modal-body p').removeClass('hidden');
$('.modalTrigger').trigger('click');
});
});
I have a MVC view and view as like this. Print this picture and I do not want to appear when the Button and TextBox.
This code only works but does not print CSS.
and my view and javascript print for code like that
#model dynamic
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_LayoutAdmin.cshtml";
}
<link href="~/print.css" rel="stylesheet" />
<link href="~/Content/assets/css/style.css" rel="stylesheet" />
<div class="event-container">
<div class="row">
#foreach (var item in Model.JoinData)
{
BLL.Concretes.OrderDetailRepository ord = new BLL.Concretes.OrderDetailRepository();
var olacak = ord.GetWithDeleted().Where(x => x.Order.Chair.ChairNo == item.ChairNo && x.Order.Chair.Table.TableNo == item.TableID).GroupBy(x => x.Product.ProductName).Select(x => new
{
Urunadi = x.FirstOrDefault().Product.ProductName,
SiparisMiktari = x.ToList().Count()
}).ToList();
<div id="#item.ChairNo#item.TableID" class="item col-xs-12">
<div class="event-item wow fadeIn animated" data-wow-delay="0.1s">
<div class="event-place">
<b>Masa:</b>#item.TableID<br />
<b>Ürünler :</b><br />
#foreach (var item2 in olacak)
{
#(item2.SiparisMiktari + "*" + item2.Urunadi) <br />
}
<strong>Fiyat:</strong><div id="olacak">#item.Fiyat</div>
<strong>Miktar:</strong><b id="s2">#item.Miktar<br /></b>
<input type="button" value="Sandalye Ödemesi Yap" class="btn" onclick="onayla(#item.ChairNo,#item.TableID)" />
</div>
<strong>Verilen Para:</strong>#Html.TextBox("VerilenParaSandalye")<br />
#Html.ValidationMessage("VerilenParaSandalye", "", new { #class = "text-danger" })
<input type="submit" value="Fişkes" class="btn" onclick="onay(document.getElementById('VerilenParaSandalye').value,#item.ChairNo,#item.TableID,#item.Fiyat)" />
<div class="event-time">
<span class="event-month">Sandalye</span>
<span class="event-date">#item.ChairNo</span>
</div><!-- /.event-time -->
</div><!-- /.event-item -->
</div>
<input id="maradaona" type="hidden" name="name" value="#item.ChairNo#item.TableID" />
}
</div><!-- /.row -->
</div>
<script type="text/javascript">
function onay(VerilenParaSandalye, ChairNo, TableID, Fiyat) {
$.post(
'#Url.Action("validate", "Kasa")',
{ VerilenParaSandalye: VerilenParaSandalye, ChairNo: ChairNo, TableID: TableID },
function (VerilenParaSandalye) {
$.call(VerilenParaSandalye, function (index, county) {
var toPrint = document.getElementById(ChairNo + "" + TableID);
var popupWin = window.open('', '_blank');
popupWin.document.open();
popupWin.document.write('<html><head><title>HotCatCafe</title><link href="~/print.css" rel="stylesheet" /><img src="~/Content/images/logo.png" /></head><body onload="window.print()">')
popupWin.document.write(toPrint.innerHTML);
popupWin.document.write('Verilen Para : ' + VerilenParaSandalye + '<br/>');
popupWin.document.write('Para Üstü : ' + (VerilenParaSandalye - Fiyat));
popupWin.document.write('</body></html>');
popupWin.document.close();
}
)
}
);
}
if (Session["VerilenParaSandalye"] == document.getElementById('maradaona').value) {
function onayla(ChairNo, TableID) {
$.ajax({
type: "POST",
url: "#Url.Action("SandalyeTopluOdeme", "Kasa")" + "?ChairNo=" + ChairNo + "&TableID=" + TableID,
success: function (ids) {
$("#" + ChairNo + TableID).fadeOut();
}
})
}
}
</script>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
and my print and style css
this is print css
#media print
{
.btn
{
display: none;
}
.event-place
{
width: 25%;
-webkit-print-color-adjust: exact;
}
}
#media screen
{
.btn
{
display: none;
}
.event-place
{
width: 25%;
}
}
and this style css
#media screen /*--This is for Print--*/
{
.btn {
display: block;
}
.event-place
{
width: 25%;
}
}
as a result How do I get my photo to appear. and I don't want seeing of the TextBox and Button.
You load the print.css style sheet prior to the style.css style sheet. Since you're using media directives in both, there shouldn't be an issue but I'd load the print style last. Also, can you use a tool like FireBug to determine if the styles are actually loaded?
I ran the code sample and I see that the class of "btn" is applied to the submit button, but I couldn't verify that the CSS files were actually loaded.
You're on the right track of using the display: none; style for print media. There has to be a problem with loading the page or the style sheet to prevent the proper application of the style to the button.
I did notice a syntax error in the line:
url: "#Url.Action("SandalyeTopluOdeme", "Kasa")" + "?ChairNo=" + ChairNo + "&TableID=" + TableID,
You appear to have an additional quote after the closing parenthesis after Kasa.
Should it read:
url: "#Url.Action("SandalyeTopluOdeme", "Kasa") + "?ChairNo=" + ChairNo + "&TableID=" + TableID,
Good Luck!
BACKGROUND:
I have a small jquery app that contains widgets. There are 2 types of widgets in this app and they are counter widgets and grid widgets. For grid widgets i am utilizing dataTables.
My app basically connects to a server and recieves various information such as widget names etc. So based on the information received i dynamically create pages for each widget. Things are working fine at the moment but i am facing a little problem.
Problem
The issue i have right now is to do with my grid widgets which utilize dataTables api.From my server I receive the grid information in this format.
//EXAMPLE INPUT
/*
<?xml version="1.0" encoding="UTF-8"?>
<rows>
<head>
<column width="55" type="ro" align="left" sort="str">Player</column>
<column width="55" type="ro" align="left" sort="str">State</column>
<column width="55" type="ro" align="left" sort="str">Points</column>
</head>
<row id="1">
<cell>Lebron King James</cell>
<cell>Best Mode</cell>
<cell>45</cell>
</row>
</rows>
*/
Then i parse it to the appropriate table format (function createTableStringFromXML) so it works with the datatables.
My table is reloading every 3 seconds. So this is the problem.
Eventhough i want my table to update i think reloading the entire table is bad because not only does it look weird but i think it is not necessary. I was wondering is there way i can write some function that compares the old table with the new updated table and only updates rows that need update? So this way the entire table it self is not loaded?
MY HTML CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>NBA Fanatico</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="themes/tdMobile.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.0/jquery.mobile.structure-1.4.0.min.css" />
<link rel="stylesheet" type="text/css" href="cssfinal/style.css" />
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.0/jquery.mobile-1.4.0.min.js"></script>
<script src="dhtmxSuite/dhtmlxWindows/codebase/dhtmlxcommon.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.min.js"></script>
<script src="jquery.ui.touch-punch.min.js"></script>
<!-- MAIN JS SCRIPT CONTANS CODE FOR COUTNER WIDGETS, TABLES , AJAX REQUEST FOR GETTING DATA-->
<script src="dynamic.js"></script>
<!-- SCRIPTS FOR DATA TABLES -->
<!-- DataTables CSS -->
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css" />
<!-- DataTables -->
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
</head>
<body>
<!-- PAGE 1 -->
<div data-role="page" data-theme="a" id="page1">
<!-- <div data-role="header" data-position="fixed">
<h1></h1>
</div> -->
<div data-role="content" data-theme="a">
<div class="login-box" id="login">
<div id="loginprompt">
<div id="header">
<h3>Basketball Fanatico</h3>
</div>
</div>
<form method="GET">
<div id="username" data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" />
</div>
<div id="password" data-role="fieldcontain">
<input type="password" name="password" id="txtId" placeholder="Password"/>
</div>
<div id ="loginbtn">
<a data-role="button" id="log" data-theme="a" href="#page2" data-transition="slide">LOGIN</a>
</div>
</form>
<br />
</div>
</div>
</div>
</div>
<!-- PAGE 2 -->
<div data-role="page" id="page2">
<div data-role ="header" data-position="fixed" data-theme="a">
<a data-iconpos="notext" href="#panel" data-role="button" data-icon="bars"></a>
<h1 class="ui-title" role="heading">Basketball Fanatico</h1>
<div class="ui-btn-right" data-type="horizontal">
<a data-iconpos="notext" href="#page2" data-role="button" data-icon="home" ></a>
<a data-iconpos="notext" href="#page1" data-role="button" data-icon="delete" ></a>
</div>
</div>
<div data-role="content" id="page2content">
<ul data-role="listview" data-inset="true">
<li data-role="list-divider" data-theme="a">WELCOME!</li>
<li>Use the menu on the left to navigate <br />and configure the various options.</li>
</ul>
</div>
</div>
<div data-role="panel" id="panel" data-position="left" data-theme="a" data-display="push">
<!-- <div> -->
<div id="nav"><h3>Navigation</h3>
<hr>
<label>
<input id="chkSort" type="checkbox" checked="true" />Allow sorting</input>
</label>
<hr>
</div>
<div id="items" data-role="button">
<!-- Insert Parsed Widget Names Here -->
LOG OUT
</div>
<!-- </div> -->
</div>
</body>
</html>
MY JS
var widgetNames = new Array();
var widgetId = new Array();
var pageId = ''
$( document ).on( "pagecreate", function() {
$( "body > [data-role='panel']" ).panel().enhanceWithin();
//Format the grid as required
$('#example2').dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
});
$(document).on('pagecreate', '#page1', function() {
// $( ":mobile-pagecontainer" ).on( "pagecontainershow", function( event, ui ) {
// pageId = $('body').pagecontainer('getActivePage').prop("id");
// alert( "The page id of this page is: " + pageId );
// });
$("#log").on('click', function(){
$.ajax({
url: "script.login",
type: "GET",
data: { 'page':'create_user', 'access':'user','username':$("input[name='username']").val(), 'password':$("input[name='password']").val()},
dataType: "text",
success: function (html) {
//console.log(html);
widgetNames = new Array();
widgetId = new Array();
var res = html.match(/insertNewChild(.*);/g);
//Get each widget name and ID and assign to values in an array
for(var i =0;i<res.length;i++){
//alert(res[i]);
var temp = res[i].split(',');
if(temp.length >= 3){
widgetNames[i] = (temp[2].replace('");','')).replace('"','');
widgetId[i] = temp[1].replace("'","").replace("'","").replace(/ /g,'');
}
}
var AllWidgets = ''
var testwidget = new Array();
//Loop through the html returned and get the data relevant to each widget... save in temp array
var tempWidgetContent = html.match(/w\d+\.isHidden(.*)\(\) == false\)[\s\S]*?catch\(err\)\{ \}/gm);
for(var i =0;i<tempWidgetContent.length;i++){
var widgetContent = tempWidgetContent[i].substring(tempWidgetContent[i].indexOf('{')+1);
//alert(widgetContent);
//This alone handles coutners...
testwidget[i] = widgetContent.replace("site +","");
//replace the code for a grids...
if(testwidget[i].indexOf('grid') > 0){
testwidget[i] = CreateGridUpdateFunction(testwidget[i],i);
}
}
var widgetPart = new Array();
//Assume we have widget names, ids, and loading data in 3 arrays
//Loop through and create the necessary page.
for(var i = 0; i<widgetNames.length; i++){
if(testwidget[i].indexOf('hi') > -1){
// alert('WORKING');
var pageHeaderPart = "<div data-role= 'page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header' id='header1' data-position='fixed' data-theme='a'><a href='#panel' data-icon='bars' data-iconpos='notext' class='ui-btn-left'></a><a href='#' data-icon='search' id='search' data-iconpos='notext' class='ui-btn-left' style='margin-left: 35px'></a><h1>BASKETBALL FANATICO</h1><a href='#page1' data-icon='delete' data-iconpos='notext' class='ui-btn-right'></a><a href='#page2' data-icon='home' data-iconpos='notext' class='ui-btn-right' style='margin-right: 35px;'></a></div><div data-role='content'>";
}
else{
var pageHeaderPart = "<div data-role='page' id='"+widgetId[i]+"' data-pageindex='"+i+"' class='dynPageClass'><div data-role='header'data-position='fixed' data-theme='a'><a data-iconpos='notext' href='#panel' data-role='button'data-icon='bars'></a><h1 class='ui-title'role='heading'>BASKETBALL FANATICO</h1><div class='ui-btn-right' data-type='horizontal'><a data-iconpos='notext' href='#page2' data-role='button'data-icon='home'style=\" margin-right:5px; \"></a><a data-iconpos='notext' href='#page1' data-role='button'data-icon='delete'></a></div></div><div data-role='content'>";
}
var pageFooterPart = "</div><div data-role='footer' data-position='fixed'><span class='ui-title'><div id='navigator'></div></span></div></div>";
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
var check = "<div data-role='tbcontent'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"";
}
var check = "<div data-role='content'><ul data-role='listview'data-insert='true'><li data-role='list-divider' data-theme='a'>"+widgetNames[i]+"</div>";
if(testwidget[i].indexOf('counterValue') > 0){
// alert('i am a counter');
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '$(\"#widgetContainer_'+widgetId[i]+'").html(counterValue);' + '}' + '</SCRIPT>';
}
if(testwidget[i].indexOf('hi') > -1){
// alert('i am a grid');
widgetPart[i] = '<DIV id=widgetContainer_'+widgetId[i]+'></DIV><SCRIPT>' + 'function UpdateWidgetDiv'+widgetId[i]+'() {' + testwidget[i] + '}' + '</SCRIPT>';
}
else {
widgetPart[i] = '<DIV style=\" text-align: center; background-color:#EDEDED; padding-bottom: auto; font-size: 55pt;\" id=widgetContainer_'+widgetId[i]+'>I dont know what I am</DIV>';
}
AllWidgets +='<a href="#'+widgetId[i]+'" class="widgetLink" data-theme="b" data-role="button" >'+widgetNames[i]+'</a>';
var makePage = $(pageHeaderPart + check + widgetPart[i] + pageFooterPart);
makePage.appendTo($.mobile.pageContainer);
}
$('#items').prepend(AllWidgets).trigger('create');
//Widget Update Function
function UpdateActivePage(){
//get active page
pageId = $(":mobile-pagecontainer" ).pagecontainer('getActivePage').prop("id");
//figure out index
var idx;
for (var i=0; i<widgetId.length; i++){
if (widgetId[i] == pageId){
idx = i;
break;
}
}
//alert(pageId);
//run your update
//alert("RUNNING:");
eval(testwidget[idx]);
//alert('Updateing active page');
$("#widgetContainer_" + pageId).html(counterValue);
$('#grid_'+idx).dataTable( {
"bPaginate": false,
"bFilter": true,
"bAutoWidth": false,
"oLanguage": { "sSearch": "" }
} );
$('.dataTables_filter input').attr("placeholder", "Search");
$('.dataTables_filter').css('float','none');
$('.dataTables_filter').css('padding-right','0px');
$("#example_filter").detach().prependTo('#header1');
}
function CreateGridUpdateFunction(oldUpdatefunction,thisWidgetID)
{
var updateLines = oldUpdatefunction.split("\n");
var updateFunctionCode = "";
for (var i=0; i<updateLines.length;i++)
{
if(updateLines[i].indexOf(" var url = ") > 0)
{
var updateURL = updateLines[i];
if(updateURL.indexOf("&windowWidth=") > 0){
updateURL = updateURL.substr(0,updateURL.lastIndexOf("&windowWidth=")) + "';";
}
updateFunctionCode += updateURL;
updateFunctionCode += " var loader = dhtmlxAjax.getSync(url);";
updateFunctionCode += " if(loader.xmlDoc.responseText.length > 0){";
updateFunctionCode += " counterValue = createTableStringFromXML(loader.xmlDoc.responseText,"+thisWidgetID+");";
updateFunctionCode += " } ";
}
}
return "var counterValue = \"hi\"; "+updateFunctionCode ;
}
$(":mobile-pagecontainer" ).on( "pagechange", function() { UpdateActivePage(); } )
setInterval(UpdateActivePage, 3000);
}
});
});
});
//Returns a bool indicated if the (space trimmed) string starts with needle.
function startsWith(searchString,searchVal){
var search = searchString.trim();
return search.indexOf(searchVal) >= 0;
}
function createTableStringFromXML(serverXML,thisWidgetID){
console.log(serverXML);
var xmlLines = serverXML.split("\n");
var returnTable = "";
for (var i=0; i<xmlLines.length;i++)
{
if(startsWith(xmlLines[i],"<rows"))
{
returnTable += "<table cellpadding=\"2\" cellspacing=\"2\" border=\"0\" class=\"display\" id=\"grid_"+thisWidgetID+"\" width=\"100%\">";
}
else if(startsWith(xmlLines[i],"</rows>"))
{
returnTable += "</tbody></table>";
}
else if(startsWith(xmlLines[i],"<head>"))
{
returnTable += "<thead><tr>";
}
else if(startsWith(xmlLines[i],"</head>"))
{
returnTable += "</tr></thead><tbody>";
}
else if(startsWith(xmlLines[i],"<column"))
{
returnTable += "<th>"+xmlLines[i].match(/>(.*?)</i)[1]+"</th>";
}
else if(startsWith(xmlLines[i],"<row"))
{
returnTable += "<tr>";
}
else if(startsWith(xmlLines[i],"</row"))
{
returnTable += "</tr>";
}
else if(startsWith(xmlLines[i],"<cell"))
{
returnTable += "<td>"+xmlLines[i].match(/>(.*?)</i)[1]+"</td>";
}
console.log(returnTable);
}
return returnTable ;
}
Please advice on how to achieve this. I am sorry if you have not understood my question so please ask me again. I am only using HTML and JS for couple of months so i am band new to this and that also might be the reason why my question might sound silly to some of you so sorry in advance. I apologize for my poor english please let me know if you dont understand. Thanks.
Updating the table every 3 seconds could cause performance issues, especially if you have lots of rows!
If you want to do it, you can iterate through the rows in the update XML and then write the values to the individual cells in the table.
DEMO
In my example, the table is already there with row ids as data attributes on the row element. I am updating once on a button click instead of every 3 seconds on a timer, but the parsing would be the same.
$("#update").on("click", function(){
var $trows= $('#example tbody tr');
var xmlDoc = $.parseXML( xmlstring );
var $xml = $( xmlDoc );
$xml.find("row").each(function(index){
var id = $(this).prop("id");
var $cells = $(this).find("cell");
var c1 = $cells.eq(0).text();
var c2 = $cells.eq(1).text();
var c3 = $cells.eq(2).text();
//get row in table with this id
var $rowtd = $('#example tbody [data-id=' + id + '] td');
$rowtd.eq(0).text(c1);
$rowtd.eq(1).text(c2);
$rowtd.eq(2).text(c3);
});
});
The code loads the XML string into an XmlDocument and then creates a jQuery object from the document. Next I iterate through all the Xml Nodes called "row" getting the id and the 3 cell texts. Then I find the row in the existing table with the same Id and write the texts into the existind TDs in the row.
You will need to test the performance of this given the normal number of rows you have and the types of devices you plan to support.