JavaScript error with eventListener - javascript

I'm getting an error which I'm not quite sure what to make of. Anyway, before I go on to that, I found out about Unobtrusive JavaScript, at first I was just going to add an "OnClick" to my HTML but then found out that isn't a very good thing to do.
Anyway, so I did that and turned up with this code which isn't quite finished yet, but I wanted to try it out anyway before I went in and made any other changes.
window.onload = function findSubmitButton(){
var button = document.getElementsByClass("send_info").addEventListener("click", retrieveInputText());
}
function retrieveInputText(){
var inputArray = document.querySelectorAll("#container_id input[type=text]");
var finalArray;
for (var i in inputArray){
if(inputArray[i].type == "text"){
finalArray.push(i);
}
alert("done");
}
}
The error chrome's console gives me is this: Uncaught TypeError: undefined is not a functionfindInputs.js:5 findSubmitButton
There was also something I wanted to know, I want to be able to use this script with any other sort of input form, so instead of directly identifying the button for this page, I used a class identifier, this way, it works with any page. The only way there would be any issues would be if I had two buttons of the sort, as it is right now, any page with that sort of information only has one button for such procedures. I would appreciate if someone helped me out with this, I'm new to JavaScript.

getElementsByClassName(), returns an array, not an element so it does not have the addEventListener method, also you need to pass a function reference
window.onload = function findSubmitButton() {
var button = document.getElementsByClassName("send_info")[0].addEventListener("click", retrieveInputText);
}
Also you need to initialize the array var finalArray = [];
window.onload = function findSubmitButton() {
var button = document.querySelector(".send_info").addEventListener("click", retrieveInputText);
}
function retrieveInputText() {
var inputArray = document.querySelectorAll("#container_id input[type=text]");
var finalArray = [];
for (var i in inputArray) {
if (inputArray[i].type == "text") {
finalArray.push(i);
}
}
alert("done:" + finalArray);
}
Demo: Fiddle

Related

Module pattern in JavaScript

I'm practicing my JS skills (I'm new at it). I'm trying to get the specific element that triggered the event and display it in a span element. But I don't know what I'm doing wrong, when I click the button nothing happens.
This is for a calculator program that I'm doing but using module pattern I think it's called.
var Calculator = {
init: function(){
var button = document.querySelectorAll("[class^='button']");
button.onclick = this.writeEvent;
},
write: function (element){
document.getElementById("display").innerHTML = element;
},
writeEvent: function(event){
write(target.event)
}
}
Calculator.init();
There are several problems with the posted code.
var button = document.querySelectorAll("[class^='button']");
button.onclick = this.writeEvent;
The result of querySelectorAll is a NodeList.
Assigning to its onclick property will not achieve what you want.
You want to assign to the onclick property of each individual node.
But actually that's not so simple, we'll need to come back to this.
writeEvent: function(event){
write(target.event)
}
One problem here is that target is undefined.
Surely you meant event.target.
Another problem is that write is also undefined.
Perhaps you meant this.write,
but that won't actually work well.
The problem is that when writeEvent is called from a click event,
it won't be called on the object,
so this will not be bound to the calculator object,
and the this.write call will raise an exception.
There's a way to overcome this,
by binding the onclick handler function to the object when setting it.
Putting the above together:
var Calculator = {
init: function() {
var nodeList = document.querySelectorAll("[class^='button']");
var callback = this.writeEvent.bind(this);
nodeList.forEach(item => item.onclick = callback);
},
write: function(element) {
document.getElementById("display").innerHTML = element;
},
writeEvent: function(event) {
this.write(event.target);
}
}
Calculator.init();

Calling a javascript function that contains dynamic parameters

I am trying to call a javascript function that contains dynamic variable as a parameter. I think i am failing in the syntax to get this particular function executed. I have tried a few combinations and none of them seem to work. Please can someone advise..
for( i=0; i<succeedList.length; i++){
var file_uniq_id = succeedList[i].filename_uniq;
//Creating dynamic button
var subm_btn = document.createElement("INPUT");
subm_btn.setAttribute("onclick", "UploadMyScript.submitTitle(this.id,'+file_uniq_id+')");
p_titleBtn.appendChild(subm_btn);
}
UploadMyScript.submitTitle = function(id, uniqID){
// Does something ....
}
My problem is I cannot appear to pass on the 'file_uniq_id' value to UploadMyScript.submitTitle().
Why not use an event listener ?
subm_btn.addEventListener('click', function () {
UploadMyScript.submitTitle(subm_btn.id, file_uniq_id); },
false);

