Show image preview after image upload - ruby-on-rails

My view contains detail of various employees and I have to upload image for each and save at last.I want to see image preview for each image before save but it takes localhost path and do not show image preview.
It's showing error :"NetworkError: 404 Not Found -localhost:3000/rails.png"
In View
<% #person.each do |person| %>
<td><%= person.name %></td>
<td><%= person.date %></td>
<td><input id="<%= person.id %>" type='file' class="imageUploader" multiple="true" ></td>
<td class="image_container"> <img id="image_<%= person.id %>" src="#" alt="Image" width="100" height="100"></td>` here
</tr>
<% end %>
In appliction.js::
$('.imageUploader').change(function() {
var target_image = $(this).val();
$(this).parent('td').parent("tr").children('td.image_container').html("<img src="+target_image+">");
console.log(target_image);
});

Guyz,
Got another one.............`
FILEFIELD = {}
$(document).ready(function() {
$('.files').change(function() {
FILEFIELD = $(this)
var fr = new FileReader;
fr.onload = function() {
var img = new Image;
img.onload = function() {
var c=$(FILEFIELD).parent("td").parent("tr").children("td").children(".images")[0];
var ctx=c.getContext("2d");
ctx.drawImage(img,0,0,50,50);
}
img.src = fr.result;
};
fr.readAsDataURL(this.files[0]);
});
});
And finally working

Well I tried for what you said and got the image preview in my application doing so:
My view:
<% if current_user %>
<p>Welcome <%= current_user.email %></p>
<tr><input type="file" id="files" name="files[]" multiple />
<img id="list" src="#" alt="Image" width="100" height="100"></img></tr>
<% end %>
<style>
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script type="text/javascript">
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList and render image files as thumbnails.
for (var i = 0, f; f = files[i]; i++) {
// Only process image files.
if (!f.type.match('image.*')) {
continue;
}
var reader = new FileReader();
// Closure to capture the file information.
reader.onload = (function(theFile) {
return function(e) {
// Render thumbnail.
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="', e.target.result,
'" title="', escape(theFile.name), '"/>'].join('');
document.getElementById('list').insertBefore(span, null);
};
})(f);
// Read in the image file as a data URL.
reader.readAsDataURL(f);
}
}
document.getElementById('files').addEventListener('change', handleFileSelect, false);
</script>
As you see above code is done by me taking into account a single user image preview before upload. But the same you can do for multiple users by changing the query and a little code for multiple users.
Cheers!

Related

Printing repeated watermark background image inside an html table

I have a web page that contains a repeated background image, but when i try to print the page using ctrl + p its showing page print preview without background.
Could you please tell me how to force to print the background?
Here's a fiddle: http://jsfiddle.net/qzw639e4/5/
the system has more than one language, therefore, it's necessary to create the image dynamically. It's the reason that I am using a html canvas for this.
function AppViewModel() {
var self = this;
self.items = ko.observableArray([]);
for(var i = 0; i< 10; i++){
var item ={
id: i,
description: 'test'+i,
cost: i*5,
price: i*8,
PriceToCustomer: i*10
}
self.items.push(item);
}
self.print = function(){
window.print();
}
var canvas = document.createElement('CANVAS');
var ctx = canvas.getContext('2d');
canvas.width = "500";
canvas.height = "400";
ctx.font = '15pt Arial';
ctx.save();
ctx.translate(100, 400);
ctx.rotate(-45 * Math.PI / 180);
ctx.fillStyle = "red";
ctx.globalAlpha = 0.3;
var rText = "This text must be a repeated background image.";
ctx.fillText(rText, 0, 0);
ctx.restore();
$('tbody').css('background-image', 'url(' + ctx.canvas.toDataURL() + ') ');
}
ko.applyBindings(new AppViewModel());
I tested the solution below and the bg was correctly printed by the browser:
<body>
<div id="background">
<p id="bg-text"> Sample Background</p>
</div>
<div id="content">
Content of the page goes here.....................
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<p>HI TO EVERBODY </p>
</div>
#background{
position:absolute;
z-index:0;
background:white;
display:block;
min-height:50%;
min-width:50%;
color:yellow;
}
#content{
position:absolute;
z-index:1;
}
#bg-text
{ margin: -900px;
color:lightgrey;
font-size:60px;
transform:rotate(300deg);
-webkit-transform:rotate(300deg);
}
https://codepen.io/YuvarajTana/pen/auiqx
The example is not a repeated background, but with some adjustments maybe it becomes suitable for your need.

