Wikipedia Viewer- Question about forms

Hi, all!

I’m working on my Wikipedia viewer and I think it’s working pretty well… but I have a question about forms. I have an input and a button to call the javascript function getArticles that I defined. It works great, but when I enclose the input and button in a form element, it doesn’t call the function anymore. Any idea why that is?

Any other input on how I can improve my code is also welcome. Thanks!

1 Like

Hey I looked through your JS, and gave some edits that may help if you’d like to use a form.

 $("#submit").on('click', function(e){
    e.preventDefault();
    var txt = $("#search").val();
    getArticles(txt);
  });
  
  $("#search").keyup(function(event){
    
    if(event.keyCode == 13){
      var txt = $("#search").val();
      getArticles(txt);
    }
  });

You could replace the code at the top of your JS with that. I believe it had to do with the variable txt being inside the function, and also not being able to prevent the page from reloading when clicking or submitting with enter. You could also write a function to get the query value instead of the ugly way I wrote it here :stuck_out_tongue:

Hope this helps!

1 Like

Thank you- that worked. It just seemed like better HTML to use a form element, though I’m not sure if it is necessary or not.

What is the line “e.preventDefault();” doing? I’m not familiar with that code.

Here’s what it does.

In this case, its preventing the form from submitting the form and reloading a new page with the search query in the URL.

1 Like