javascript function won't run onchange - javascript

window.onload = init;
function init(){
var allSelect = document.getElementsByTagName("option");
for (var i = 0; i < allSelect.length; i++){
allSelect[i].onchange = loadLink;
}
}
function loadLink(){
alert("TEST");
}
So I'm working on this problem for a class and the functions are incredibly simple. I replaced the code needed with a simple alert because even tracking break point by point it doesn't run the loadLink() function. AllSelect is populated and are all have the onchange value with the specified code in the {}.
I have also tried putting it into the html element by hand and it still doesn't work.
Any Ideas? I'm running locally on my computer with both IE and Chrome if anyone cares to know. Thanks ahead of time.

The onchange event belongs on the select element, not the option elements. So:
window.onload = init;
function init(){
var allSelect = document.getElementsByTagName("select");
for (var i = 0; i < allSelect.length; i++){
allSelect[i].onchange = loadLink;
}
}
function loadLink(){
alert("TEST");
}

I think you want
var allSelect = document.getElementsByTagName("select");
You are instead querying the option elements within selects in the DOM.

Related

addEventListener firing automatically within loop - or only last element works

I have a loop, and I am creating a button within each iteration. I am attaching an event listener to each newly created button, and I need to pass unique parameters through. Please see the code below (in this case, just passing the index from the loop through the event listener)
for (i = 0; i <= worklog.worklogs.length; i++) {
if (worklog.total > 0) {
var theButton = document.createElement("button");
theButton.addEventListener("click", alertButton(i));
theButton.innerHTML = "Add";
mySpan.appendChild(theButton);
}
}
function alertButton(arg) {
return function () {
alert(arg);
};
}
Currently, the event listener fires on only the button implemented on the very last iteration. If I remove the "return function(){}" within my alertButton function, then the event listener is fired on each iteration without the user clicking on the button.
If you have any ideas I would be extremely appreciative. I am finding other people who have had this problem, yet the solutions provided don't seem to work so well for me. Hopefully I am overlooking something simple.
Thanks!
Issue is in the way you are assigning listener:
theButton.addEventListener("click", alertButton(i));
in above code, alertButton(i) will call function and not assign to it. If you want to pass a value to a function assignment, you should bind value.
theButton.addEventListener("click", alertButton.bind(this,i));
As pointed by #Andreas, a working example.
function createButtons() {
for (var i = 0; i < 5; i++) {
var theButton = document.createElement("button");
theButton.addEventListener("click", alertButton.bind(this, i));
theButton.innerHTML = "Add";
content.appendChild(theButton);
}
}
function alertButton(arg) {
console.log(arg)
}
createButtons();
<div id="content"></div>

onclick() automatic firing on loading but failing afterwards

I understand that onclick() in html with parenthesis calls automatically. But in my situation, I want to pass a parameter into the onclick function(specifically, the element clicked). So how do I manage this without having onclick fired when the page loads? In addition, the onclick method does not fire after its automatically firing upon loading. My code is below:
for (i = 0; i < returnPostPhotoSrcs().length; i++) {
// var photosArray=returnPhotoNames()
// var imgName=photosArray[i]
var imgSrcArray=returnPostPhotoSrcs();
var imgSrc=imgSrcArray[i]
var postNamesArray=returnPostNamesArray();
var postName=returnPostNamesArray[i]
var img=img_create(imgSrc,postName,'')
img.style.width=returnPostHeight();
img.style.height=returnPostWidth();
img.className="postImage";
img.onmousedown=playShout(img);
var postNamesArray=returnPostNames();
var innerSpan = document.createElement('span');
innerSpan.onmousedown=playShout(innerSpan); //problem line
var text = postNamesArray[i];
innerSpan.innerHTML = text; // clear existing, dont actually know what this does
var outerSpan = document.createElement('span');
outerSpan.className="text-content";
outerSpan.onmousedown=playShout(outerSpan); //another problem line, also doesnt call onclick
var li = document.createElement('li');
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(img)
outerSpan.appendChild(innerSpan)
li.appendChild(imgSpacer)
imgSpacer.style.opacity="0"
// if (i>0 && i<returnPostPhotoSrcs().length-1) {
// hackey
var imgSpacer=img_create('spacerSource',"spacer",'')
imgSpacer.style.width="25px";
imgSpacer.style.height=returnPostWidth();
li.appendChild(imgSpacer)
li.appendChild(outerSpan)
imgSpacer.style.opacity="0"
// }
var outerDiv = document.getElementById("postDivOuter");
outerDiv.appendChild(li)
}
Adding onto this you could also do:
img.onmousedown= function(e) { playShout(e) };
//for playshout
playshout = function(e) {
var element = e.target; //this contains the element that was clicked
};
The function fires because you are calling it. You need to use a closure
img.onmousedown= function() { playShout(img) };
As others have shown, you can create an anonymous function, or another option is to use .bind():
innerSpan.onmousedown = playShout.bind(null, innerSpan);

