1

Whenever I click on a certain letter, I want the first slot value from the beginning to be changed to the letter value I clicked on. Is it correct that I put the letter.onclick = letterClick(this); into the for loop or should I realise it some other way. Also, what should the letterClick() function contain?

// Makes slots and letters for the chosen word.
function maker() {
    for (i=0; i<word.length; i++) {
        var slot = document.createElement("input");
        var letter = document.createElement("input");
        var letters=(shuffledWord).split("");
        slot.type = "submit";
        slot.value = "";
        slot.id = "slot" + i;
        slot.setAttribute('id', 'slot');
        letter.type = "submit";
        letter.value = letters[i];
        letter.id = "letter" + i;
        letter.onclick = letterClick(this);
        letter.setAttribute('id', 'letter');
        document.getElementById("slotbar").appendChild(slot);
        document.getElementById("letterbar").appendChild(letter);
    }
}
2
  • Creating more buttons will mean there's a greater supply with an equal demand, so the value of buttons will decrease. But if you have very few buttons then those buttons that are left will be worth a lot. If you have direct control over the supply of buttons then you can change the value that way. If not then maybe you can persuade people that buttons are awesome, thus driving up demand & price. Or try to convince them buttons suck and they shouldn't want any, thus lowering demand & price. Outside of this I'm not sure. Commented Oct 10, 2013 at 20:03
  • LOL, sounds like my economy class. Commented Oct 11, 2013 at 6:16

1 Answer 1

3

Not really, this refers to the context where you run the method maker. So mostly you get this as window, and you do not want to invoke the function when you bind the handler for onClick. It should be a function reference.

Try

 letter.onclick = letterClick.bind(this, letter); 

Now the function will be invoked with your first argument as that letter element.

When you do

letter.onclick = letterClick(this);

it immediately invokes the function and set its result as handler, i.e if it doen't return another function ref that is the real handler, it won't work.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! This actually works, as it gives me the letter value in the function letterClick(), but how should I replace the slot value with the value of the letter?
@danrodi Do you mean inside the function letterClick?
You can do elem.previousElementSibling.value = 'value of letter'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.