Search code examples
jqueryhtmlenter

jQuery: content to show when enter key is pressed



I am trying to display some content when a button is clicked (which it works perfectly with my code), but I would also like it to be shown when an enter key is pressed as well.
The console is running well with an error of " getFigures could not be defined " and no content has been shown! I have tried a lot of different methods suggested, but still with no luck... It would be wonderful if anyone could address where have I put wrong please?

Here is my code below and you may find the full code in the link here:

HTML:

    <section id="fetch">
         <input type="text" placeholder="Please enter your name here" id="term" />
         <button type = "button" id="search">ENTER</button>
    </section>

    <section id="content">
        <div id = "figures">
            <script>
            </script>
        </div>

        <div id ="name">
            <div id = "nameBox">
            </div>
            <div id = "nameText">
            </div>
        </div>

        <div id = "message">        
            <div id = "messageBox">
            </div>
            <div id = "greetingText">
            </div>
            <div id = "messageText">
            </div>
        </div>
    </section>

jQuery:

$('#search').click(displayContent);     // the value of the #term is being called within the displayContent();

$('#term').keyup(function(event){
   if(event.keyCode == 13){
       displayContent();
       getFigures();
   }
});

$('#term').keypress(function(event){        // this function looks redundant...?
    if(event.which == 13){
    $('#search').click(displayContent);
        displayContent();
        getFigures();
    }
});

Thanks a lot :))) x

EDIT: The updated fiddle of what I want is here for anyone's reference :))) x


Solution

  • The function getFigures is defined in the scope of the function displayContent and does not exists outside this scope. You try to call getFigures in $('#term').keypress(function (event)) which is outside the displayContent scope and so getFigures does not exist.

    Put getFigures out of the displayContent function and it works.

    edit: You also need to add the type variable as an attribute to the getFigures function so you can pass it appropriately.

    See my new jsfiddle: https://jsfiddle.net/rokvowjv/12/

    Note: you delete the #figures div by emptying the #content div, I add the image in the content instead to display it, but I am not sure if that is what you want.
    You tried to add the image output to the figures div, but since you first delete the div it would not work.