GAS PropertiesService to Save and Return Sort Order

QUESTION
How can I use PropertiesService to store an array from index.html, send the array to code.gs, and return the array in index.html?
SPECIFIC CASE
In a Google Web App, I have a group of sortable lists (made using JQuery UI Sortable). I want to save the most recent order/position of each li. I'm attempting to have that order/position "persist" when the page is refreshed or closed.
EXAMPLE
If you see the default Sortable, you could change the order of the items. If you refreshed the page, or closed it and return, the items would be in their original order.
WHERE I'M HAVING TROUBLE
I am able to get the array to show up in the console, but I don't know how to get it back to code.gs. I think I am now, but I'm not sure. Beyond that, I don't know how to "read" that PropertiesService so that the array is returned to index.html. I'm not really sure what I'm doing so if someone could slow walk me it would be appreciated!
ALTERNATIVES
I also looked into writing directly to the spreadsheet where the values originate. I'm not really sure how to do that either. I made some attempts, and was able to get "undefined" as a value in a spreadsheet cell.
FULL CODE (note: the list items are formed using an array, so they will not show up here): https://jsfiddle.net/nateomardavis/Lmcjzho2/1/
PARTIAL CODE
code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function webAppTest() {
getTeamArray();
}
function getTeamArray() {
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('TEST');
var range = sheet.getRange(2, 1, 1000, 1);
var values = range.getValues();
var teamsArray = [];
for (var i = 0; i < values.length; ++i) {
teamsArray.push(values[i][0]);
}
var uniqueArray = [];
uniqueArray.push(teamsArray[0]);
for (var i in teamsArray) {
if ((uniqueArray[uniqueArray.length - 1] != teamsArray[i]) && (teamsArray[i] !== "")) {
uniqueArray.push(teamsArray[i]);
}
}
return uniqueArray;
}
function savePositions(myProperty, positions) {
PropertiesService.getScriptProperties().setProperty("myProperty", JSON.stringify(positions));
};
function getPositions() {
var returnedObj = PropertiesService.getScriptProperties()
};
index.html
<body>
<div id="myList" class="connectedSortable">MY LIST</div>
<table id=table1>
<div id="team1">
<p>TEAM 1</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team1s" name='team1s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team1a" name='team1a' class="connectedSortable"></ul>
</div>
</table>
<table id=table2>
<div id="team2">
<p>TEAM 2</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team2s" name='team2s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team2a" name='team2a' class="connectedSortable"></ul>
</div>
</table>
<table id=table3>
<div id="team3">
<p>TEAM 3</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team3s" name='team3s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team3a" name='team3a' class="connectedSortable"></ul>
</div>
</table>
<table id=table4>
<div id="team4">
<p>TEAM 4</p>
<br>
<div id="group" v>SELECTED</div>
<ul id="team4s" name='team4s' class="connectedSortable"></ul>
<div id="group">ALTERNATE</div>
<ul id="team4a" name='team4a' class="connectedSortable"></ul>
</div>
</table>
<script>
$(function() {
google.script.run.withSuccessHandler(buildOptionsList)
.getTeamArray();
});
function buildOptionsList(uniqueArray) {
var div = document.getElementById('myList');
for (var i = 0; i < uniqueArray.length; i++) {
var ul = document.createElement('ul');
var li = document.createElement('li');
var cLass = li.setAttribute('class', 'ui-state-default');
var iD = li.setAttribute('id', uniqueArray[i]);
li.appendChild(document.createTextNode(uniqueArray[i]));
div.appendChild(ul);
div.appendChild(li);
}
}
$(function() {
$("#myList, #team1s, #team1a, #team2s, #team2a, #team2s, #team3s, #team3a, #team4s, #team4a").sortable({
connectWith: ".connectedSortable",
update: function(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
//Instead of using JSON to save, can I use the spreadsheet itself to save the positions and then pull it from there as I did with "buildOptionsList" above?
function saveList() {
google.script.run.savePositions("myProperty", JSON.stringify(positions));
JSON.parse("myProperty");
}
}
})
});
$(function getPositions(event, ui) {
var changedList = this.id;
var order = $(this).sortable('toArray');
var positions = order.join(';');
console.log({
id: changedList,
positions: positions
});
});
</script>
</body>
</html>
It's also possible to just use the browser's localStorage client side.
localStorage.setItem('id', positions); //Store positions in users browser
localStorage.getItem('id'); //Retrieve the stored positions later
Notes:
For this to work, the url(document.domain of the iframe="*.googleusercontent.com") from which your script is deployed must remain constant. During my brief testing, it was constant even when changing from /dev to /exec of the parent(script.google.com) and even during version update. But there's no official reference.
This solution is better than properties service, if you have multiple users, as each one will have their own data stored in their own browsers and there are no server calls during each change.
Using google.script.run simple example:
<script>
function sendStringToServer() {
var string=$('#text1').val();
google.script.run
.withSuccessHandler(function(s){
alert(s);
})
.saveString(string);
}
</script>
Google Script:
function myFunction() {
PropertiesService.getScriptProperties().setProperty('MyString', string);
return "String was saved in Service";
}
Client to Server Communication

