Duplicate Object after .click() JQuery - javascript

I need a help,
i have .click() event for adding some value into my table.
$("#ButtonSave").click(function()
{
var someObject: myCurrentObject = new myCurrentObject();
someObject.A = String($("someInputTextId").val());
someObject.B = String($("someInputTextId").val());
}
});
for first click, after i put console.log(someObject); show correct result. and in second click, someOject value already flushed, but become duplicate.
any solution?

Related

'this' and click handler doesn't seem to go well together for me

I am having some trouble with my jQuery code. I am building a solution with pagination, I have one 'paginate' function (line 87) that I want to use on whatever array is needed to be manipulated.
This is the paginate function that has two parameters. It's the "selected" argument that seems to mess things up because when I call it in the next code sample (the button click function) the $(this) keyword is referring to the button. Not the selected anchor as intended.
function paginate(list, selected) {
// Removes all the items from the document. But because we are storing
// the items in an array, nothing is really lost.
removeStudents();
// Declaring the array that is to be filled with the students needed
// based on which pagination anchor element is clicked.
var arrToShow = [];
// Variable that decides where the counting of the students should start
// based on which pagination anchor element has the class of 'active'.
var headIndex = selected * maxStudents;
// Variable that goes together with the headIndex.
var tailIndex = headIndex - 10;
// Pushes the students, that have been chosen by the parameters of the function,
// to the arrToShow array.
for ( var i = tailIndex; i < headIndex; i++ ) {
arrToShow.push(list[i]);
}
// Displays all of the objects within the arrToShow array.
for ( i = 0; i < arrToShow.length; i++ ) {
$(".student-list").append(arrToShow[i]);
}
I have two parameters in the function: the list itself and which pagination anchor element that is currently active, or clicked. The issue seems to be that the $(this) refers to the button (line 57) when I implement the pagination function inside of another function (I am referring to the button click function on line 57).
This is the button function. It only works right now because I put a '1' for the second argument. I'd like for it to be like a global variable there that specifies which anchor argument that's selected.
function buttonClicked() {
removeStudents();
// Store what's typed in to the search input in a variable.
var userSearch = $("input").val();
// Creating an array for the successfully searched array objects.
var userSearchArr = [];
// Iterating through every single student, looking for a match, if a match
// is found, push it to the userSearchArr, then appending the objects
// within that array to the student list container.
$.each(allStudentsArr, function() {
var studentName = $(this).find("h3").text();
var filterThrough = studentName.indexOf(userSearch);
console.log(filterThrough);
if (filterThrough !== -1) {
userSearchArr.push($(this));
}
});
constructPagPages(userSearchArr.length);
paginate(userSearchArr, 1);
}
Is there some way of making the $(this) keyword within the click handler global, so that it refers to the click handlers $(this) and not to the $(this) that belongs to the function in which I'm calling the paginate function?
This is the paginationClicked function. The culprit. It works fine to call the pagination function inside of that since the $(this) keyword refers to the anchor element. However, it does not when I call the pagination function within the buttonClicked function.
function paginationClicked() {
// Removes all the sibling anchor elements classes.
$(this).parent().parent().children().children().removeClass("active");
// Adds the class active to the selected anchor.
currentPagPage = $(this).text();
console.log(currentPagPage);
paginate(allStudentsArr, $(this).text());
}
This is the event handlers:
// Event click handler that targets the pagination buttons.
$(".pagination a").click(paginationClicked);
$("button").click(buttonClicked);
Please feel free to ask if something seems unclear. I have been on this for hours and I can't seem to find a solution.
Some guidelines would be hugely appreciated. Cheers.
Here is my code:
https://github.com/SebastianPeterAndersson/Pagination-And-Content-Filter/blob/master/js/pagination-content-filter.js
Your problem is that you construct totally new list of anchor when someone searches for something.
When you remove the old pagination, all anchor would be gone, along with their event handlers. You need to move the event registration into your constructPagPages function
move this:
// Event click handler that targets the pagination buttons.
$(".pagination a").click(paginationClicked);
into your constructPagPages function, after you construct the pagination.
Have a look here: http://codepen.io/mrducnguyen/pen/xOoLPV

Polymer reset property

I use the [[]] binding in polymer. Their is a way/function to get the first Object as it was as rendered?
My problem is that I change the object in the element and then I want to reset the element to be as it was before the inside change.
I thought to deep copy the object but then it make problem with the polymer functions on the object.
<custom-elem item=[[item]]></custom-elem>
in original
item={a:123,b:234}
In the custom element I change the values of item to be
{a:241,b:382}
How can I get the original item inside the custom-elem?
Thanks.
I could think of two solutions
assign values as below
<custom-elem item-orginal=[[item]] item=[[item]]></custom-elem>
In your custom-elem when ever you want to reset the item call a function that will reset the value.
resetItem: function() {
this.item = this.itemOriginal
}
In your custom-elem, fire a custom event whenever you want to reset the value, like below.
resetItem: function() {
this.fire('custom-item-reset')
}
In the host, listen for this event and reset the item value.
<custom-elem id="customElem" item=[[item]] on-custom-item-reset="resetCustomItem"></custom-elem>
resetCustomItem: function() {
this.$.customElem.item = this.item;
}
Edit: The code is not formatting clearly. So made some modifications.

Protractor: can't get repeater element

I'm testing basic example from https://angularjs.org/ called "Add new control".
The problem is that after adding new value to repeater I can't obtain any element . Only first one.
...
var listRepeater = by.repeater('todo in todoList.todos');
var list = element.all(listRepeater);
expect(list.count()).toEqual(2);
addNewElement();
expect(list.count()).toEqual(3);
expect(list.get(0).element(by.model("todo.done")).getAttribute("checked")).toEqual("true");
expect(list.get(2).element(by.model("todo.done")).getAttribute("checked")).toEqual("true");
After adding new element check on element's count is Ok: it's equal ti 3 and I know that new values was added properly. And I can clearly get right "checked" property of first element (it's disabled by default). But when I'm trying to get(2) element I have error about null object. Same with the get(1). Only get(0) works fine. But 2 rows repeater have by default with out a doubt.
The problem is that the second and the third elements are unchecked and don't have a checked attribute - this is why you are getting null.
Instead, a correct way to check if a checkbox is checked is to use isSelected():
expect(list.get(0).element(by.model("todo.done")).isSelected()).toEqual(true);
expect(list.get(2).element(by.model("todo.done")).isSelected()).toEqual(false);
Worked for me.
It might be a promise/synchronization/refreshing issue. See if this works, if yes, you need to start using promises.
it("your test", function(done){
var listRepeater = by.repeater('todo in todoList.todos');
var list = element.all(listRepeater);
expect(list.count()).toEqual(2);
addNewElement();
browser.sleep(2000);
setTimeout(function(){
var listRepeater = by.repeater('todo in todoList.todos');
var list = element.all(listRepeater);
expect(list.get(2)
.element(by.model("todo.done"))
.getAttribute("checked")).toEqual("true");
done();
}, 2000);
});

giving a variable a unique name javascript/jquery

I'm trying to set up a function to run 1.5 seconds after a keyup event in a textarea. But, if another keyup event occurs in the same area I'd like to either extend the time to 1.5 seconds again or cancel the old function and update it with the new function.
To make things even more interesting xD
There are multiple textarea, each has their own unique ID. I'd like for it to only cancel if the keyup event is from the same textarea.
Here is an example of what I've been trying to do.
$(document).on("keyup",".edit_main textarea",function(e){
location_val = //textareas unique ID
curval = $(this).val();
blue = "blue";
UNIQUE_VARIABLE = blue+location_val;
clearTimeout(UNIQUE_VARIABLE);
UNIQUE_VARIABLE = setTimeout(function(){
// do cool stuff
}, 1500);
});
This way it will only clear once, but it gets overwritten. So I tried using an array but I'm not sure that you can store a Timeout with that.
If my question is too vague, please say so and I will try to be more detailed.
For the timeout itself you would not need unique ids, you could use the .data() functionality of jQuery to have a unique timeouts for every element.
$(document).on("keyup",".edit_main textarea",function(e) {
var textArea = $(this);
var curval = textArea.val();
var blue = "blue";
clearTimeout( textArea.data().keyupTimeout );
textArea.data().keyupTimeout = setTimeout(function(){
// do cool stuff
textArea.val('the cool result');
}, 1500);
});
This is way more complicated than it needs to be. It seems you're having issues with scope. Have a look at the documented code solution below. Also, you can take a look at the jsFiddle as well. Hope this is helpful!
//This needs to be declared OUTSIDE the function.
var unique;
//No need to use $(document), target your textareas directly.
$('.edit_main textarea').on('keyup', function(e){
//$(this) doesn't work here. Use e (an argument for the event). e.target.id gets the textarea's id.
var location_val = e.target.id;
//e.target.id returns just the id.
//We need to prepend the CSS selector for jQuery to find the element.
var curval = $('#'+location_val).val();
//I don't see the point of blue = 'blue', so I omitted it.
//Clear the timeout first if any.
clearTimeout(unique);
//Set a new one.
unique = setTimeout(function(){
//Do something cool. Like telling you what's in the textarea.
alert(curval);
}, 1500);
});

Array of HTML buttons with on click event to return an attribute

I am trying to create an array of buttons with an onclick event alerting an attribute.
the buttons are created with no problem and every time I create a problem I set up an alert of the attribute. this works perfect.
Every time you press a button, the right function is called, and it works great, but for some reason I get the second alert to say "undefined"
Just look at the code, it explains it self better then I can.
var i = 0
var insertframe = function () {
savebutton[i].index = i
//this works!
alert(savebutton[i].index)
savebutton[i].click(function (event) {
//this returns "undefined"
alert(savebutton[i].index)
})
i++
}
Solution:
instead of naming the object, I had to use "this" instead so, instead of:
savebutton[i].index
use:
this.index

Categories

Resources