How to call own function from click method - javascript

I know it sounds stupid, but i have no idea how to call my function from "onclick" function?
I made own class and what i wanna do is to call my function inside a class.
I have tried various stuff inside that onclick function:
function(){this.getWidth()}
this.getWidth()
Test.getWidth()
function Datagrid(_parent, _data)
{
this.table = [];
this.parent = $("#"+_parent)[0] ? $("#"+_parent) : ($("."+_parent)[0] ? $("."+_parent) : ($(+_parent)[0] ? $(_parent) : null));
this.data = _data;
this.Datagrid = function(parent,data)
{
this.setParent(parent);
if(data != null)
this.setData(data);
return this;
}
this.setParent = function(parent)
{
return this.parent = $("#"+parent)[0] ? $("#"+parent) : ($("."+parent)[0] ? $("."+parent) : ($(+parent)[0] ? $(parent) : null));
}
this.getParent = function()
{return this.parent;}
this.setData = function(data)
{this.data = data;}
this.buildTable = function()
{
var dtTbl = [];
dtTbl.push('<table class="TimeSheetmainTable" cellpadding="10" cellspacing="0" border="0">');
var style;
//Header//////////////////////
dtTbl.push('<tr class="header">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
dtTbl.push('</tr>');
//Content//////////////////////
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
dtTbl.push('<tr ' + style + ' >');
for(var c in this.data.row[r].cell)
{
dtTbl.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
}
dtTbl.push('</tr>');
}
//Footer//////////////////////
dtTbl.push('<tr class="footer">');
for (var cell in this.data.row[0].cell) {
dtTbl.push('<td> </td>');
}
dtTbl.push('</tr></table>');
this.parent.html(dtTbl.join(''));
}
this.buildTableDiv = function()
{
var tableString = [];
//Header//////////////////////
tableString.push('<div class="container"><div class="header"><table><tr id="header">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td>' + this.data.row[0].cell[cell].id + '</td>');
}
tableString.push('</tr></table></div>');
//Content//////////////////////
tableString.push('<div class="content"><table>');
var TD1 = new Object();
var TD2 = new Object();
for(var r in this.data.row)
{
if (r % 2 == 0) { style = 'class="r1" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r1\'"'; }
else { style = 'class="r2" onmouseover="this.className=\'hover\'" onmouseout="this.className=\'r2\'"'; }
for(var c in this.data.row[r].cell)
{
if(c == 0)
{ if(TD1.value != this.data.row[r].cell[c].value){
TD1.value = this.data.row[r].cell[c].value;
TD1.show = true;
}
else
TD1.show = false;
}
if(c == 1)
{ if(TD2.value != this.data.row[r].cell[c].value){
TD2.value = this.data.row[r].cell[c].value;
TD2.show = true;
}
else
TD2.show = false;
}
if(TD1.show && c == 0){//First line
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '"><input type="button" class="arrow_down" /> ' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 1; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr>');
}
else if(TD2.show && c == 1)//Second line
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value + '</td>');
for(var c = 0; c < this.data.row[r].cell.length - 2; c++)
{
tableString.push('<td>&nbsp</td>');
}
tableString.push('</tr><tr id="content" ' + style + ' ><td> </td><td> </td>');
}
else if(!TD2.show && c == 1)//third line (distincts second cells name)
{
tableString.push('<tr id="content" ' + style + ' >');
tableString.push('<td> </td><td alt="' + this.data.row[r].cell[c].id + '"> </td>');
}
else if(c > 1)//Rest filling (not ordered stuff)
{
tableString.push('<td alt="' + this.data.row[r].cell[c].id + '">' + this.data.row[r].cell[c].value.replace(""," ") + '</td>');
}
}
tableString.push('</tr>');
// $(".arrow_down").children(":nth-child(1)").click(function(){alert("test");});
}
tableString.push('</table></div>');
//Footer//////////////////////
tableString.push('<div class="footer"><table><tr id="footer">');
for (var cell in this.data.row[0].cell) {
tableString.push('<td> </td>');
}
tableString.push('</tr></table></div></div>');
this.parent.html(tableString.join(''));
// Setting width to all cells
for (var i in this.data.row[0].cell)
{
cell = parseInt(i)+1;
var h = this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var c = this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var f = this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width();
var width = h > c ? h : (c > f ? c : f);
this.parent.children(":first").children(".header").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".content").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
this.parent.children(":first").children(".footer").children("table").children("tbody").children("tr").children(":nth-child("+ cell +")").width(width);
}
// this.activateScroller(0);
}
this.getScrollerWidth = function()
{
var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
// Append our div, do our calculation and then remove it
$('body').append(div);
var w1 = $('div', div).innerWidth();
div.css('overflow-y', 'scroll');
var w2 = $('div', div).innerWidth();
$(div).remove();
return (w1 - w2);
}
this.activateScroller = function(value)
{
var d = [];
d.push('<div style="height: ' + this.parent.children(":first").children(".content").height() + '; width:20px; background:#FFF"><div style="background:#333; height:200"> </div></div>');
this.parent.children(":first").children(".content").scrollTop(value);
}
expandParent = function()
{
alert(this.parent);
}
};
i am kinda makig datagrid based on javascript. i am not allowed to use jQuery UI.
My datagrid is made from tables. now i try to add a button inside a td element like User Name
The problem is that i cant access my function inside my class without making instance. is it even possible to do that without making an instance?