How to let user know the resume they are submitting is too large

my cshtml file for upload, where would the javacsript go in this file?
#{
ViewBag.Title = "Upload";
}
<div id="progressbar">
<div id="progressbar" class="all-rounded" style="width: 20%"><span></span></div>
</div>
<div class="jumbotron">
<h2>Job Application Management System</h2>
<p class="lead2"> Welcome #((string)(ViewData["FullName"])), Please upload your resume here. Thank you!</p>
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td> <label> </label> <input type="file" class="btn btn-default" name="File" id="File" /></td>
</tr>
<tr>
<td><input type="submit" class="btn btn-default" id="upload" value="Upload" /></td>
</tr>
</table>
if (TempData["notice"] != null)
{
<p>#TempData["notice"]</p>
<p><button class="btn btn-default" onclick="location.href='#Url.Action("Create", "Accomplishments")';return false;">Continue To Accomplishments</button></p>
}
}
Here is my working code that shows how to accept a resume and save it using asp.net mvc
How do I post an error message stating that the file size is too large if the user submits a file that cannot be handled. Right now, if a user submits a file too large, it takes them to an errors page. I just want a popup or something on the screen that tells them to submit a file that is smaller. Thanks!
if (resume.File.ContentLength > 0)
{
string fileName = Path.GetFileName(resume.File.FileName);
string path = Path.Combine(Server.MapPath("~/Content/Resumes"), fileName);
resume.File.SaveAs(path);
}
TempData["notice"] = "Resume Added: "+ resume.File.FileName;
return View(resume);
}
catch (Exception)
{
ViewBag.Message = "Upload Error";
return View("Upload");
}
}
You can do this with simple javascript :
<script type="text/javascript">
$('#image-file').on('change', function() {
var filesize = this.files[0].size/1024/1024).toFixed(2) + " MB");
//Now can use use filesize variable and check it's value and show pop.
});
</script>
OR you can use this :
function GetFileSize(fileid) {
try {
var fileSize = 0;
//for IE
if ($.browser.msie) {
//before making an object of ActiveXObject,
//please make sure ActiveX is enabled in your IE browser
var objFSO = new ActiveXObject("Scripting.FileSystemObject"); var filePath = $("#" + fileid)[0].value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
fileSize = fileSize / 1048576; //size in mb
}
//for FF, Safari, Opeara and Others
else {
fileSize = $("#" + fileid)[0].files[0].size //It will calculate file size in kb
// Put Your Alert or Validation Message Here
}
}
catch (e) {
alert("Error is :" + e);
}
}
Or you can check file size on form submit as:
<script type="text/javascript">
$(document).ready(function(){
$('#upload').on('click', function(e) {
e.PreventDefault();
var filesize = $("#File").files[0].size/1024/1024).toFixed(2)); //filesie in MB
//Now can use use filesize variable and check it's value and show pop.
if(parseInt(filesize)>3){ alert("File too large");return false; }
else{ $("form").submit(); }
});
});
</script>

Jquery Mobile val() returns undefined after changePage

