I have a table full of data, upon clicking on any of the record. A jquery ajax function called and get the detailed information for that record and display it in the div associated with the record.
Now i want to show it in a accordion.
Most of time a jquery accordion works like this
$(document).ready(function() {
$('#accordion').accordion();
});
But here i want that my div gets populated first with data then accordion method gets called. Because if accordion() called first then there is nothing for accordion to display as the request for data is still in processing.
My jquery ajax method is like this
$(function () {
$("span.Consignment").click(function () {
var position = 'div#' + this.innerHTML;
var url = "/Tracking/TrackingConsignment?consno=" + this.innerHTML;
$(position).load(url, function() {
$("a.Consignment").accordion();
return false;
});
});
});
This is my code
#foreach (var lst in item.Item2)
{
<a href="#" class="Consignment">
<table class="gridtable">
<a href="#">
<tr>
<td>
<span class="Consignment" href="#">#lst.ConsignmentNo</span>
</td>
<td>#lst.ConsignmentDate
</td>
</tr>
</a>
</table>
</a>
<div id="#lst.ConsignmentNo">
</div>
}
How should i make it work. First data then accordion.
Setup your accordion in the success of the .load.
.load(url,function(){
$("#accordion").accordion();
})
Related
EDIT:
Here is the exact problem that I have demonstrate, please have a look and as soon as I click the submit button it post back and lost its state and as you can see in the sample code I have three pages I'm posting the form
1) EmployeeForm, 2) EmployerForm, 3) ContractorForm
https://dotnetfiddle.net/wVtwgW
How do I persist the checkbox?
Once I post the page and it reloads the same page if I have my data-model invalid and it display the error message on the screen but the problem is that, it hides the fieldset and the user has to click the checkbox again to show the fieldset.
my question is: how can I still show the fieldset and show the error message in it?
//my scripts that shows the fieldset
<script>
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
});
</script>
//it shows the fieldset with checkbox:
<fieldset class="fieldset-auto-width">
<legend>
Select Employee
</legend>
<table width="auto">
<tr>
<th>
Employee
</th>
<td>
#Html.CheckBox("Employee")
</td>
</tr>
</table>
</fieldset>
//my form where I have all the input text and button etc...
<fieldset id="emp" style="display: none" class="fieldset-auto-width">
<legend>
Employee Display
</legend>
#using (Html.BeginForm("EmployeeServer", "EmployeeForm", FormMethod.Post))
{
#Html.ValidationSummary(true)
<div>..... </div>
}
</fieldset>
Instead of using #Html.CheckBox() use #Html.CheckBoxFor()
<td>
#Html.CheckBoxFor(m => m.Employee)
</td>
this will retain the state of the checkbox when you return the model state errors..
in your javascript, just call the $("#Employee") change event after the page loads..
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
$('#Employee').trigger("change");
});
Set the Fieldset display value when view is rendered
<fieldset id="emp" style="#(Model.Employee ? "": "display: none")" class="fieldset-auto-width">
<legend>
Employee Display
</legend>
#using (Html.BeginForm("EmployeeServer", "EmployeeForm", FormMethod.Post))
{
#Html.ValidationSummary(true)
<div>..... </div>
}
</fieldset>
this will hide the fieldset if Model.Employee = false or display it if Model.Employee = true.
Just do it with JavaScript. Look for the rendered element from the validation summary helper, and if it exists then you can show your employee form. You can add it to your already executing script like this:
$(document).ready(function() {
$('#Employee').change(function() {
if (this.checked) {
$('#emp').show();
}
});
//check for validation summary elements
if($('.validation-summary-errors').length > 0){
//and show previous entry if present
$('#emp').show();
}
});
I am new to knockoutJS. I am working on an MVC application where I want to implement knockoutJS but the scenario is bit different.
I have a page where I am showing a list. I have 3 links on the page and on click of them I am adding partial views to page accordingly. What I want to do is that whenever I add values/data to partial views, the list which is on page should be updated with knockout. In other words I want to add value to observable array when I save data from partial view.
Please let me know if this is possible or I should keep it in jquery only.
Here is the code:
Main view:
<input type="button" value="Add Partial View" onclick="LoadPartial();" />
<div id="dvContent"></div>
<h4>People</h4>
<ul data-bind="foreach: people">
<li>
Name at position <span data-bind="text: $index"> </span>:
<span data-bind="text: name"> </span>
Remove
</li>
</ul>
<button data-bind="click: addPerson">Add</button>
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/knockout-2.1.0.js"></script>
<script>
function LoadPartial() {
$.ajax({
url: "/home/index",
dataType:"html",
type: "GET",
success: function (data) {
$("#dvContent").html(data);
}
});
}
</script>
<script>
function AppViewModel() {
var self = this;
self.people = ko.observableArray([
{ name: 'Bert' },
{ name: 'Charles' },
{ name: 'Denise' }
]);
self.addPerson = function () {
self.people.push({ name: "New at " + new Date() });
};
self.removePerson = function () {
self.people.remove(this);
}
}
ko.applyBindings(new AppViewModel());
</script>
Partial View:
<table>
<tr>
<td>Add new Row</td>
<td><input type="button" value="Add" data-bind="click: addPerson"/></td>
</tr>
</table>
Thanks,
JsHunjan
It is easy to accomplish with Knockout. You need to show some code that you have tried though if you want to get some help. I will post a general answer but it isn't going to fix your use case exactly, just basically -
Create an object to hold your new item, you can do this either in the parent or the child view model, but if you do it in the child you need to pass it back to the parent.
Once you hit a save button or add or whatever in the child view model just do a .push() into the observableArray that you created ex... - myObservableArray.push(newItem());
Knockout will recognize all of the changes taking place and perform the actions you want automatically.
Hope this helps.
I have the following snippet JQuery inside an HTML file:
$.getJSON("/events/", function (data) {
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
The code is executed when, for example, the user presses a button and returns JSON like:
{"Events":[{"Name":"Event1"},{"Name":"Event2"},{"Name":"Event3"}]}
This result is linked (using KnockoutJS) to:
<ul data-bind="foreach: Events">
<li><span data-bind="text: Name"></span></li>
</ul>
Everything works fine with the first call to $.GetJSON. I get what I want, which is (browser output):
Event1
Event2
Event3
But in subsequent calls to "$. GetJSON" I get the following error in Firebug:
NotFoundError: Node was not found.
containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
And I get no list item.
What I can be doing wrong?
Thank you very much in advance.
The whole point of Knockout is to handle the interaction between your view and view model. In this case, you're trying to update a list of events in response to a button click. The button click should be linked to a function in your view model, while the list should be linked to an observable array that's updated when you click the button. I've put this together in a fiddle here: http://jsfiddle.net/mbest/uZb3e/ and the important parts are below:
<button type=button data-bind="click: updateEvents">Update</button>
<ul data-bind="foreach: data.Events">
<li><span data-bind="text: Name"></span></li>
</ul>
Javascript:
var viewModel = {
data: ko.mapping.fromJS({"Events":[]}),
updateEvents: function() {
var self = this;
$.getJSON("/events/", function (data) {
ko.mapping.fromJS(newData, self.data);
});
}
};
ko.applyBindings(viewModel);
My friend Thomas Brattli found the solution:
<ul data-bind="template: { name: 'template', foreach: Events }"></ul>
<script id="template" type="text/html">
<li><span data-bind="text: Name"></span></li>
</script>
Thanks !
I'm working on Android with Jquery Mobile with PhoneGap using Knockout for loading data.
I'm getting the data all right and loading it on the HTML page accordingly to the for each data-bind I have on the tags.
When I want to refresh the data, it just doesn't do it. It returns just an HTML without bound data or throwing dom exception not found.
My applyBinding happens inside pagecreate event of the page.
I've posted a simple example describing the problem on my SkyDrive - http://sdrv.ms/LpUdLt
It's a public example reproducing the problem.
the viewmodel holds an array that holds array.
refreshed with randomal values.
trying to reload the page in jquery mobile with changepage reload with new data by pressing the navbar button fails with the dom object mistake.
I do agree not to that I shouldn't create an instance of VM every page create, just can't find a way to implement it, so that the data will be rerendered on HTML.
//indexPage.js
var wAViewModelInst ;
var viewPageIndexContent;
$('#pageIndex').live('pagecreate', function (event) {
viewPageIndexContent = document.getElementById("pageIndexContent");
wAViewModelInst = new WAViewModel(true);
ko.applyBindings(wAViewModelInst, viewPageIndexContent);
waHeaderVM.refreshContentData = function () {
// wAViewModelInst.updateRowList();
// ko.cleanNode(viewPageIndexContent);
// viewPageIndexContent = document.getElementById("pageIndexContent");
//wAViewModelInst = new WAViewModel(true);
//ko.applyBindings(wAViewModelInst, viewPageIndexContent);
$.mobile.changePage("index.html", { allowSamePageTransition: true, reloadPage: true });
$.mobile.hidePageLoadingMsg();
}
}
//WAViewModel
self.WARowList = ko.observableArray();
self.updateRowList = function () {
self.WARowList(self.GetWA());
}
//tried the exteding
//ko.observableArray.fn.WARowListUpdate = function () {
// //create a sub-observable
// this.hasItems = ko.observable();
// //update it when the observableArray is updated
// this.subscribe(function (newValue) {
// this.hasItems(newValue && newValue.length ? true : false);
// }, this);
// //trigger change to initialize the value
// this.valueHasMutated();
// //support chaining by returning the array
// return this;
//};
is there any way to update the html after the first rendering ?
adding the html code:
<div id="pageIndex" data-role="page" data-transition="flip" data-theme="e" data-dom-cache="true">
<div id="indexHeader" data-role="header" data-theme="e">
<div data-role="navbar" data-iconpos="right">
<ul>
<li><a href="login.html" data-role="tab" data-icon="back" data-bind="click: loadingHandler"
class="brighter-text">חזרה</a></li>
<li><a href="#" data-role="tab" data-icon="refresh" data-bind ="click: refreshContentData" >רענן</a></li>
<li>ביצוע חקר</li>
<li><a href="#" data-role="tab" data-icon="grid" class="ui-btn-active brighter-text">
סידור עבודה</a></li>
</ul>
</div>
</div>
<div id="pageIndexContent" data-role="content" data-theme="e" style="padding-bottom: 52px;
height: 570px;">
<h2 data-bind="text:Title" class="brighter-text" style="font-size:22pt;">
</h2>
<div data-bind="foreach: WARowList" style="width: 99%; text-align: center">
<div>
<table style="float: right; width: 20%; height: 60px;" cellpadding="0" cellspacing="0">
<tr data-bind="visible : FirstRow " style="height: 31px;">
<th class="AlignedHeader">
<label>
שעה / שילוט</label>
</th>
</tr>
<tr data-bind="style: { backgroundColor: Odd() ? '#8CC63F' : '#AFC493' }">
<td style="width: 20%;" data-bind="style: { backgroundColor: IsNew() ? 'yellow' : 'transparent' }">
<input type="button" data-bind="click: ShowSampleDetails, value: ShilutTime , jQueryButtonUIEnableDisable:$data"
data-icon="plus" data-iconpos="right"/>
</td>
</tr>
</table>
<table style="height: 60px; width: 80%; background-color: #8CC63F;" data-bind="style: { backgroundColor: Odd() ? '#8CC63F' : '#AFC493' }"
cellpadding="0" cellspacing="0">
<thead data-bind="if : FirstRow">
<tr data-bind="foreach: CellList">
<th class="AlignedHeader">
<label data-bind="text: Date">
</label>
</th>
</tr>
</thead>
<tbody>
<tr data-bind="foreach: CellList">
<td style="width: 11.5%;">
<div data-bind="visible:IsPopulated ">
<div data-bind="visible: HasDrivers">
<input type="button" data-role="button" data-bind="click: ShowBusDriverList.bind($data , $root) , jQueryButtonUIEnableDisable: $data "
data-icon="search" data-iconpos="right" value="נהגים" class="brighter-text" />
</div>
<div data-bind="visible: !HasDrivers()">
<input type="button" data-role="button" id="btnNoDriver" disabled="disabled" data-icon="info"
data-iconpos="right" value="אין נהג" class="brighter-text" />
</div>
</div>
<div data-bind="visible: !IsPopulated">
</div>
</td>
</tr>
</tbody>
</table>
</div>
and so on ..
the GetWA function returns an observableArray of warow list .
it works the first time the trouble is rerendering the dom object.
the dom element is contaminated with ko and fails ..
I tried the answer of Luffy :
var lVM = new loginViewModel();
var footerViewModelLogin = {
IsOnline: ko.observable(globalContext.Network()),
IsSync: ko.observable(globalContext.Sync())
};
$('#login').live('pagecreate', function (event) {
viewLoginContent = document.getElementById("loginContent");
ko.applyBindingsToNode(viewLoginContent, lVM);
viewLoginFooter= document.getElementById("footerLogin");
ko.applyBindingsToNode(viewLoginFooter, footerViewModelLogin);
});
$('#login').live('pagehide', function (event, ui) {
$.mobile.hidePageLoadingMsg();
});
function loginViewModel() {
var self = this;
try {
self.userName = ko.observable("");
self.password = ko.observable("");
self.message = ko.observable("");
self.CleanGlobalContext = function () {
...
};
self.Validate = function () {
...
};
}
catch (e) {
if (IsDebug) alert("GlobalContext.prototype.SetMapOverlay " + e.message);
if (typeof (console) != 'undefined' && console) console.log("GlobalContext.prototype.SetMapOverlay " + e.message);
}
}
ko.applyBindings(lVM);
ko.applyBindings(footerViewModelLogin);
The knockout fails without the element predefined event to bind .
I have not understood well you difficulty. However, I don't understand why you need to reapply bindings. Notice what follows:
If you change an observable array the needed templates are re-instantiated to updated coherently the UI. However you have to update the observalble array either by using the observable array functions, or by passing to the observable a new array: obs(newArray).
If you need to perform actions after the ko re-rendering you just need to use the afterRender, or afterAdd parameters of the template binding
if you add new jquery mobile code you have to parse it after having created it otherwise jquery mobile will not work...again you can do this in the afterRender function.
it is problematic to load html containing ajax ko bindings via ajax. The right approach is to create that content as a template, that you render immediately (not with ajax). Then you query the server just to get new json content. Then you can instantiate the template by using for instance the with binding.
Yes you can reapply bindings with ko.applyBindingsToNode function to the specific dom element.
Check these examples
http://jsfiddle.net/rniemeyer/gYk6f/ ---> With templating
http://jsfiddle.net/rniemeyer/BnDh6/ ---> With data - value pair
The solution was to add afterRender on the foreach table data-bind. as – Francesco Abbruzzese suggested.
The ajax request has been turned to async:false though.
Each time I update the list I perform some dat-bind = "click:updateRowList" which updates the table.
Thanks a lot to Elad Katz for help with bounty .
I'm using the jquery tab plugin with the same results that are on jquery ui site (link text).
The problem is that I want to change the tab label to something like "Loading" when the Ajax request is waiting for a response. How shall I achieve that?
Edit:
What I have now:
<div id="tabs">
<ul>
<li>User Profile</li>
<li>Edit</li>
<li>Delete AccountT</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
</div>
and on javascript I just have the following code:
<script type="text/javascript">
$(function () {
$("#tabs").tabs({
});
});
</script>
What i want is to show a loading message inside the div of the active tab.
According to the widget doc, ajax should work outside the box if your href is an actual link :
To customize loading message, you can use the spinner option :
Fetch external content via Ajax for
the tabs by setting an href value in
the tab links. While the Ajax request
is waiting for a response, the tab
label changes to say "Loading...",
then returns to the normal label once
loaded.
<script>
$(function() {
$( "#tabs" ).tabs({
spinner: "<em>My Loading Msg</em>",
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
}
});
});
</script>
Why don't you just set the tab label to "loading" onclick and change it to whatever you want once you get a response back from your AJAX?
$(function () {
$("#tabs").tabs();
$("#tab1").click(function() {
$(this).val("Loading...");
$.ajax({
blablabla...
success: function() {
$("#tab1").val("Tab 1");
}
});
});
This should give you an idea, obviously the function could be written better to act on each tab.
I think what you are after already exists in the jquery ui for Tabs.
The HTML content of this string is
shown in a tab title while remote
content is loading.
http://jqueryui.com/demos/tabs/#option-spinner
Hope this helps!
From your example am I correct in assuming that you want to navigate to another page when the user clicks on either of the second two tabs, but you want a loading message to be displayed while you are waiting for the next tab to load?
If so, you could do it by keeping a loading message in the other tabs like so:
<input type="hidden" id="modelId" value="<%=Model.Id%>" />
<div id="tabs">
<ul>
<li>
User Profile
</li>
<li>
Edit
</li>
<li>
Delete AccountT
</li>
</ul>
<div id="tabs-1">
<% Html.RenderPartial("UserProfile", Model); %>
</div>
<div id="tabs-2">
<p>Loading, please wait...</p>
</div>
<div id="tabs-3">
<p>Loading, please wait...</p>
</div>
</div>
And doing the redirection to your other pages in your javascript, doing it something like this:
$(document).ready(document_ready);
function document_ready()
{
$("tabs").bind("tabsselect", onTabSelected);
}
function onTabSelected(event, ui)
{
var modelId = $("#modelId").val();
switch (ui.panel.id)
{
case "tabs-2":
window.location.href = "/User/EditUser/" + modelId;
break;
case "tabs-3":
window.location.href = "/User/Delete/" + modelId;
break;
}
}