Checkbox in ListView with Jquery mobile - jquery-mobile

I am starting to learn HTML5 and CSS (with Jquery Mobile), and because I do not have much background in this area, I am stuck at something very easy.
I want to put a checkbox in a listview (at each li).
How can I do it in order to look like that :
http://a4.mzstatic.com/us/r1000/095/Purple/ff/1d/33/mzl.ecpvufek.320x480-75.jpg
(I mean that the checkbox is at the left of the others text and all).
For the moment, my code is : http://jsfiddle.net/AzN7S/
And as you can see the checkbox is above the text, and even with a div with a float:left in the second li, it doesn't work :(
Can you help me please ?
Thank you very much beforehand for your answer, and sorry for my english ^^
Have a great day.
Olivier.
EDIT :
I finally succeeded in adding a checkbox at the left of the the right part.
I updated my example : http://jsfiddle.net/AzN7S/2/
I do not know if it is the right method, but it works :)

i rethought my old answer and re did the issue especially to fit the mvc 4 framework but the client side is all the same.
so lets start:
if you just want the html you can get it here
this link is to a 3 parts checkbox list, the checkbox, the link to the item and the info popup:
Here is the link to jsfiddle for working listview with checkbox AND icon
iv added at the end some 2 parts listbox and a single part, for any questions let me know.
now for the controller all you need to do is
[Authorize]
public ActionResult Items(string act,
string tab, string search_by, string search, string sort, string sortdir, int? page, int? resultsPerPage,
List<int> selected, int? projectId, string username)
{
if (act == "AddItemsToUser")
{
string response;
if (selected != null)
{
response = "Project Items Added:";
foreach (var item in selected)
{
try
{
if (username != null)
if (UserItemRecordModel.InsertUserItem(username, item, null, null, 0, null, null))
response += item + " - inserted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "AddItemsToProject")
{
string response;
if (selected != null)
{
response = "Project Items Added:";
foreach (var item in selected)
{
try
{
if (projectId != null)
if (ProjectItemRecordModel.InsertProjectItem(projectId.ToString(), item, null, null, 0, null, null))
response += item + " - inserted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "RemoveItemsFromUser")
{
string response;
if (selected != null)
{
response = "Project Items Removed:";
foreach (var item in selected)
{
try
{
if (UserItemRecordModel.DeleteUserItem(username, item))
response += item + " - deleted, ";
}
catch (Exception ex)
{
response += item + " - " + ex.Message + ", ";
}
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
else if (act == "RemoveItemsFromProject")
{
string response;
if (selected != null)
{
response = "Project Items Removed:";
foreach (var item in selected)
{
if (ProjectItemRecordModel.DeleteProjectItem(projectId.ToString(), item))
response += item + " - deleted, ";
}
response.TrimEnd(' ', ',');
}
else
{
response = "No Items Were Selected!";
}
return Json(response, JsonRequestBehavior.AllowGet);
}
List<ItemRecordModel> items = ItemRecordModel.GetSensors(search_by, search, sort, sortdir);
return View("Items", new AdminRecordsViewModel() { Records = items });
}
this was my old answer:
i solved your problem you need to change some stuff but you can accomplish a searchable listview with checkbox like so:
jsfiddle example:
basic:
basic jsfiddle version
nicer version:
nicer version
jquery mobile listview with checkbox and icon or image

here is a listView of checkBox and a search bar. you should add this js code
$("li").on("tap",function(){
$(this).find('label').click();
}); in the button somewhere in your page.
the js code crete a click on the check box when the user clicks on the li
<div class="ui-content" data-role="main">
<div data-role="main" class="ui-content">
<h2 class="settings-h2">Select category</h2>
<h5 lass="settings-h2">You will get articles on those subject,you can change your selection at any time.</h5>
<form class="ui-filterable">
<input id="myFilter-settings" data-type="search">
</form>
<ul data-role="listview" id="ScheduleList-settings" data-filter="true" data-input="#myFilter-settings" data-inset="true" class="ui-listview ui-listview-inset ui-corner-all ui-shadow">
<li data-icon="false">
<form>
<fieldset class="myhover" data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Sports" >
<label for="checkbox-Sports">Sports</label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="ccheckbox-Food" >
<label for="ccheckbox-Food">Food</label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Politics" >
<label for="checkbox-Politics">Politics </label>
</fieldset>
</form>
</li>
<li data-icon="false" >
<form>
<fieldset data-role="controlgroup" data-iconpos="right" >
<input type="checkbox" name="checkbox-h-6a" id="checkbox-Fashion" >
<label for="checkbox-Fashion">Fashion</label>
</fieldset>
</form>
</li>
</ul>
</div>
</div>

Related

Problems with partialview data

I have a problem with a partial view. The first time when it is rendered everything is ok, but after that some data is loosed.
This is how my page should look: this is when the partial view is rendered the first time
but when I'm clicking on a category to check his subcategories, the image is null, it is not visible anymore. (only the name is visible)
This is my partial view:
#model IEnumerable<OnlineCarStore.Models.CategoriesVM>
<div class="container">
<div class="row">
#using (Html.BeginForm("SubCategories", "Product"))
{
<div class="list-group col-sm-3" style="width:280px;">
#{var selected = string.Empty;
if (#HttpContext.Current.Session["selectedCar"] == null)
{
selected = string.Empty;
}
else
{
selected = #HttpContext.Current.Session["selectedCar"].ToString();
}
foreach (var c in Model)
{
<a href="#Url.Action("SubCategories", "Product", new { selected = #selected, id = #c.ID, category = #c.CategoryName })" class="list-group-item">
<span> #c.CategoryName</span>
</a>
}
}
</div>
<div class="col-sm-9">
#foreach (var c in Model)
{
<div class="card-group" style="width:200px; display: inline-block">
<div class="card card">
<a href="#Url.Action("SubCategories", "Product", new { selected = #HttpContext.Current.Session["selectedCar"].ToString(), id = #c.ID, category = #c.CategoryName })" id="linkOnImg" class="card-group">
<img class="card-img-top center-block" src="#string.Format("../content/images/categories/{0}.jpg", #c.AtpID)" alt=#c.CategoryName style="padding-top: 5px">
<div class="card-text text-center">
<p class="category-card-title ">
<span class="text-muted">#c.CategoryName</span>
</p>
</div>
</a>
</div>
</div>
}
</div>
}
</div>
and this is the Subcategoris view, where the partial view is rendered second time:
<div class="container">
<div class="row">
#Html.Partial("/Views/Home/CategorieTypes.cshtml");
Here is the Product controller Subcategories method:
public ActionResult SubCategories(string selected, int id, string category)
{
List<CategoriesVM> listOfCategories = new List<CategoriesVM>();
var list = db.Categories.ToList();
var root = list.GenerateTree(c => c.ID, c => c.ParentId).ToList();
TreeItem<Categories> found = null;
var test = new TreeItem<Categories>();
foreach (var rootNode in root)
{
found = TreeGenerator.Find(rootNode, (n) => n.Item.ID == id);
if (found != default(TreeItem<Categories>))
{
test = found;
break;
}
}
foreach (var item in found.Children.ToList())
{
CategoriesVM categoryv = new CategoriesVM();
categoryv.ID = item.Item.ID;
categoryv.AtpID = item.Item.AtpID;
categoryv.Childrens = item.Children.ToList();
categoryv.CategoryName = item.Item.AtpName;//.Name;
listOfCategories.Add(categoryv);
}
SiteMaps.Current.CurrentNode.Title = selected + " " + category;
var tests = found.Children.ToList();
if (found.Children.ToList().Count == 0 )
{
return View("Index");
}
else
{
return View("SubCategories", listOfCategories);
}
}
I've checked in developer tool if the source for the image is correct, and although it is correct, the image is not showed:
Can you please help me in this problem? What I do wrong? Why the images don't appear after the first render of the partial view? Thanks in advance!
The path of the partial view is /Views/Home/CategorieTypes.cshtml and the path of the images is /Content/images/categories. In the partial view you are using ../content/images/categories/ as the path of the images which means that it will search for the path /Views/Content/Images/Categories which is invalid.
Remove the two dots in the src property and add a ~ so it will be like: ~/Content/Images/Categories/{img}.
or
Add one more ../ in order to go one level down to the directory like:
../../Content/Images/Categories/{img}

JQuery Mobile filterable listview with multiple filters

I have a JQM 1.4.2 filterable listview which contain entries in different languages.
I would like to search only within items code, not the whole description, whereby i set the data-filtertext for list items to the item code, e.g. "Apple" or "Banana".
This works ok but now i need an additional language filter, e.g. "EN", "DE", and so on:
...
<li data-filtertext="Apple language_en">
<h2>Title</h2>
<p>Red fruit</p>
<p class="ui-li-aside"><strong>EN</strong></p>
</li>
...
...
<li data-filtertext="Banana language_de">
<h2>Titel</h2>
<p>Beschreibung</p>
<p class="ui-li-aside"><strong>DE</strong></p>
</li>
...
This is my data input:
<form class="ui-filterable">
<div class="ui-grid-a">
<div class="ui-block-a">
<input id="descriptions-input" data-type="search" placeholder="Search..." />
</div>
<div class="ui-block-b">
<fieldset data-role="controlgroup" data-type="horizontal">
<input name="lang-en" id="lang-en" type="checkbox" data-mini="true">
<label for="lang-en">EN</label>
<input name="lang-de" id="lang-de" type="checkbox" data-mini="true">
<label for="lang-de">DE</label>
<input name="lang-fr" id="lang-fr" type="checkbox" data-mini="true">
<label for="lang-fr">FR</label>
</fieldset>
</div>
</div>
</form>
What i try to do now, is that when a checkbox is selected, only the list items belonging to that language are visible.
How can i set this additional filter to my filterable jQuery Mobile listview?
Plunker: http://plnkr.co/edit/TV6rcatzdvaIvQzWBdoI?p=preview
EDIT:
This is the final solution, thanks to EZANKER: https://jsfiddle.net/m64kg5fw/4/
The filterable widget as a filterCallback property: http://api.jquerymobile.com/filterable/#option-filterCallback
You can use this to write a function that checks both the text and which language checkboxes are checked.
$(document).on("pagecreate", "#list-descriptions", function () {
$("#descriptions-list").filterable('option', 'filterCallback', checkedOrMatch);
$("#searchLangs input").on("change", function(){
$("#descriptions-list").filterable("refresh");
});
});
function checkedOrMatch(idx, searchValue) {
var ret = false;
var en = $("#lang-en").is(':checked');
var de = $("#lang-de").is(':checked');
var fr = $("#lang-fr").is(':checked');
var ignoreLang = false;
if (!en && !de && !fr) {
ignoreLang = true;
}
if (searchValue && searchValue.length > 0) {
searchValue = searchValue.toLowerCase();
var filttext = $(this).data("filtertext") || '';
filttext = filttext.toLowerCase();
if (filttext.indexOf(searchValue) < 0) {
ret = true; //filter this one out
} else if (!ignoreLang) {
//found filter text now check language
if ( (filttext.indexOf("language_en") > 0 && !en) || (filttext.indexOf("language_de") > 0 && !de) || (filttext.indexOf("language_fr") > 0 && !fr) ) {
ret = true; //filter this one out
}
}
}
return ret;
}
Updated DEMO
The checkedOrMatch functions runs for each item in the list. It first tests if the entered search text is found in the filter text. If it is, it then sees which language buttons are checked and tests the item for that language. I also added code to re-trigger the filter if the user selects language buttons after typing the search criteria.
NOTE: if the user types in "lang" you might not get what you want... In that case you could move the language designation out of the filter text and into a separate data-attribute.

Url.Action within #helper does not raise event

I am having issues with an Action link within the #helper.
See below this line
<a href="#Url.Action("Index","Category", new { id = item.Id })">
It simply does not raise event. What am i doing wrong here?
#helper ShowTree(IEnumerable<FrontEnd.Controllers.SharedController.Category> categories)
{
<ul id="#(Added == false ? "categories" : "")" class="parent-1">
#foreach (FrontEnd.Controllers.SharedController.Category item in categories)
{
Added = true;
<li class="child-1 has-sublist">
<a href="#Url.Action("Index","Category", new { id = item.Id })">
#item.CategoryName
#if (item.Children.Count > 0)
{ <span>
[#item.Children.Count]
</span>
}
</a>
#if (item.Children.Any())
{
#ShowTree(item.Children)
}
</li>
}
</ul>
}
Have you tried something like the following??
#Html.ActionLink(item.CategoryName, "Index", "Listing", new { id = item.Id }, null, null)
https://msdn.microsoft.com/en-us/library/dd460522(v=vs.118).aspx
Ok. Just found the cure.
Javascript was blocking the request to the controller..
$('#categories > li a').click(function(e){
if($(this).parent().hasClass('has-sublist')) {
e.preventDefault();
}....
.................

The model item passed into the dictionary is of type 'BlogHomePageModel', but this dictionary requires a model item of type 'BlogHomePageModel'

I'm using Umbraco 7.04. I would post code but I can't determine what is causing the problem. I did make some edits to a class in my App_Code folder and my website started displaying this error. I reverted those edits but still get the error.
A coworker mentioned that .net can cache files so I tried recycling app pool and editing web.config to no avail.
EDIT: here is the code I believe was causing the problem, although it seemed to have gone away randomly.
BlogHomePage View
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
Layout = "BlogLayout.cshtml";
var BlogBackgroundImageCss = Html.Raw(HttpUtility.HtmlDecode(Model.BannerImageBackgroundImageCss));
var BlogHomeContent = Html.Raw(HttpUtility.HtmlDecode(Model.BlogHomeContent));
var AllTags = Html.Raw(HttpUtility.HtmlDecode(thunder.TagHelper.GetAllTags(Model.Content)));
var PagingHtml = Html.Raw(HttpUtility.HtmlDecode(Model.PagingHtml));
}
<div class="blog-area">
<div class="blog-banner-area" style="#BlogBackgroundImageCss" >
<span>#Model.BannerImageTitle</span>
</div>
<div class="blog-nav-area">
<button class="blog-nav-collapse-button"><span>Search</span></button>
<div class="blog-nav-inner-area">
#{ Html.RenderPartial("BlogHomeSearchInformation", Model); }
#{ Html.RenderPartial("BlogPostSearch"); }
#AllTags
#{ Html.RenderPartial("BlogHomeAside", Model); /*use partial to render blog post aside*/ }
</div>
</div>
<div class="blog-main-area">
<div class="blog-heading-area">
<div class="blog-heading-text-container">
#BlogHomeContent
<button class="blog-about-this-blog-expand-button">Read More</button>
</div>
</div>
#if (Model.Posts.Count() > 0) {
foreach (var Post in Model.Posts) {
Html.RenderPartial("BlogHomePostPartial", Post); /*use partial to render blog post content*/
}
#PagingHtml
} else {
<p>Sorry, but no posts matched your query.</p>
}
</div>
</div>
BlogHomeSearchInformationPartial
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
string SearchTerm = (!string.IsNullOrEmpty(Request.QueryString["s"])) ? Request.QueryString["s"] : "";
string TagTerm = (!string.IsNullOrEmpty(Request.QueryString["t"])) ? Request.QueryString["t"] : "";
}
<div id="blog-search-results-information">
#if (!string.IsNullOrEmpty(SearchTerm)) {
if (Model.TotalResults == 1) {
<p>Your search for "#SearchTerm" returned #Model.TotalResults result. Click here to return to home page.</p>
} else {
<p>Your search for "#SearchTerm" returned #Model.TotalResults results. Click here to return to home page.</p>
}
}
#if (!string.IsNullOrEmpty(TagTerm)) {
if (Model.TotalResults == 1) {
<p>There is #Model.TotalResults post tagged "#TagTerm". Click here to return to home page.</p>
} else {
<p>There are #Model.TotalResults posts tagged "#TagTerm". Click here to return to home page.</p>
}
}
</div>
BlogPostSearch
#inherits UmbracoTemplatePage
#{
string SearchTerm = "";
SearchTerm = Request.QueryString["s"];
}
<form role="search" method="get" id="searchform" action="/">
<div class="blog-search-area">
<input type="search" name="s" value="#SearchTerm">
<button type="submit">Search</button>
</div>
</form>
BlogPostAside
#inherits Umbraco.Web.Mvc.UmbracoViewPage<BlogHomePageModel>
#{
var AsideLinks = Html.Raw(HttpUtility.HtmlDecode(Model.AsideLinks));
}
#if (!string.IsNullOrEmpty(Model.AsideHeading) || !string.IsNullOrEmpty(Model.AsideSubheading) || !string.IsNullOrEmpty(Model.AsideContent) || !string.IsNullOrEmpty(Model.AsideLinks)) {
<div class="blog-contact-area">
<span class="blog-contact-heading">#Model.AsideHeading</span>
<span class="blog-contact-subheading">#Model.AsideSubheading</span>
<p>#Model.AsideContent</p>
#AsideLinks
</div>
}
Seems to me you have defined a special model on your view (or you did inherit form something).
Try to remove the #model and the #inherits from your view.
problem solved itself mysteriously :( After a little more research I believe it may be related to this question: The model item passed into the dictionary is of type ‘mvc.Models.ModelA’ but this dictionary requires a model item of type ‘mvc.Models.ModelB‘

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

Resources