Save new click change with jQuery on RELOAD (new page) - javascript

I made a dropdown with a html value change result, so after every click i get the new html value:
$("#list li a").on('click',function(){
var val=$(this).html();
$("#selector").html(val);
});
Simple enough to understand. What I'm trying to do is in the new reload, the html (val) stays on the new load. How can one do this?
I was thinking of HTML5: localStorage but really not sure if this is right?
localStorage.setItem(currentlist, $('#selector').val());
window.onload = function() {
var name = localStorage.getItem(currentlist);
}
Not sure if Im doing this right or missing something. But this is where I'm at. Is this the right way to go...or do some cookie state?

JSFIDDLE DEMO
$("#list li a").on('click',function(){
var val = $(this).html();
$("#selector").html(val);
localStorage.setItem("currentlist", val); //add to localStorage
});
and in your onload
var name = localStorage.getItem("currentlist"); //get from localStorage
$("#selector").html(name); //assign here

Related

innerHTML is not working inside a function

I'm a beginner in Javascript programming. innerHTML method is not working in a function to update content of a HTML element.
My JS code is :
$(':button').on("click", function() {
// reference clicked button via: $(this)
var buttonElementId = $(this).attr('id');
var sliceId = buttonElementId.charAt(buttonElementId.length - 1);
bringData(sliceId);
})
function bringData(id) {
var a = localStorage.getItem("Blogs")
var b = JSON.parse(a)
console.log(b[id].blogHeader)
document.getElementById("foo").innerHTML = b[id].blogHeader
}
Buttons and element which has id of "foo" are at different HTML pages. I want to update content of that element after clicking any button from other page, but it is not working. The content still remains same. What is my mistake ?
Note : If I use innerHTML property out of a function, it works and content is changing.

Set Hidden textbox using Angularjs