I have 2 pages that I'm working with: first being the page where the values are being fetched from php server and populating the selects/inputs and the second page being a dialog box that fetches the value from the hidden inputs in the first page. The first transition opens the dialog box and fetches the values properly. After which I save the values in php session and reload the first page. After this process when I open the dialog box again the jquery is not able to fetch val() and shows undefined. I'm not sure if this is due to some reloading of the page issue or something else. If I refresh the page then it will work fine again.
<div data-role="page" id="page1">
<div data-theme="a" data-role="header">
.....
<div data-role="navbar" data-iconpos="top">
.....
</div>
<div data-theme="c" id="cashtab" data-role="content">
<div style="display:none" id="proddata" data=""></div>
<div style="display:none" id="prodstock" data=""></div>
<form id="mainsubmit" action="form.php" method="post" data-ajax="false">
<input id="formproduct" type="hidden" name="product" value=""/>
<div id="productsearch" style="width:48%; float:left; margin-right:2%;">
<label for="search">Search Product:</label><br/><br/>
<ul id="productautocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Select a product... (type at least 3 letters)" data-filter-theme="d"></ul>
</div>
<div id="packingselect" style=" width:23%; float:left; margin-right:2%;">
<label for="packing">Select Packing:</label>
<select name="packing" id="packing" data-iconpos="left">
</select>
</div>
<div id="qtyenter" style=" width:23%; float:left; margin-right:2%;">
<label for="quantity">Select Qty:</label>
<input type="number" data-clear-btn="true" name="quantity" id="qty" value=""/>
</div><br/><br/><br/><br/><br/><br/><br/><br/>
<div style="display:inline-block; width:33%; margin-left:33%; margin-right:33%;">
<a href="#page3" data-rel="dialog" data-role="button" >ADD</a>
</div>
</form>
</div>
</div>
<div data-role="page" id="page3" data-url="dialog.html" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<!--data populated from server once the values from first page is read properly.
<!-- currently not loading the second time as unable to fetch val() -- >
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<!-- function the send the checked checkboxes relavent info to store in session -->
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
<script>
$( document ).on( "pageinit", "#page1", function() {
//for product select autopopulate -- working //
$("#productautocomplete").live( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),$input = $( data.input ),value = $input.val(),html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.getJSON('ajax/getProductList.php', {term:$input.val()}, function(data) {
var items = [];
var str = "";
for (var key in data) {
if (data.hasOwnProperty(key)) {
var value = data[key].value;
var label = data[key].label;
var stock = data[key].stock;
var proddata = data[key].data;
str += '<li code="'+value+'" name="'+label+'" stock="'+stock+'" data="'+proddata+'">';
str += '<a data-ajax="false" rel="external">'+label+' [ '+stock+' ]</a>';
str += '</li>';
}
}
$ul.html( str );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout" );
});
}
});
//end search
//on click set hidden input fields to be used in dialog box. -- working
$('#productautocomplete li').live('click', function(e) {
//--------------------fetch data ------------------------
var id = $(this).attr('code');
var name = $(this).attr('name');
var data = $(this).attr('data');
var stock = $(this).attr('stock');
//add packaging type and unit info to div data
$('#proddata').attr('data',data);
//add currstock info to div
$('#prodstock').attr('data',stock);
//----------------------hide list
$('#productautocomplete li').hide();
//----------------------place name in visible input box
$('#productsearch input').attr('value',name);
//----------------------place id in hidden input box for the actual form.
$('#formproduct').val(id);
//----------------------fill options for package + show select package div
var filteroptions = data.split(",");
$('#packing option').remove();
for (var x=0; x<3 ; x++) {
var eachoption = filteroptions[x].split(":");
//if unit wise option is less than that of stock show as option.
if (eachoption[0]!="0" && eachoption[0] <= stock.valueOf()) {
$('#packing').append($('<option>', {
value: eachoption[0]+':'+eachoption[1],
text : eachoption[1]+' [ '+eachoption[0]+' ] '
}));
}
}
});
});
//this is where the problem lies ..
//have tried with pageinit.. but that only calls it once.
$( document ).on( "pageshow", "#page3", function() {
$('#batchsel tbody').empty();
// !!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!! //
//doesnt fetch any of 4 following values after pageChange back to page1.
//not sure if this is due to how i'm reloading the page1.
//see function addProduct below.
var prodcode = $('#formproduct').val(); //
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
//returns undefined
alert(prodcode); alert(packing); alert(prodqty);
//always ends here when dialog opens second time.
if (!prodcode || !packing || !prodqty) {
alert("Please give all required information");
//does not close also when opens the second time.
$('#page3').dialog('close');
}
var packinginfo = packing.split(":");
var totalrequired = prodqty * packinginfo[0];
//alert(packinginfo[1]);alert(totalrequired);
if (totalrequired > prodstock ) {
alert("Not enough Stock");
$('#page3').dialog('close');
} else {
//------------------------------ Getting Batch Info ---------------------------------------------------
var rows = '';
$.getJSON('ajax/getBatchDetails.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired}, function(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
//alert (data[key].Batch);
rows += '<tr><td><input type="checkbox" class="batchcheckbox" id="batchcheckbox_'+data[key].BatchId+'" value="'+data[key].BatchId+':'+data[key].Stock+'" onchange="resetRemainingQty(this.value);""/></td><td>' + data[key].Batch + '</td><td>' + data[key].ExDt +'</td><td>' + data[key].BRate + '</td><td>' + data[key].SRate + '</td><td>' + data[key].Pack + '</td><td>' + data[key].Stock + '</td><td>' + data[key].Supname + '</td><td>' + data[key].Stax + '</td><td>' + data[key].BillDt + '</td><td>' + data[key].BillNo + '</td><td>' + data[key].btax + '</td><tr>';
}
}
$('#batchsel tbody').append(rows);
//add remaining amount in the data field of p1.
$('#remainingdata p1').attr('data',totalrequired);
$('#remainingdata p2').attr('data',totalrequired);
$('#remainingdata p1').html("<h4>Remaining Amount : "+totalrequired+"</h4>");
});
//---------------------------------------------end batch info display: -----------------------------------
}
});
function addProduct() {
//--------code info---------
var prodcode = $("#formproduct").val(); // to send
//--------packing info---------------
var packing = $('#packing').find(":selected").val();
var packinginfo = packing.split(":");
//-----------qty req ---------------------
var prodqty = $('#qty').val();
var totalrequired = prodqty * packinginfo[0]; // to send
//-------------batch info -----------
var allbatchids = "";
$('.batchcheckbox').each(function() {
if($(this).is(':checked')){
var data = $(this).val();
var datasplit = data.split(":");
var batchid = datasplit[0];
allbatchids += batchid+":";
}
});
allbatchids = allbatchids.substring(0, allbatchids.length - 1); // to send
alert(prodcode+",,"+packinginfo[1]+",,"+totalrequired+",,"+allbatchids);
//-------------- send to server to save to session ---------
$.getJSON('ajax/saveProductSession.php', {code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids}, function(data) {
if (data.error == "1") {
alert(data.message);
} else {
/// !!!!!!!! !!!!!!!!!!!!!!! !!!!!!!!!!!!!!!
///
/// the loads the page1. but jquery doesnt take val() after this.
///tried multiple variations of this but to no effect.
///removed all options.. redirect to main.php.. reloadpage:false.. etc.
///Any other way to reload the page so that the dialog once open again can
///get the values from the page1 again.
$.mobile.changePage("#page1", { reloadPage: true , dataUrl : "page1", reverse : true, changeHash: true } );
}
});
//
// $.ajax({
// type: "POST",
// url: "ajax/saveProductSession.php",
// data: { code:prodcode,pack:packinginfo[1],qty:totalrequired,batch:allbatchids }
// }).done(function() {});
}
</script>
Ok ! I got it to work ! thanks anyway #Gajotres. Steps :
1a. Send out the variables from main.php through changePage :
var prodcode = $('#formproduct').val();
var prodstock = $('#prodstock').attr('data');
var prodqty = $('#qty').val();
var packing = $('#packing').find(":selected").val();
$.mobile.changePage('batch.php', {
role: 'dialog',
data: {'prodcode': prodcode,'prodstock': prodstock, 'prodqty' : prodqty , 'packing' : packing},
type: 'get'
});
2a. Moved the entire div id 'page3' to a new php page named 'batch.php' where I get the variables from php and set it to the html divs.
<?php
extract($_GET);
if (!$prodcode && !$prodstock && !$packing && !$prodqty) {
header('Location: '.DEF_SITEURL."main.php");
exit;
}
?>
<div data-role="page" id="batchpage" data-url="batch.php" data-close-btn="right">
<div data-role="header">
<h1>Batch Selection</h1>
</div>
<div data-role="content">
<div style="display:none;" id="batchprodcode" data="<?php echo $prodcode; ?>"></div>
<div style="display:none;" id="batchprodstock" data="<?php echo $prodstock; ?>"></div>
<div style="display:none;" id="batchpacking" data="<?php echo $packing; ?>"></div>
<div style="display:none;" id="batchqty" data="<?php echo $prodqty; ?>"></div>
<div style="overflow:auto;">
<table id="batchsel" style="border:1px;">
<thead>
<tr>
<th></th>
<th>Batch No</th>
<th>Exp Date</th>
<th>Brate</th>
<th>Srate</th>
<th>Packing</th>
<th>Stock</th>
<th>Supplier</th>
<th>ST%</th>
<th>Bill Date</th>
<th>Bill No</th>
<th>btax</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div id="remainingdata">
<p1 id="changeable_requirements"></p1>
<button id="saveprod" onclick="addProduct(); return false;">Add Product</button>
</div>
</div>
</div>
3a. Then I just change the pageshow that i was using for page3 to the new div that is created on batch.php. The script still runs on main.php.
$( document ).on( "pageshow", "#batchpage", function() {
$('#batchsel tbody').empty();
var prodcode = $('#batchprodcode').attr('data');
var prodstock = $('#batchprodstock').attr('data');
var prodqty = $('#batchqty').attr('data');
var packing = $('#batchpacking').attr('data');
...
});

