How not Javascript printing my textbox button and print my photo? - javascript

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!

Related

Pass only selected checkboxes and attributed input textboxes via jQuery?

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();

Javascript state change reverting

I have a simple jQuery app to display images from Giphy based on an ajax call, and toggle animate/stop them on mouseclick by toggling the src URL and data-state attributes.
I'm also displaying a different set of images based on user input.
I have a bug where it only animates gifs displayed after the first ajax call. It doesn't animate gifs displayed by subsequent calls. console-logging for each condition makes me think that for the latter it changes the state and changes it back, but I can't wrap my head around why.
Screencap: https://screencast.com/t/uZCzH6E6hZ8n
$('document').ready(function () {
//array with topics
var topics = [
"Ronaldinho",
"Zidan",
"Messi",
"Maradona",
"Pele"
]
//function loop to display all topics in buttons
function displayTopics() {
for (var i = 0; i < topics.length; i++) {
$('#buttons').append('<div class="btn btn-info get-giphy" data-attribute=' + topics[i] +
'>' + topics[i] +
'</div>');
}
}
//call function to display all the topic buttons
displayTopics();
//on clicking button
$('#buttons').on('click', '.get-giphy', function () {
$('#gifs-appear-here').empty();
//set topic to the clicked button's data-attribute
var topic = $(this).attr('data-attribute');
//set query URL to picked topic
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic +
"&api_key=O2X0wRMnWEjylyUypx1F5UVxCz5Jp8kr&limit=10";
//ajax call to Giphy API
$.ajax({
url: queryURL,
method: 'GET'
}).then(function (response) {
console.log(response);
// Storing an array of results in the results variable
var results = response.data;
// Looping over every result item
for (var i = 0; i < results.length; i++) {
// Only taking action if the photo has an appropriate rating
if (results[i].rating !== "r") {
// Creating a div with the class "item"
var gifDiv = $("<div class='item'>");
// Storing the result item's rating
var rating = results[i].rating;
// Creating a paragraph tag with the result item's rating
var p = $("<p>").text("Rating: " + rating);
// Creating an image tag
var topicImage = $("<img>");
// Giving the image tag necessary attributes
topicImage.attr({
"class": "topicImage",
"src": results[i].images.fixed_height_still.url,
"data-state": "still",
"data-still": results[i].images.fixed_height_still.url,
"data-animate": results[i].images.fixed_height.url
});
// Appending the paragraph and personImage we created to the "gifDiv" div we created
gifDiv.append(topicImage);
gifDiv.append(p);
// Prepending the gifDiv to the "#gifs-appear-here" div in the HTML
$("#gifs-appear-here").prepend(gifDiv);
}
}
});
$('#gifs-appear-here').on('click', '.topicImage', function () {
var state = $(this).attr("data-state");
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
console.log('still --> animate');
} else if (state === "animate") {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
console.log('animate --> still');
}
else {
return false;
}
});
});
//add buttons
$('button[type="submit"]').click(function () {
var inputValue = $('.form-control').val().trim();
//don't add buttons if they're already in topics array
if (topics.includes(inputValue)) {
$('.modal').modal('show');
$('.modal-body').html('You already have a button for <b>' + inputValue +
'</b>. Use it or add something else');
setTimeout(function () {
$('.modal').modal('hide');
}, 4000);
//add buttons if they aren't in the topics array
} else {
topics.push(inputValue);
$('#buttons').empty();
displayTopics();
}
});
//get form input on pressing "enter key"
$('.form-control').keypress(function (e) {
if (e.which == 13) { //Enter key pressed
$('button[type="submit"]').click(); //Trigger search button click event
}
});
});
.row {
margin-top: 30px;
}
.col {
background-color: #eee;
padding: 15px;
border-radius: 10px;
}
.get-giphy {
margin: 0 15px 15px 0;
}
.topicImage {
max-width: 100%;
}
#media all and (min-width: 768px) {
#buttons {
border-right: 15px solid #fff;
}
#formWrap {
border-left: 15px solid #fff;
}
}
#media all and (max-width: 768px) {
#buttons {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
#formWrap {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
#media all and (max-width: 575px) {
.row {
margin-left: 0;
margin-right: 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="main.js"></script>
<title>Homework 6</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col col-12">
<h1>Who's your favorite Futbol star?</h1>
</div>
</div>
<div class="row">
<div id="buttons" class="col col-12 col-md-6 col-lg-6">Click a button!
<br>
<br>
</div>
<div id="formWrap" class="col col-12 col-md-6 col-lg-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="You can also add more buttons!">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<div class="row">
<div id="gifs-appear-here" class="col col-12">
Your gifs will appear here
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="answerModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Not so fast!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</body>
</html>
As it stands, ('#gifs-appear-here').on('click', '.topicImage', ...) is executed inside the buttons' onclick handler, causing that delegated click handler to accumulate every time one of the buttons is clicked.
To fix, simply move ('#gifs-appear-here').on('click', '.topicImage', ...) out of the buttons' onclick handler.
Here it is (significantly tidied) :
$('document').ready(function () {
var topics = [
"Ronaldinho",
"Zidan",
"Messi",
"Maradona",
"Pele"
];
function displayTopics() {
for (var i = 0; i < topics.length; i++) {
$('#buttons').append('<div class="btn btn-info get-giphy" data-attribute=' + topics[i] + '>' + topics[i] + '</div>');
}
}
displayTopics();
$('#buttons').on('click', '.get-giphy', function () {
$('#gifs-appear-here').empty();
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + $(this).data('attribute') + "&api_key=O2X0wRMnWEjylyUypx1F5UVxCz5Jp8kr&limit=10";
$.ajax({
'url': queryURL,
'method': 'GET'
}).then(function (response) {
var results = response.data;
for (var i = 0; i < results.length; i++) {
if (results[i].rating !== "r") {
var gifDiv = $("<div class='item'/>").prependTo("#gifs-appear-here");
$("<img class='topicImage'/>").attr({
'src': results[i].images.fixed_height_still.url
}).data({
'state': 'still',
'images': results[i].images
}).appendTo(gifDiv);
$('<p/>').text("Rating: " + results[i].rating).appendTo(gifDiv);
}
}
});
});
$('#gifs-appear-here').on('click', '.topicImage', function () {
var data = $(this).data();
if (data.state === 'still') {
$(this).attr('src', data.images.fixed_height.url);
data.state = 'animate';
} else {
$(this).attr('src', data.images.fixed_height_still.url);
data.state = 'still';
}
});
//add buttons
$('button[type="submit"]').click(function () {
var inputValue = $('.form-control').val().trim();
//don't add buttons if they're already in topics array
if (topics.includes(inputValue)) {
$('.modal').modal('show');
$('.modal-body').html('You already have a button for <b>' + inputValue + '</b>. Use it or add something else');
setTimeout(function () {
$('.modal').modal('hide');
}, 4000);
//add buttons if they aren't in the topics array
} else {
topics.push(inputValue);
$('#buttons').empty();
displayTopics();
}
});
//get form input on pressing "enter key"
$('.form-control').keypress(function (e) {
if (e.which == 13) { //Enter key pressed
$('button[type="submit"]').click(); //Trigger search button click event
}
});
});
.row {
margin-top: 30px;
}
.col {
background-color: #eee;
padding: 15px;
border-radius: 10px;
}
.get-giphy {
margin: 0 15px 15px 0;
}
.topicImage {
max-width: 100%;
}
#media all and (min-width: 768px) {
#buttons {
border-right: 15px solid #fff;
}
#formWrap {
border-left: 15px solid #fff;
}
}
#media all and (max-width: 768px) {
#buttons {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
#formWrap {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
}
#media all and (max-width: 575px) {
.row {
margin-left: 0;
margin-right: 0;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<link rel="stylesheet" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
crossorigin="anonymous"></script>
<script src="main.js"></script>
<title>Homework 6</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col col-12">
<h1>Who's your favorite Futbol star?</h1>
</div>
</div>
<div class="row">
<div id="buttons" class="col col-12 col-md-6 col-lg-6">Click a button!
<br>
<br>
</div>
<div id="formWrap" class="col col-12 col-md-6 col-lg-6">
<div class="form-group">
<input type="text" class="form-control" placeholder="You can also add more buttons!">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
<div class="row">
<div id="gifs-appear-here" class="col col-12">
Your gifs will appear here
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="answerModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Not so fast!</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
</div>
</div>
</div>
</div>
<script type="text/javascript">
</script>
</body>
</html>

how to add fade in and fade out

I am stuck with my project.
I need to add to the code below fade-in and fade-out effect by using javascript and css only. please help me.
I created this function to store all the data in the local storage and when I am clicking on the save button I want the note to be added with fade in effect. when I am deleting the note I want it to be deleted in fade out. only the note I am adding or deleting will be added or removed with the effect
this is the function to add the note:
function saveIt() {
var content = document.getElementById("content").value;
var date = document.getElementById("date").value;
var time = document.getElementById("time").value;
var id = Math.floor(Math.random() * 100000); //creating random id number.
var note = { id: id, content: content, date: date, time: time };
notesArray.push(note);
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
for (var i = 0; i < notesNewArray.length; i++) {
theId = notesArray[i].id;
var output = "<div id='justFade'>" + "<div class='main col-xm-12 col-sm-6 col-md-4 col-lg-3'>" + "<div class='note-bg'>" + "<div id='" + theId + "'" + "onclick='deleteNote(this.id)'>" + "<p id='hide-delete' class='glyphicon glyphicon-remove-circle'></p>" + "</div>" + "<div class='noteContent'>" + notesNewArray[i].content + "</div>" + "<div class='noteDate'>" + notesNewArray[i].date + "</div>" + "<div>" + notesNewArray[i].time + "</div>" + "</div>" + "</div>" + "</div>";
}
document.getElementById("results").innerHTML += output;
document.getElementById("msg").innerHTML = ""; //to hide the message for the empty note.
document.getElementById("msgDate").innerHTML = ""; //to hide the message for the empty or wrong date.
document.getElementById("msgTime").innerHTML = ""; //to hide the message for the empty or wrong date.
document.forms['myNotes'].reset(); //reseting the form on saving.
function deleteNote(clickedId) {
var myList = localStorage.myList;
notesArray = JSON.parse(myList);
for (var i = 0; i < notesArray.length; i++) {
if (notesArray[i].id == clickedId) {
notesArray.splice(i, 1); // searching for the same ID number that the user clicked on and deleting it.
}
localStorage.myList = JSON.stringify(notesArray);
notesNewArray = JSON.parse(localStorage.myList);
document.getElementById("results").innerHTML = "";
getIt(); // calling again to the notes from the local storage.
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Project</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
</head>
<body id="init">
<div class="center">
<img src="img/title.png" class="img-center" alt="My Task Board" width="876" height="225">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form id="myNotes" name="myNotes">
<div class="form-group">
<textarea rows="8" name="myContent" cols="100" class="form-control" id="content" placeholder="type your note here..." required></textarea><br>
<div><input type="date" class="form-control" id="date" required></div>
<div><input type="time" class="form-control" id="time" required></div>
<input type="submit" class="btn btn-primary" id="save" value="save">
<div id="msg"></div>
<div id="msgDate"></div>
<div id="msgTime"></div>
</div>
</form>
</div>
<div class="col-sm-4"></div>
</div>
</div>
<div id="results" class="singleNote"></div>
<script src="js/myscript.js"></script>
</body>
</html>
thank you.
You can use jquery to solve this problem. For any element that requires to fade in or out you can do this...
$("#div1").fadeIn();
$("#div1").fadeOut();
Here is a link that explains...
Jquery fade in and out
You need to make two async functions fadeIn() and fadeOut() and a function to return a promise.
With async you are solving the function asynchronously meaning other code can continue executing and doesn't have to wait for the return of a priorly called function to start it's execution. Because of this they appear to fade in and out at the same time even though they are called by 4 different lines of code.
Here is a quick example of fade in and fade out done in plain javascript:
(Run the snippet at the bottom of the code)
function sleep(ms)
{
return new Promise(resolve => setTimeout(resolve, ms));
}
async function fadeIn(elmnt)
{
for(var i=0; i<101; i++)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20); // Play with the sleep time to suit your needs, in miliseconds
}
}
async function fadeOut(elmnt)
{
for(var i=100; i > -1; i--)
{
document.getElementById(elmnt).style.opacity = i/100;
await sleep(20);
}
}
// Simply call the functions anywhere you want like this
fadeIn('fade_1');
fadeIn('fade_2');
fadeOut('fade_3');
fadeOut('fade_4');
.opacityZero
{
opacity:0;
}
.opacityOne
{
opacity:1;
}
.firstDiv
{
position:relative;
float:left;
width:97%;
border:1px solid #000;
padding:5px;
}
.secondDiv
{
position:relative;
float:left;
width:98%;
border:1px solid #000;
padding:5px;
}
.container
{
position:relative;
float:left;
width:95%;
margin-top:20px;
border:1px solid #09f;
padding:10px;
}
h3
{
font-family:calibri;
position:relative;
float:left;
}
<h3>Fade in effect</h3>
<div id="fade_1" class="firstDiv opacityZero">hi</div>
<div class="container">
<span id="fade_2" class="secondDiv opacityZero">hi</span>
</div>
<h3 style="margin:20px 0 0;">Fade out effect</h3>
<div id="fade_3" class="firstDiv opacityOne">hi</div>
<div class="container">
<span id="fade_4" class="secondDiv opacityOne">hi</span>
</div>

How to popup a modal on click of each item which are generated dynamically?

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');
});
});

