JavaScript back button to display previous list - javascript

I want create a web application that display a list of items. Suppose I have displayed a list view (say listobject1) of 3 items. when clicked on any of them I get new list view (say listobject2) which its value is according to listobject1. When again I click one of them I get another view. Now when I click back button i want to go back to previous list view i.e. when I'm now on listobject2 and again when back button is pressed I want to show listobject1. Can anybody tell me how I can do this in JavaScript?
Edit
I'm still study about the stuff but I can't solve this problem yet. In order to clarify my problem now, here's my code:
$(document).ready(function() {
$("#result").hide();
$("input[name='indexsearch']").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $("[name='valueLiteral']").val();
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">"
+ arraySubject[k] + "</span> " + " -> " + v + " : "+
//change object from text to be button form
"<button class = 'searchAgain-button' name = 'searchMore' \n\
value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br> <br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
$("button").live("click", function() {
$("#result").show();
$("#result").empty();
loading_img();
var $textInput = $(this).attr("Value");
//var $textInput = "G53SQM";
$.getJSON("get_onto", {
"input" : $textInput
}, function(json) {
if(json.length > 0 ) {
var arrayPredicate = [];
var arrayObject = [];
var arraySubject = [];
$.each(json, function(index, value) {
arraySubject[index] = value.subject;
arrayPredicate[index] = value.predicate;
if(value.objectGeneral != null) {
arrayObject[index] = value.objectGeneral;
} else {
arrayObject[index] = value.objectLiteral;
}
}
);
var stmt = [];
var searchMore = "searchMore";
//concat all related array into string (create triple statement)
$.each(arrayPredicate, function(k,v){
stmt[k] = "<span class='subject' id="+arraySubject[k]+">" + arraySubject[k] + "</span> " + " -> " + v + " : "+ " <button class = 'searchAgain-button' name = " +searchMore + " value = " + arrayObject[k] + ">" + arrayObject[k] + "</button><br><br>";
});
stmt = stmt.sort();
$.each(stmt, function(k,v){
$("#result").append(v);
});
} else {
var $noresult = "No Result : Please enter a query";
$("#result").append($noresult);
}
});
});
At first, user only see one button name "valueLiteral". After user perform 1st search, the result is return in a form of JSON and eventually put in stmt[] to display, which at this state the second button was create as a clickable-result which will automatically take the value of result and do second search if user click the second button.
Now the problem is, I want to add a 3rd HTML button name "back" to make the web display the previous result in stmt[] if user click on the button.
Hope this helps in clarify the problems, I'm still doing a hard work on this stuff since I'm a newbie in JavaScript. Appreciate all helps.

This is what you want almost exactly the way you want it.
You'll have to use history.pushState to push these fake events into the history.
Alternatively, you can use location.hash to store the current object, and update the hash every time you display a new list. Then onhashchange find the hash and display the appropriate list.

See http://jsfiddle.net/cFwME/
var history=[new Array(),new Array()];
history[0].id="#back";
history[1].id="#next";
Array.prototype.last=function(){
return this[this.length-1];
}
$('#list>li:not(:first)').click(function(){
if(!history[0].length || history[0].last().html()!=$('#list').html()){
history[0].push($('#list').clone(true,true));
$(history[0].id).prop('disabled',false);
history[1].length=0;
$(history[1].id).prop('disabled',true);
}
$('#list>li:first').html('This is List '+$(this).index());
});
$('#back').click(getHistory(0));
$('#next').click(getHistory(1));
function getHistory(n){
return function(){
if(!history[n].length){return false;}
history[(n+1)%2].push($('#list').replaceWith(history[n].last()));
history[n].pop();
$(history[(n+1)%2].id).prop('disabled',false);
if(!history[n].length){$(history[n].id).prop('disabled',true);}
}
}

Check out jQuery BBQ - http://benalman.com/projects/jquery-bbq-plugin/

Related

How to save values from option to one array cell in a loop

So I got a loop of processes. You can check it here.
So the point is my system can have different number of processes. And for each process there can be more than one studio. What I want to achieve is to save studios under one process into one array cell divided by coma. So later I could use this array and split studios to insert it to database.
My save function:
var LISTOBJ = {
saveList: function() {
$(".output").html("");
$(".studio").each(function() {
var listCSV = [];
$(this).find("input").each(function() {
listCSV.push($(this).text());
});
var values = '' + listCSV.join(',') + '';
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.debug(listCSV);
});
}
}
But it seems it doesnt work. What do I need to change to achieve what i want? Thank you
on html file, on process 1 select option add this to the class attribute process-1, and on the process 2 also add process-2 on class attribute then, modify the saveList function
var processList = {process_1 : [] , process_2 : []};
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
var process1 = $(this).hasClass('process-1');
var process2 = $(this).hasClass('process-2');
if(text) {
listCSV.push(text);
if(process1) {
processList.process_1.push(text);
} else if (process2) {
processList.process_2.push(text);
}
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
console.log(processList);
ahh, i think i have solved the first question, about the question #1. on your html file add value attribute on each option. and also remove the div class="studio" hence put the class "studio" on the select class. after that try my code on the javascript file
// everytime the save button is clicked
$('#savebutton').click(function() {
saveList();
});
// set list studio
var listCSV = [];
// your list object
var listObj = {saveList: []};
// save list function
function saveList() {
$(".output").html("");
$(".studio").each(function() {
var text = $(this).val();
if(text) {
listCSV.push(text);
}
});
listObj.saveList = listCSV;
var values = listCSV.join(', ');
$(".output").append("<input type='text' name='studio[]' value='" + values + "' />");
$("#output").append("<p>" + values + "</p>");
}

Replace prototype objects property

<script>
Croppic = function (id, options) {
var that = this;
that.id = id;
that.obj = $('#' + id);
that.outputDiv = that.obj;
};
Croppic.prototype = {
form: {}
};
init: function () {
var that = this;
var cropControlUpload = '';
if (that.options.customUploadButtonId === '') {
cropControlUpload = '<i class="cropControlUpload"></i>';
}
var cropControlRemoveCroppedImage = '<i class="cropControlRemoveCroppedImage"></i>';
if ($.isEmptyObject(that.croppedImg)) {
cropControlRemoveCroppedImage = '';
}
if (!$.isEmptyObject(that.options.loadPicture)) {
cropControlUpload = '';
}
var html = '<div class="cropControls cropControlsUpload"> ' + cropControlUpload + cropControlRemoveCroppedImage + ' </div>';
that.outputDiv.append(html);
var formHtml = '<form class="' + that.id + '_imgUploadForm" style="visibility: hidden;"> <input type="file" name="img" accept="image/*" id="' + that.id + '_imgUploadField"> </form>';
that.outputDiv.append(formHtml);
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
},
reset:function (){
var that=this;
that.init();//This initializes using init function
}
</script>
I have a crop module which does something like above.So everytime reset is called the module is initialized by using the init function.
However, the output is not coming as expected what is happening that when a reset is called more than twice, the form object shows this kind of behavior.
That is what console shows when reset is called the first time.Look for the property 0.
When the reset is called twice the result is something like this.Instead of removing the property 0 , it appended a new property 1.
This thing go on if i make more calls to the reset.
So when this happens Inspector in Mozilla shows more than one form when reset is called more than one time(Here i have called reset twice hence two forms in Inspector).
To overcome this problem i tried deleting the property 0 and even tried deleting the whole object and tried to create a new object but nothing helps.
if(that.form.hasOwnProperty("0"))
{
delete that.form["0"];// Here i even did this delete that.form;
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
}else{
that.form = that.outputDiv.find('.' + that.id + '_imgUploadForm');
}
I did everything but the same thing happens.How do i make sure it doesn't add more properties if 0 exists .If 0 exists just replace 0 by the new one.
Full Code :http://codepad.org/03EiunbL

Getting a 'Cannot find variable' error trying to access a json object

hopefully somebody can help me. The JS below, loads a JSON file and parses the counties into a select menu. It also removes duplicates. Now in the JSON feed, each item has something like this:
{
"County":"Antrim",
"Town":"Antrim Town",
"Restaurant":"Diane's Restaurant & Pizzeria"
}
What I am trying to do is in the first select menu, once the user chooses the county, the second select menu is updated with values from the son object. At the moment I'm getting a 'Cannot find variable' error and I can't work out why. Is the data array not available for some reason?
<script type="text/JavaScript">
$(document).ready(function(){
//get a reference to the select elements
var county = $('#county');
var town = $('#town');
var restaurant = $('#restaurant');
//request the JSON data and parse into the select element
$.getJSON('rai.json', function(data){
console.log(data);
//clear the current content of the select
$('#county').html('');
$('#county').append('<option>Please select county</option>');
$('#county').html('');
$('#town').append('<option>Please select town</option>');
$('#restaurant').html('');
$('#restaurant').append('<option>Please select restaurant</option>');
//iterate over the data and append a select option
$.each(data.irishtowns, function(key, val) {
county.append('<option id="' + val.County + '">' + val.County+ '</option>');
});
var a = new Array();
$('#county').children("option").each(function(x){
test = false;
b = a[x] = $(this).text();
for (i=0;i<a.length-1;i++){
if (b ==a[i]) test =true;
}
if (test) $(this).remove();
});
});
$( "#county" ).change(function() {
var myCounty = $(this).val();
console.log(myCounty);
$.each(data.irishtowns, function(key, val) {
if (val.Town === myCounty) {
town.append('<option id="' + val.Town + '">' + val.Town + '</option>');
}
});
});
});
</script>
Data is not in scope in this line
$.each(data.irishtowns, function(key, val) {
You could move this up into the callback, or use a global variable to provide access: i.e. in the callback have a line countries = data and then
$.each(countries.irishtowns, function(key, val) {

JQuery Datatable rows not deleting despite on calling clear function

Im trying to remove all the rows in jquery data tables when new data arrives in order to fill with new rows.
But the problem is despite calling clear function it simply add the result rows to previous rows.
How to clear the rows in jquery data tables . Following is the code
var table = $("#editable");
var tp = table.DataTable({
"paging": true,
"createdRow": function (row, data, index) {
$compile(row)($scope);
}
});
//more code here ajax call only from angular post
if (result != null) {
$scope.reviews = result;
$window.toastr["success"]("Loaded Successfully !", "Recent Reviews");
tp.clear().draw();
for (var i = 0; i < $scope.reviews.length; i++) {
var id = $scope.reviews[i].ID;
var checked = $scope.reviews[i].Enabled == "1" ? true : false;
tp.row.add([
$scope.reviews[i].ID,
$scope.reviews[i].AddedOn,
$scope.reviews[i].Company.Name,
$scope.reviews[i].Rate,
$scope.reviews[i].User.Name,
$scope.reviews[i].Description,
"<div class='switch'><div class='onoffswitch'><input ng-model='$scope.reviews[" + i + "].Enabled' ng-click='ChangeReviewPublishStatus(" + $scope.reviews[i].ID + ")' ng-checked='" + checked + "' class='onoffswitch-checkbox' id= 'stat" + id + "' type= 'checkbox'><label class='onoffswitch-label' for='stat" + id + "'><span class='onoffswitch-inner'></span><span class='onoffswitch-switch'></span></label></div></div>"
]).draw();
}
}
I would place that piece of code inside a $timeout. Both dataTables and angular wants to manipulate the DOM - angular wins the battle and by that dataTables never get a chance to finish its business. A $timeout will force the dataTables clear() and data population into the next digest, and ensure it is actually executed.
$timeout(function() {
tp.clear().draw();
for (var i = 0; i < $scope.reviews.length; i++) {
var id = $scope.reviews[i].ID;
var checked = $scope.reviews[i].Enabled == "1" ? true : false;
tp.row.add([
$scope.reviews[i].ID,
$scope.reviews[i].AddedOn,
//etc
]).draw();
}
});
Well, that is at least my theory - cannot replicate your scenario in full - let me know if it makes any difference.

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

Categories

Resources