Backbone routing loading data-role=page

I have a mobile app built using jquery mobile and backbone. I'm trying to work through the routing logic to render my views accordingly and am thus starting simple and adding complexity as I go along.
The html is as follows
<div id="main">
<li>Click Here to Test Me</li>
</div>
<div id="view-goes-here"></div>
<script type="text/template" id="actions-template">
<table cellspacing='0' cellpadding='0' border='1' >
<thead>
<tr>
<th>Id</th>
<th>Str</th>
</tr>
</thead>
<tbody>
<% _.each(action, function(c) { %>
<% var f = c.id, g = c.str; %>
<tr>
<td class="<%= f %>"><%= c.id %></td>
<td class="<%= g %>"><%= c.str %></td>
</tr>
<% }); %>
</tbody>
</table>
</script>
Here is a jsfiddle with functional code: http://jsfiddle.net/horcle_buzz/4JGhZ/
I would like it so that when I do a hashchange to "test_me" then the contents of the "main" div (specifically, the url with text "Click Here to Test Me") would disappear with only the output from my view being rendered in the output, specifically the table contents from my variable c in the function test:
var c = [
{ id: 1, str: 'This'},
{ id: 2, str: 'is'},
{ id: 3, str: 'a'},
{ id: 4, str: 'test!'}
];
My view is as follows:
var ActionView = Backbone.View.extend({
template: ActionTemplate,
events:{
"click":"makeInput"
},
render:function(){
alert("a" + JSON.stringify(this.collection));
alert("b" + this.collection.toJSON());
$(this.el).html(this.template({
action: this.collection.toJSON()
}));
$('#view-goes-here').append(this.el);
return this;
},
makeInput:function(){
alert("im in");
}
});
My guess is that I would have to use the data-role=page tag for my divs, but when I do this, the view does not render as expected. I am slightly confused about how to get the desired output, especially since most examples out there are rather basic.
I disable jQuery Mobile routing as follows and then start Backbone history:
$(document).ready(function(){
$.mobile.linkBindingEnabled = false;
$.mobile.hashListeningEnabled = false;
var router = new ActionsRoute();
Backbone.history.start();
});
Routing is done as follows:
var ActionsRoute = Backbone.Router.extend({
routes: {
'': 'main',
'test_me': 'loader'
},
main: function() {
$.mobile.changePage( "#main" , { reverse: false, changeHash: false } );
},
loader: function() {
test(function(c, Actions, ActionView){
alert("Data:" + JSON.stringify(c));
var actions = new Actions(c);
var actionView = new ActionView({collection:actions});
actionView.render();
});
}
});
Thanks in advance!
Doh! I did not have jquery.mobile-1.2.0.min.css defined as a resource. Added it, and all is behaving as desired.

Resources