Once your html is generated using your generateHTML function, the handler for onclick on div looses context of what "this" is. To be more specific, this in onclick handler for div refers to that div node in DOM.
To access getWidth method you have to make it available to global context or (better solution) do something like this:
// new version of your generateHTML function
this.generateHTML() {
var str = [];
str.push('<div><input type="button" value="button"/></div>');
var that = this;
$("#testDiv").append(str.join('')).find('button:first').click(function() {that.getWidth()});
}
EDIT:
To further explain how code above works, here's simplified example with comments.
​​Test = function() {
this.generate = function() {
var newnode = $('<button>click me</button>');
$("body").append(newnode);
// "cache" this in a variable - that variable will be usable in event handler
var that = this;
// write event handler function here - it will have access to your methods by using "that" variable
newnode.click(function(e) {
// here this refers to button not Test class
// so we have to "reach" to outer context to gain access to all methods from Test
that.doSomething('learn');
})
}
this.doSomething = function(x) {
alert('do it: '+x);
}
}
// initialize part
// make instance of Test "class"
t = new Test();
// generate the button (clicking on a button will essentialy fire Test.doSomething function in a context of "t"
t.generate();

Related

How do I remove just the current instance of the array, not all instances of the array?

How do I remove just the current instance of the array, not all instances of the array?
var persons = [];
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
Created new node instances.
for (var l in persons) {
var listNode = document.createElement("LI");
var btn = document.createElement("BUTTON");
btn.innerHTML = "Remove";
showList.appendChild(listNode);
showList.appendChild(btn);
Displays pushed instances correctly.
listNode.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>'
}
Tried a few variations of the following function but just empties the array, or at least wont return the amended array.
btn.onclick = function() {
var index = Array.indexOf(persons[l]);
persons.splice(index, 1);
return persons;
}
if (showAllButton.value=="Show Contacts") {
showAllButton.value = "Hide Contacts";
showList.style.display = "block";
}
else if (showAllButton.value = "Hide Contacts") {
showAllButton.value = "Show Contacts";
showList.style.display = "none";
}
}
probably bind l, remove the element at index l, then redraw the dom somehow.:
btn.onclick = function(l) { //take over the bound l
persons.splice(l, 1);
//some kind of redraw
showAllButton.click();
}.bind(null,l);//bind l
Something like this should work as expected (sorry, blind coding, have no time to test now)
var persons = [];
function removePerson(index) {
persons.splice(index, 1);
renderList();
}
function clearList() {
while (showList.firstChild) {
showList.removeChild(showList.firstChild);
}
}
function renderItem(person, index) {
var item = showList.appendChild(document.createElement("LI"));
var label = item.appendChild(document.createElement("SPAN"));
label.innerHTML = persons[i];
var btn = item.appendChild(document.createElement("BUTTON"));
btn.innerHRML = "Remove";
btn.onclick = removePerson.bind(null, index);
}
function renderList() {
clearList();
persons.forEach(renderItem);
}
Not a kind of best practices, but seems to be working.
Final Working Code, thank you!
showAllButton.onclick = function() {
while (showList.firstChild)showList.removeChild(showList.firstChild);
for (var l in persons) {
var list = showList.appendChild(document.createElement("LI"));
list.innerHTML =
'<p><b>Full Name:</b> ' + persons[l].firstName +' ' + persons[l].lastName + '</p>' +
'<p><b>Phone:</b> ' + persons[l].phone + '</p>' +
'<p><b>Address:</b> ' + persons[l].address + '</p>';
var btn = showList.appendChild(document.createElement("BUTTON"));
btn.innerHTML = "Remove";
btn.onclick = function(l) {
persons.splice(l, 1);
showAllButton.click();
}.bind(null,l);
}

Global variable does not increment

Most of the action is in the function next. The other functions are provided for context. The global variable tally increments as it should when the right answer is selected. However the variable nr is not incremented and I can't figure out way it is not.
You can see that I commented out that the next function returned an object with tally and nr and assigned those values in the event listener. When I did it that way, it worked. But it should work the other way as well, right.
var nr = 0;
var tally = 0;
function onLoadEvent(nr) {
//alert('onload');
var quiz = document.getElementById('quiz');
var question = allQuestions[nr];
var next = quiz.lastElementChild;
var qHeader = "<h2>" + question.question + "</h2>";
var q = "";
for(var i=0;i<question.choices.length;i++){
q = q + '<p><label for="a' + i + '">' +
'<input type="radio" id="a' + i + '" name="q" value="' +
i + '">' + question.choices[i] + '</label></p>';
}
quiz.innerHTML = qHeader + q + next.outerHTML;
//next = document.getElementById('next');
}
function getChecked(){
var radios = document.getElementsByName('q');
var radio;
for(var i=0;i<radios.length;i++){
if(radios[i].checked){
radio = radios[i];
break;
}
}
return radio;
}
function next(nr){
if (getChecked() !== undefined) {
var answer = getChecked();
if(answer.value == allQuestions[nr].correctAnswer){
tally = tally + 1;
}
nr = nr + 1;
if (nr>=allQuestions.length){
alert("You got " + tally + " points!");
} else {
onLoadEvent(nr);
}
} else {
alert('You need to check a radio button');
}
//return {nr: nr, tally: tally};
}
var form = document.getElementById('quiz');
form.addEventListener('click', function(event){
if(event.target.id === 'next'){
next(nr);
//nr = obj.nr;
//tally = obj.tally;
} else if(event.target.id === 'prev'){}
}, false);
window.addEventListener('load', function(event){onLoadEvent(nr);}, false);
You are accepting parameters with same name nr which is hiding global scope nr.
Solution to your problem is remove nr as parameter. So use function onLoadEvent() instead of function onLoadEvent(nr)

I need Javascript syntax and logic advice

I have a two part question. The first is that I tried to replace all of my document.write with innerHTML and now nothing generates on the page correctly. The second part of my question is that I can't figure out the logic on my toggleCurrent function so that I can hide show the currently displayed view. example - if the thumbnail view is visible I want to hide/show or if the full view is visible I want to hide/show that. http://jsfiddle.net/5M3k7/
//Creating generic Object
function Person(name,age,biog,thumb,char,bg,cider) {
this.fullName = name;
this.age = age;
this.biog = biog;
this.thumb = thumb;
this.char = char;
this.bg = bg;
this.cider = cider;
}
//Creating new Objects
var jay = new Person ("Jay Jones",24,"Story","img","guy","bg","Fleet",true);
var jai = new Person ("Jai Janes",23,"Story","img","gal","bg","Sleet",true);
var dan = new Person ("Dan Dones",19,"Story","img","guy","bg","Leet",true);
var den = new Person ("Den Danes",49,"Story","img","guy","bg","Treat",true);
var dun = new Person ("Dun Dunes",20,"Story","img","guy","bg","Meet",true);
var vim = new Person ("Vim Vanes",22,"Story","img","guy","bg","Meat",true);
//Defining arrays
var characters = [jay, jai, dan, den, dun, vim];
//For loop goes though character array and prints it out.
var thumbs = function() {
var full = document.getElementById('full');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
}
return;
};
var full = function() {
var thumb = document.getElementById('fullthumb');
var cLength = characters.length;
for (var i = 0; i < cLength; i++){
thumb.innerHTML = '<div class="fullwrap"><div class="bg"><div class="fullcont">Name: '
+ characters[i].fullName + '<br/> Age:' + characters[i].age + '<br/>Cider:' + characters[i].cider + '<div class="char"></div></div></div></div>';
}
return;
};
//Toggle Function
function toggleMenuDiv() {
var full = document.getElementById('full');
var thumb = document.getElementById('fullthumb');
var butt = document.getElementById('button');
if (full.style.display == 'none') {
full.style.display = 'block';
thumb.style.display = 'none';
butt.innerHTML = 'THUMB VIEW<span class="arrow-e"></span>';
}
else {
full.style.display = 'none';
thumb.style.display = 'block';
butt.innerHTML = 'FULL VIEW<span class="arrow-e"></span>';
}
}
//Toggle Function
function toggleCurrent() {
var chng = document.getElementById('change');
var thumb = document.getElementById('fullthumb');
var full = document.getElementById('full');
while (full.style.display == 'none')
{
if(thumb.style.display == 'block') {
chng.innerHTML = 'HIDE<span class="arrow-n"></span>';
}else{
thumb.style.display = 'none';
chng.innerHTML = 'SHOW<span class="arrow-s"></span>';
}
}
}
Because you keep overriding the last thing entered in.
full.innerHTML = '<div class="wrap"><div class="cont">' + "Name: " + characters[i].fullName + '<br/>' + 'Age: ' + characters[i].age + '<br/>' + 'Cider: ' + characters[i].cider + '</div></div>';
You are need to append to the innerHTML
full.innerHTML = full.innerHTML + '<div class="...