I am using angularjs, please see this code in http://jsfiddle.net/6XDeV/
what I want:
When click on the button add it will appear $scope.todotest value a long with the value in textbox.
My problem:
When I add the first it not show the date along with the text in textbox and if I add the second time it will appear. And I want to appear since the first time that click on add button.
Anyone know about this help me to fix please, thanks.
That's because at the first time you call addTodo the todotest is undefined.
Just move the $scope.todotest = '23' before the push, like this:
$scope.addTodo = function() {
$scope.todotest = '23';
$scope.todos.push({text:$scope.todoText,test:$scope.todotest, done:false});
$scope.todoText = '';
};
Example: http://jsfiddle.net/757d3/
You're setting the $scope variable todotest after adding a new item to your array todos.
$scope.addTodo = function() {
$scope.todos.push({text:$scope.todoText,test:$scope.todotest, done:false});
$scope.todoText = '';
$scope.todotest = '23'; // This should be done before the push
};
See updated fiddler here.
add this line $scope.todotest = '23'; before this $scope.addTodo = function() {
check this[code] http://jsfiddle.net/6XDeV/1/[/code]

Recursive IDs and duplicating form elements

I have the following fiddle:
http://jsfiddle.net/XpAk5/63/
The IDs increment appropriately. For the first instance. The issue is when I try to add a sport, while it duplicates, it doesn't duplicate correctly. The buttons to add are not creating themselves correctly. For instance, if I choose a sport, then fill in a position, and add another position, that's all fine (for the first instance). But when I click to add another sport, it shows 2 positions right away, and the buttons aren't duplicating correctly. I think the error is in my HTML, but not sure. Here is the JS I am using to duplicate the sport:
$('#addSport').click(function(){
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $('div.kpSports').first().clone();
//recursively set our id, name, and for attributes properly
childRecursive(newItem,
// Remember, the recursive function expects to be able to pass in
// one parameter, the element.
function(e){
setCloneAttr(e, $('#kpSport').val());
});
// Clear the values recursively
childRecursive(newItem,
function(e){
clearCloneValues(e);
});
Hoping someone has an idea, perhaps I've just got my HTML elements in the wrong order? Thank you for your help! I'm hoping the fiddle is more helpful than just pasting a bunch of code here in the message.
The problem is in your clearCloneValues function. It doesn't differentiate between buttons and other for elements that you do want to clear.
Change it to:
// Sets an element's value to ''
function clearCloneValues(element){
if (element.attr('value') !== undefined && element.attr('type') !== 'button'){
element.val('');
}
}
As #PHPglue pointed out in the comments above, when new positions are added, they are incorrectly replicated (I'm assuming here) to the newly cloned for
There is a similar problem with the add years functionality.
A quick fix would be to initialize a variable with a clone of the original form fields:
var $template = $('div.kpSports').first().clone();
Then change your addSport handler to:
$('#addSport').click(function () {
//increment the value of our counter
$('#kpSport').val(Number($('#kpSport').val()) + 1);
//clone the first .item element
var newItem = $template.clone();
…
});
However, there are no event bindings for the new buttons, so that functionality is still missing for any new set of form elements.
Demo fiddle
Using even a simple, naive string based templates the code can be simplified greatly. Linked is an untested fiddle that shows how it might be done using this approach.
Demo fiddle
The code was simplified to the following:
function getClone(idx) {
var $retVal = $(templates.sport.replace(/\{\{1\}\}/g, idx));
$retVal.find('.jsPositions').append(getItemClone(idx, 0));
$retVal.find('.advtrain').append(getTrainingClone(idx, 0));
return $retVal;
}
function getItemClone(setIdx, itemIdx) {
var retVal = itemTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, itemIdx);
return $(retVal);
}
function getTrainingClone(setIdx, trainingIdx) {
var retVal = trainingTemplate.replace(/\{\{1\}\}/g, setIdx).replace(/\{\{2\}\}/g, trainingIdx);
return $(retVal);
}
$('#kpSportPlayed').on('click', '.jsAddPosition', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var itemIdx = $container.find('.item').length;
$container.find('.jsPositions').append(getItemClone(containerIdx, itemIdx));
});
$('#kpSportPlayed').on('click', '.jsAddTraining', function() {
var $container = $(this).closest('.kpSports');
var containerIdx = $container.attr('data_idx');
var trainIdx = $container.find('.advtrain > div').length;
$container.find('.advtrain').append(getTrainingClone(containerIdx, trainIdx));
});
$('#addSport').click(function () {
var idx = $('.kpSports').length;
var newItem = getClone(idx);
newItem.appendTo($('#kpSportPlayed'));
});

Jquery mobile - Click button to add to UL

i am trying to build an application that when the user enters text into a textbox on a jquery based mobile app and clicks save it adds it to the list on the screen
so by default i won't have a list, but as the user adds an item the list should be created or if the list already exists, the new item added as a new list item.
in terms of saving it i will work on that after, for the time being i just want to dynamically append to a ul in jqm on the screen
Can someone assist with code that may help with this. it is giving me an item added saying "item undefined" however numslist is my list and txtbox is the textbox so im not sure where i am going wrong
thanks
<script>
var $txtbox = $("#txtbox").val();
var count = 0;
$("#main").live("pagecreate", function(event) {
$("#numlist").listview({create: function(event, ui) {
$("#addBtn").bind("click", function(event, ui) {
var str = "<li><a href='#'>Item " + ($txtbox) + "</a></li>";
$("#numlist").append(str);
$("#numlist").listview("refresh");
});
$("#removeBtn").bind("click", function(event, ui) {
// if (--count < 0) {
// count = 0;
// return;
// }
$("#numlist").find("li").remove();
$("#numlist").listview("refresh");
});
}});
});
</script>
Well, you can use localstorage, that way you won't need to code extra functions that save/store data.
try this:
var $lst = $('#productList');
$("#btnID").on("click",function() {
var $txtBox = $("#txtBox");
var $li = $('<li/>').html($txtBox.val());
$lst.append($li).listview('refresh');
$txtBox.val("");
});
working fiddle here: http://jsfiddle.net/REthD/21/
If I understood your question correctly, something similar to the following should work for you:
$('input[type=button]').on('click', function() {
var ul = $('#ul_id').length > 0 ? $('#ul_id') : $('<ul />', { id: 'ul_id'}).appendTo('#parent');
$('<li />').text($('#textbox').val()).appendTo(ul);
});
The first line in the event will check if the element exists, if it does, it returns that, otherwise, creates a new and appends to the specified parent element. Then, it appends a to the with the text from the textbox.
jsFiddle example

JQuery: loosing the <tr> id when using replaceWith() method

I am trying to implement a function which will change the elements order in a table. The logic is very easy: Each TR (except the first and the last ones) has a button_up and a button_down. When the user clicks one of those buttons, the element will change his place with the one above or below.
To do this, I am using jQuery and each TR has a unique Id and the buttons have a common class.
When a button with the specific class is clicked, I am executing this JavaScript code:
$('.upArrow').click( function(something)
{
var id = $(this).attr("id");
var n=id.split("_");
var new_id = '#row_'+n[1];
var parent =$(new_id);
var prev = $(new_id).prev();
swap(prev, parent);
init_authors_list_ordering();
});
$('.downArrow').live('click', function()
{
var id = $(this).attr("id");
var n=id.split("_");
var new_id = '#row_'+n[1];
var parent =$(new_id);
var next = $(new_id).next();
swap(next, parent);
init_authors_list_ordering();
});
}
function swap(a, b, direction)
{
var html = a.wrapInner('<tr></tr>').html();
a.replaceWith(b.wrapInner('<tr></tr>').html());
b.replaceWith(html);
}
The problem is that: The first time, everything works fine (my funxtion is not finished, I have to set some other parameters on change but the logic is there). But then, The two elements who changed their place have lost the TR's id, so they can't be touched anymore.
I don't know why the id is lost. This is the replaceWith() method.
Any help is welcome. Thank you.
To swap the elements, simply do:
function swap(a, direction, b) {
a[direction](b);
}
and call like:
var firstElem = $('#divID'),
secondElem = $('#divID');
swap(firstElem, 'before', secondElem); // or after, whatever you need ?
FIDDLE
Your constant <tr></tr> has no id attribute, so it ends up with no id attribute.
EDIT:
Here is what I reference:
function swap(a, b, direction)
{
var html = a.wrapInner('<tr></tr>').html();
a.replaceWith(b.wrapInner('<tr></tr>').html());
b.replaceWith(html);
}

Categories

Resources