2

I'm trying to append a word in the word bank wordBank_Headings to the textbox #textBox.

My jQuery is working because I've tested the click function with other elements, such as $("#textBox").click(function (event) {, then log("testing : " + $(this).attr('word')); outputs "testing : undefined".

When a user clicks on a word, it will be sent to the textbox:

enter image description here

I checked HTML in Chrome. I see the words are being wrapped appropriately in the spans.

enter image description here

I'm not sure why clicking on the words won't work though.

Here is my code:

$(document).ready(function() {
    //initially append words to word bank   
    $.getJSON("php/Quests.php", { "_questNum" : questNum},
        function(wordsArray) {
            $.each(wordsArray, function(key, value) {   
                $(".wordBank_Words").append("<span class='bankword' word='" + key + "' ><b>" + key + "</b>: " + value + "</span><br/>");
            }
        );
    });

    /*If user clicks word in word bank, word is added to text box*/
    $(".bankword").click(function (event) {
        log("testing : " + $(this).attr('word'));
        $('#textBox').val($('#textBox').val() + " " + $(this).attr('word'));        
        //hide word from word bank
        $(this).hide();
    });


    /*If User removes word from text box, add it back to word bank*/
    $('#textBox').on('change', function(){
        var words = $(this).val().split(' ');
        $('.bankword').each(function(){
           if( words.indexOf( $(this).attr('word') ) !== -1 ){
               $(this).hide();
           }
           else {
               $(this).show();
           }
        });
    });
});
user3871
  • 12,432
  • 33
  • 128
  • 268

2 Answers2

3

I think you create a span element after document is created. So, you should try on for your click event. you can try as below:

$(document).on('click',".bankword",function (event) {
   log("testing : " + $(this).attr('word'));
   $('#textBox').val($('#textBox').val() + " " + $(this).attr('word'));        
   //hide word from word bank
   $(this).hide();
});
Arjun
  • 1,431
  • 1
  • 12
  • 32
1

You know what? Looks like You try to attach listeners to the spans before they're created. You just have to replace this line

$(".bankword").click(function (event) {

with this one

$(".wordBank_Words").on('click', ".bankword", function (event) {
Sergey Semenov
  • 369
  • 2
  • 7