how to create two different nameSpaces in one same nameSpace avoiding covering the first one?

i want to use two string(which i dont know their content) to create two nameSpace.And i dont want to create a new one if the nameSpace exists.
here is my code:
function createNameSpace(nameSpace)
{
var spaceArr = nameSpace.split(".");
var curSpace = window;
//judge if this nameSpace exists.
var i;
for(i in spaceArr)
{
curSpace = curSpace[spaceArr[i]];
if(curSpace)
window.alert("nameSpace1:" + nameSpace + "\ncurSpace do exists:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
else
{
curSpace = {};
window.alert("nameSpace1:" + nameSpace + "\ncurSpace not found:" + curSpace + "\ni:" + i + "\nspaceArr[i]:" + spaceArr[i] + "|");
break;
}
}
//now curSpace must have been created.
i++;
//window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
//create the nameSpace
for(;i < spaceArr.length; i++)
{
//window.alert("nameSpace2:" + nameSpace + "\ni:" + i + "\nspaceArr.length:" + spaceArr.length);
if(i == 0)
{
window[spaceArr[i]] = {};
curSpace = window[spaceArr[i]];
}
else
{
//window.alert("nameSpace3:" + nameSpace + "\ncurSpace[spaceArr[i]]:" + curSpace[spaceArr[i]]);
curSpace[spaceArr[i]] = {};
curSpace = curSpace[spaceArr[i]];
}
}
return curSpace;
}
the problem is,if i send"myTest.myNameSpace"and"myTest.monaNameSpace" into this func,it all alert"curSpace not found",which should be "curSpace do exists:" when i send "myTest.monaNameSpace" . i can`t tell where the mistakes are,can someone tell me?
I think your algorithm is a little to complex. I refactored it a little and added a test to it and verified it worked in the console. I have also written this code several times, so i am pretty sure i have hit your requirements
function createNameSpace(nameSpace)
{
var spaceArr = nameSpace.split(".");
var curSpace = window;
//judge if this nameSpace exists.
var i = 0;
for(i = 0;i < spaceArr.length; i++)
{
var next = spaceArr[i];
console.log(curSpace, next);
if(curSpace[next] == undefined)
{
curSpace[next] = {};
curSpace = curSpace[next]
}
else
{
curSpace = curSpace[next];
}
}
return curSpace;
}
createNameSpace("myTest.myNameSpace");
console.log(myTest.myNameSpace);
myTest.myNameSpace.myName = "Leat Hakkor";
createNameSpace("myTest.monaNameSpace");
console.log(myTest.monaNameSpace);
console.log(myTest.myNameSpace.myName);

get text from attribute and format it

I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
​
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE

Categories