Modify the target of a .appendChild() and it causes the program to reinitialize

I am having a problem wherein I changed this line:
document.body.appendChild(node);
to this line:
document.getElementById("character").appendChild(node);
and now when I click the update button that was just working perfectly, it now reinitializes the page. this is the function that the button calls:
updateList: function(){
this.updateStats();
this.derivedStats();
document.getElementById("moveList").innerHTML = "";
var strName;
var node = document.getElementById("selectR");
var c = node.childNodes;
for(var i=0; i<c.length; i++) {
for(strName in this.list) {
if(this.list[strName].name==c[i].value) {
//var helper = this.list[strName].display();
//document.getElementById("moveList").appendChild(helper);
}
}
}
},
No magic here, input of type "button" causes form submission, page reloads.

addEventListener isn't working properly

I want to move some elements between two div's. Everything works normal with onclick event, but when i swicth to addEventListener it lets me switch just a few times the elements.
Here is a previev http://jsfiddle.net/2u6nyxp4/1/ .
Can someone explain why is that ? Thank you.
HTML
<div id="one">
<span>One</span>
<span>Two</span>
</div>
<div id="two"><span>One</span></div>
JAVASCRIPT
var one = document.getElementById('one');
var two = document.getElementById('two');
var movetoOne = function () {
one.appendChild(this);
bindEvents (this,movetoTwo);
}
var movetoTwo = function () {
two.appendChild(this);
bindEvents (this,movetoOne);
}
var bindEvents = function (childList, moveEvent) {
childList.onclick = moveEvent;
}
for (i=0; i < one.children.length ; i+=1 ) {
bindEvents(one.children[i], movetoTwo);
}
for (i=0; i < two.children.length ; i+=1 ) {
bindEvents(two.children[i], movetoOne);
}
If you use oncklick there is only one event-handler for the event at a time. Each time you call bindEvents the old one becomes overwritten by the new one.
If you use addEventListener, each time you call bindEvents a new handler is added to the existing. After ten clicks there are five handlers movetoOne and five movetoTwo attached to the same element and the browser is totally confused.
The way out: remove the existing handler before adding a new one like so:
var bindEvents = function (childList, moveEvent) {
var old = movetoOne;
if (old === moveEvent) old = movetoTwo;
childList.removeEventListener('click', old);
childList.addEventListener('click', moveEvent);
}
Working DEMO here. - - - Reference: removeEventListener().

Use Javascript string as selector in jQuery?

I have in Javascript:
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
}
How can I continue in jQuery like:
$(function() {
$(vst).'click': function() {
....
}
}
NO, like this instead
$(function() {
$(vst).click(function() {
....
});
});
There are other ways depending on your version of jquery library
regarding to this, your vst must need to be an object which allow you to click on it, and you assign a class or id to the object in order to trigger the function and runs the for...loop
correct me if I am wrong, cause this is what I get from your question.
$(function() {
$(vst).click(function() {
....
}
})
You can use any string as element selector param for jQuery.
Read the docs for more information.
http://api.jquery.com/click/
http://api.jquery.com/
You can pass a String in a variable to the $() just the way you want to do it.
For example you can do:
var id = 'banner';
var sel = '#'+id;
$(sel).doSomething(); //will select '#banner'
What's wrong is the syntax you are using when binding the click handler. This would usually work like:
$(sel).click(function(){
//here goes what you want to do in the handler
});
See the docs for .click()
Your syntax is wrong, but other than that you will have no problem with that. To specify a click:
$(function() {
for ( i=0; i < parseInt(ids); i++){
var vst = '#'+String(img_arr[i]);
var dst = '#'+String(div_arr[i]);
$(vst).click(function (evt) {
...
});
}
})
Note that since vst is changing in the loop, your event code should also be placed in the loop.
EDIT: Assuming you want the same thing to happen for each image and each div, you could also do something like this:
$(function () {
function imgEventSpec($evt) {
// image clicked.
}
function divEventSpec($evt) {
// div clicked.
}
for (var idx = 0; idx < img_arr.length && idx < div_arr.length; idx ++) {
$("#" + img_arr[idx]).click(imgEventSpec);
$("#" + div_arr[idx]).click(divEventSpec);
}
});

Categories

Resources