Javascript: uncaught typeerror undefined is not a function for object methods

I make a simple quiz game. Here is some relevan methods that i have inside one object.
But doesn't work. I always get an error within 'rightAnswerGot' function. Console drops
"uncaught typeerror undefined is not a function for object methods" for this.addVariantsHtml(this.updateCharacter());
BasicGame.Game.prototype = {
actionOnClick: function (button) {
var log;
if(button.value==this.char_bubble.text) {
setTimeout(this.rightAnswerGot,1000);
} else {
// wrong
swoshsound.play();
}
console.log(log);
},
rightAnswerGot: function (){
this.addVariantsHtml(this.updateCharacter());
},
addVariantsHtml: function(id) {
this.answer = this.getAnswersVariants(id);
for (var i = 0; i < 6; i++) {
this.button[i].value = this.answer[i]['trans'];
this.button[i].char_id = this.answer[i]['id'];
this.ans_text[i].setText(this.answer[i]['trans']);
}
},
updateCharacter: function() {
var i = this.getRandomCharacter();
console.log("updateCharacter: "+i + " " +this.chars[i]);
this.char_bubble.setText(this.chars[i].getPath());
return i;
}
}
The aim is to froze the game for a second, when user choose the right answer, and than go to next question. Any ideas why does it happens?
Thanks
Looks like a classic JavaScript scope issue to me. However as you've tagged this question as using Phaser, I would suggest you use a Phaser Timer event to avoid scope problems. Specifically:
setTimeout(this.rightAnswerGot,1000);
replace it with:
this.game.time.events.add(Phaser.Timer.SECOND, this.rightAnswerGot, this);
Which will create a single 1 second timer that fires only once, calling your function at the end of it. You can use 1000 instead of Phaser.Timer.SECOND of course.
I would image that whats happening is that its trying to call the this.addVariantsHtml method, before its calling this.updateCharacter and getting the ID.
So your probably expecting that when it runs, for it to be something like:
this.addVariantsHtml(1);
But its actually trying to run
this.addVariantsHtml(this.updateCharacter());
So just do this:
var id = this.updateCharacter();
this.addVariantsHtml(id);
Either that or you need to look into method chaining/piping, which is just complicated and doesnt need to be used for this situation, but is interesting :)
Ok I found something that made it work!!
Here is a solution:
actionOnClick: function (button) {
var log;
if(button.value==this.char_bubble.text) {
var context=this;
setTimeout(function() {
context.addVariantsHtml(context.updateCharacter());
},1000);
} else {
// wrong
swoshsound.play();
}
console.log(log);
},

how to get a property name which represent a function in JS

This is some JS code
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr)
{
window[methodName] = function()
{
console.log(methodName);
}
}
My problem is that how to get the name of a function in JS.
In JS, use this.callee.name.toString() can get the function name. But in this situation, it is a null value. How can i get the 'funName' string?
Sorry, I didn't make it clear.
I want to create functions in a for loop, all these functions has almost the same implementation which need its name. But others can call these functions use different name.I want to know what methodName function is called.
it seems a scope problem.
Try this:
var methodArr = ['firstFunc','secondFunc','thirdFunc'];
for(var i in methodArr) {
var methodName = methodArr[i]; // <---- this line missed in your code?
window[methodName] = (function(methodName) {
return function() {
console.log(methodName);
}
})(methodName);
}
window['secondFunc'](); // output: secondFunc

strange javascript IE bug, variable in class clears

I've got a problem, so:
var pager = new Array();
var Imtech = {};
Imtech.Pager = function() {
this.paragraphs = '';
this.showPage = function() {
console.log(this.paragraphs.html());
}
}
What i do:
pager[0] = new Imtech.pager();
pager[0].paragraphs = $('some obj name here');
pager[0].showPage();
pager[0].showPage();
So, i ve got arr of paginating classes;
When i call method pager[0].showPage(); - its all ok
But when i try to make it again pager[0].showPage() - i got empty result...
Even got no ideas where is mistake; and var clears not only after console.log(), but after any operation...
How I decided problem:
So I made a very very bad version, but for ie it works fine;
The problem was, that after first usage of stored DOM element, all innerHTML cleared, but objects still existed; I decided to store innerHTML like a text string; smth like:
pager[0].innerHTML = $('some obj name here').html();
And when i need this inneHTML like obj I can make obj, so it's not brilliant variant, but in ie (& other browsers) works fine.

Categories

Resources