How to maintain the dynamic generated textboxes after postback - html

I am generating dynamic html textboxes in my aspx page. I add a button for do some functionality. now whenever I click on my button it post back and all the dynamic generated textboxes go from my form for this I have to add it again. But I want to maintain these textboxes after postback. Here is the code how i am generating textboxes
<script type="text/javascript">
var textid = null;
var textid1 = null;
$(document).ready(function () {
setupAutoComplete(textid);
setupAutoComplete1(textid1);
var counter = 2;
$("#addButton").click(function () {
if (counter > 5) {
alert("Limit Exceeds");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
textid = "textbox" + counter;
textid1 = "textbox" + counter+1;
// newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
// '<input type="text" name="textbox' + counter +
// '" id="textbox' + counter + '" value="" class="auto">');
newTextBoxDiv.after().html('<div class="fields-left"><label> Leaving from</label><input type="text" name="textbox' + counter + '" id="textbox' + counter + '" class="auto"/> </div><div class="fields-right"> <label> Going to</label> <input type="text" name="textbox' + counter + '" id="textbox' + counter + 1 + '" class="auto"/> </div>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
setupAutoComplete(textid);
setupAutoComplete1(textid1);
counter++;
});
$("#removeButton").click(function () {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
var setupAutoComplete= function SearchText2(textid) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
var setupAutoComplete1 = function SearchText3(textid1) {
$('.auto').autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Home.aspx/GetAutoCompleteData",
data: "{'code':'" + document.getElementById(textid1).value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
</script>
now in this code I am generating maximun 10 textboxes two in each row and after that I write some code for json autocomplete for each dynamic generated textbox. Now problem is this when i click on my button after that its postback and all the textboxes and its values goes away. I am unable to maintain these textboxes. Can anybody tell me how can we maintain the dymanic generated textboxes after postback?
Thanks

Related

How to show Total No. of post In blogger with ajax get method

I want to show total no. of post in blogger with ajax get method bellow is my code.
<div id='show'></div>
<script type="text/javascript">
$.ajax({
url: "https://techtovillage.blogspot.com/feeds/posts/default?orderby=published&max-results=10&start-index=2&alt=json-in-script",
type: "get",
dataType: "jsonp",
success: function (data) {
var Posts = '<div class="hindipathtestapp">';
for (var i = 0; i < data.feed.entry.length; i++) {
var totalposts = json.feed.openSearch$totalResults.$t;
var posttitle = data.feed.entry[i].title.$t;
var postcontent = data.feed.entry[i].content.$t;
Posts += "<div class='testapp'><h1>" + totalposts + "</h1><h3>" + posttitle + "</h3><div class='content'>" + postcontent + "</div></div>";
}
Posts += "</div>"
document.getElementById('show').innerHTML = Posts;
}
});
</script>
Try this
<div id='show'></div>
<script type="text/javascript">
$.ajax({
url: "https://techtovillage.blogspot.com/feeds/posts/default?alt=json-in-script",
type: "get",
dataType: "jsonp",
success: function (data) {
var totalposts = data.feed.openSearch$totalResults.$t;
document.getElementById('show').innerHTML = "<div class='totalposts'>" + totalposts + "</div>";
}
});
</script>

Calculate the json's value then show in html

I have a json array:
[{"value": "1"},{"value": "2"},{"value": "3"},{"value": "4"},{"value": "5"},{"value": "6"}]
My code is :
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, value) {
items.push("<tr>");
items.push("<td id=''" + key + "''>" + value.value+ < /td>");
items.push("<td id=''" + key + "''>" + total of values + < /td>");
items.push("</tr>");
});
}
});
I want to calculate the values, how to do with that?
$.ajax({
url: "120.58.243.11:8080/needCal/myJson.json",
dataType:'json',
success: function(data){
var items = [];
var totalOfValue = 0;
$.each(data,function(key,value){
totalOfValue = totalOfValue + parseInt(value.value);
});
$.each(data,function(key,value){
items.push("<tr>");
items.push("<td id='" +key+ "'>" + value.value+</td>");
items.push("<td id='" +key+ "'>" + totalOfValue +</td>");
items.push("</tr>");
});
}
}
);
A simple way is to use the reduce method:
Something like this:
var total = arr.reduce(function(t, v) {
return t += Number(v.value);
}, 0);

Refresh dropdown with Jquery

I have one dropdown for displaying the month from January to current month in jQuery mobile. I'm getting the data using JSON. But the problem is selected option is not getting refresh.
$.ajax({
type: "POST",
url: "../modules/loadmonth.php?id=getoption&studid=" + $('#studentids').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var sel;
if (date[i].optval == date[i].curmon) {
sel = "selected";
} else {
sel = "";
}
result = '<option value=' + data[i].optval + '' + sel + '>' + data[i].opt + '</option>';
});
$('#getmon').append(result);
}
});
The value attribute should be in quotes, but more importantly you'll need a space between it and your selected attribute.
I have added selectmenu after append then it works.
$.ajax({
type: "POST",
url: "../modules/loadmonth.php?id=getoption&studid=" + $('#studentids').val(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function (i, item) {
var sel;
if (date[i].optval == date[i].curmon) {
sel = "selected";
} else {
sel = "";
}
result = '<option value=' + data[i].optval + '' + sel + '>' + data[i].opt + '</option>';
});
$('#getmon').append(result).selectmenu('refresh',true);
}
});

Javascript: each function value dynamic title

I am trying to use following code:
var list_id = "Cust";
var page_id = "SubPageCust";
var show = "Company";
$.ajax({
url: "sap.php",
dataType: "json",
type: "POST",
success: function(data) {
var output = '';
$('#' + list_id).empty();
var value1 = "value." + show;
$.each(data, function(index, value){
output += '<li><a href="#' + value.show
+'" data-transition="slide">' + value.show + '</a></li>';
});
$('#' + list_id).append(output).listview('refresh');
The JSON title is Company:Company. Has anyone an idea how to use the value.title dynamically?
Regards

Save Data with KnocloutJS viewmodel to server

I want to save my ViewModel to my SQL server. The standard knockout ko.toJSON(viewModel) keeps giving me an undefined error, so after some digging i found this Question, but still keeps giving me undefined.
Here is the code for my viewmodel, this is just a currency conversion table that gets the Conversion Rate between 2 currencies.
//ko Event Handler for datepicker.js
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options).on("changeDate", function (ev) {
var observable = valueAccessor();
observable(ev.date);
});
},
update: function (element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$(element).datepicker("setValue", value);
}
};
//Currency Model Definition
var currency = function (data) {
var self = this;
self.DateCreated = ko.observable(formatJsonDate(data.DateCreated));
self.CurrencyFrom = ko.observable(data.CurrencyFrom);
self.CurrencyTo = ko.observable(data.CurrencyTo);
self.ConversionRate = ko.observable(data.ConversionRate);
//Yhoo Finance API
ko.computed(function () {
var from = self.CurrencyFrom(),
to = self.CurrencyTo();
if (!from || !to) {
self.ConversionRate("N/A");
return;
}
getRate(from, to).done(function (YahooData) {
console.log("got yahoo data for [" + from + "," + to + "]: ", YahooData);
self.ConversionRate(YahooData.query.results.row.rate);
});
});
}
var NewDate = new Date().getFullYear() + '-' + ("0" + (new Date().getMonth() + 1)).slice(-2) + '-' + new Date().getDate();
var CurrencyModel = function (Currencies) {
var self = this;
self.Currencies = ko.observableArray(Currencies);
self.AddCurrency = function () {
self.Currencies.push({
DateCreated: NewDate,
CurrencyFrom: "",
CurrencyTo: "",
ConversionRate: ""
});
};
self.RemoveCurrency = function (Currency) {
self.Currencies.remove(Currency);
};
self.Save = function () {
$.ajax({
url: "#",
contentType: 'application/json',
data: ko.mapping.toJSON(CurrencyModel),
type: "POST",
dataType: 'json',
success: function (data) {
//I get undefined....
alert(ko.mapping.toJSON(CurrencyModel));
},
error: function (data) { alert("error" + data); }
});
}
$.ajax({
url: "CurrencyConfiguration.aspx/GetConfiguredCurrencies",
data: '{}',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
// callback(Result);
var MappedCurrencies =
$.map(Result.d,
function (item) {
getRate(item.CurrencyFrom, item.CurrencyTo);
return new currency(item);
}
);
self.Currencies(MappedCurrencies);
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
};
function formatJsonDate(jsonDate) {
var FormatDate = new Date(parseInt(jsonDate.substr(6)));
var Output = FormatDate.getFullYear() + '-' + ("0" + (FormatDate.getMonth() + 1)).slice(-2) + '-' + FormatDate.getDate();
return (Output);
};
function getRate(from, to) {
return $.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20rate%2Cname%20from%20csv%20where%20url%3D'http%3A%2F%2Fdownload.finance.yahoo.com%2Fd%2Fquotes%3Fs%3D" + from + to + "%253DX%26f%3Dl1n'%20and%20columns%3D'rate%2Cname'&format=json&callback=?");
}
function callback(data) {
if (viewModel) {
// model was initialized, update it
ko.mapping.fromJS(data, viewModel);
} else {
// or initialize and bind
viewModel = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
}
}
$('#Date').datepicker();
$(document).ready(function () {
var VM = new CurrencyModel();
ko.applyBindings(VM);
})
data: ko.mapping.toJSON(CurrencyModel)
You are trying to JSONify the definition not the actual instance
Isn't the method that you want to use:
ko.toJSON
rather than off the mapping object?