how to convert image into byte array in jsp/javascript

hi i am acquiring the image from the scanner device successfully i want to store that image in data base i am thinking that i need to convert into byte array then pass to controller but i am not able to convert that image into byte array.
can any one please suggest me that is it right approach or not,if it is wrong then what is the alternate way please help me.
this is my code.
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html lang="en">
<head>
<title>Scanning documets</title>
<script type="text/javascript"
src="http://direct.asprise.com/scan/javascript/base/scanner.js"></script>
<!-- required for scanning -->
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!-- optional -->
<link href="http://getbootstrap.com/dist/css/bootstrap.min.css"
rel="stylesheet">
<!-- optional -->
<style type="text/css">
img.zoom {
margin-right: 4px;
}
body {
margin: 20px 10px;
}
</style>
<script>
// -------------- Optional status display, depending on JQuery --------------
function displayStatus(loading, mesg, clear) {
$('#info').empty(); // jQuery is used
if (loading) {
$('#info')
.html(
(clear ? '' : $('#info').html())
+ '<p><img src="http://asprise.com/legacy/product/_jia/applet/loading.gif" style="vertical-align: middle;" hspace="8"> '
+ mesg + '</p>');
} else {
$('#info').html((clear ? '' : $('#info').html()) + mesg);
}
}
// -------------- scanning related code: independent of any 3rd JavaScript library --------------
/* function scanSimple() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SIMPLE_SCAN, // simple scan without the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
null);
}
*/
function scan() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN, // normal scan with the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS, {
'wia-version' : 2
});
}
/* function scanThenUpload() {
displayStatus(true, 'Scanning', true);
com_asprise_scan_request(myCallBackFunc,
com_asprise_scan_cmd_method_SCAN_THEN_UPLOAD, // scan and then upload directly in the applet UI
com_asprise_scan_cmd_return_IMAGES_AND_THUMBNAILS,
{
'upload-url': 'http://asprise.com/scan/applet/upload.php?action=upload' // target URL
,'format': 'PDF'
});
} */
/** Use this callback function to get notified about the scan result. */
function myCallBackFunc(success, mesg, thumbs, images) {
var logText;
displayStatus(false, '', true);
logText = 'Callback function invoked: success = ' + success
+ ", mesg = " + mesg;
logText += '\nThumbs: ' + (thumbs instanceof Array ? thumbs.length : 0)
+ ", images: " + (images instanceof Array ? images.length : 0)
+ ",image name" + (images instanceof Array ? images.name : 0);
logToConsole(logText, !(success || mesg == 'User cancelled.'));
displayStatus(false, '<pre>' + logText + '</pre>', true);
for (var i = 0; (images instanceof Array) && i < images.length; i++) {
addImage(images[i], document.getElementById('images'));
}
}
/** We use this to track all the images scanned so far. */
var imagesScanned = [];
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
var elementImg = createDomElementFromModel({
'name' : 'img',
'attributes' : {
'src' : imgSrc,
'height' : '100',
'class' : 'zoom'
}
});
$('<input>').attr({
type : 'hidden',
name : '',
})
$('#imageData').val(imgSrc);
domParent.appendChild(elementImg);
// optional UI effect that allows the user to click the image to zoom.
enableZoom();
}
function submitForm1() {
displayStatus(true, "Submitting in progress, please standby ...", true);
com_asprise_scan_submit_form_with_images('form1', imagesScanned,
function(xhr) {
alert("image :" + imagesScanned);
if (xhr.readyState == 4) { // 4: request finished and response is ready
displayStatus(false,
"<h2>Response from the server: </h2>"
+ xhr.responseText, true);
alert("before");
document.getElementById("form1").submit();
}
});
}
</script>
</head>
<body style="margin: 10px 30px;">
<div
style="display: block; position: absolute; right: 30px; top: 20px;">
<!-- <a href="http://asprise.com/" target=_blank> <img src="http://asprise.com/res/img/nav/logo.fw.png"/> </a> -->
</div>
<h2></h2>
<!-- <p style="color: #9eadc0;">For evaluation purpose only. Please order a license from <a href="http://asprise.com/" target=_blank>asprise.com</a>
| View source code of this page
</p> -->
<div class="panel panel-info" style="margin: 20px 0px;">
<div class="panel-heading">
<h3 class="panel-title">Scann your docs:</h3>
</div>
<div class="panel-body">
<form id="form1" action="<c:url value='/upload'/>" method="POST"
enctype="multipart/form-data" target="_blank">
<!-- <label for="field1"
style="display: inline-block; width: 150px; text-align: right;">Field
1</label> <input id="field1" name="field1" type="text" value="value 1" /> <input
type="file" name="file" /> <br> -->
<span style="height: 4px;"></span><br> <label
style="display: inline-block; width: 150px; text-align: right;">Documents</label>
<button type="button" class="btn btn-info" onclick="scan();">Scan</button>
<!-- <button type="button" class="btn btn-default" onclick="scanSimple();">Simple Scan</button>
<button type="button" class="btn btn-default" onclick="scanThenUpload();">Scan Then Upload</button> -->
<div id="images" style="margin-left: 154px; margin-top: 10px;">
<input type="hidden" name="imageName" value="" />
</div>
<input type="button" class="btn btn-primary" value="Submit form"
onclick="submitForm1();"
style="margin-left: 154px; margin-top: 20px;">
</form>
</div>
</div>
<div id="info" class="well"
style="display: block; background-color: #fff; height: 500px; margin-top: 12px; padding: 12px; overflow: scroll;">
<p>
<i>Information window</i>
</p>
</div>
<script src="http://yyx990803.github.io/zoomerang/zoomerang.js"></script>
<script>
function enableZoom() {
Zoomerang.config({
maxWidth : window.innerWidth, // 400,
maxHeight : window.innerHeight, // 400,
bgColor : '#000',
bgOpacity : .85
}).listen('.zoom');
}
</script>
</body>
</html>
You can get the image binary in BASE64 format. The imgObj.data in below code is the BASE64 format of image object:
function addImage(imgObj, domParent) {
imagesScanned.push(imgObj);
var imgSrc = imgObj.datatype == com_asprise_scan_datatype_BASE64 ? 'data:'
+ imgObj.mimetype + ';base64,' + imgObj.data
: imgObj.data;
...
To get the actual binary bytes, you can use:
var bin = window.atob(imgObj.data)
For a complete discussion of converting BASE64 to binary, please refer to: Base64 encoding and decoding in client-side Javascript
For a complete usage of scanner.js, you may consult Developer guide to scanner.js: cross-Browser HTML/JavaScript Scanning - Acquires images from scanners to web pages (Java, C# ASP.NET, PHP)

Categories