Playing With HTML Elements: Issues That Might Arise While Listening to Form Elements and fetching data.
Published: 2023-01-10 03:04:45

## Solving refresh issues with submit events.


Preventing the refresh default action of a Submit event might sound straightforward but as I have found out it is not as intuitive as it might sound.


Let’s start with some basics. What is an event?

The Web Browser fires an event when something happens to the page. Be it when you click, submit, hoover, etc over something.

In Javascript,  The syntax of an event has three main components ;

Event target: The target is the HTML element to which we point the action of the event.

Event type: This is a string that defines what kind of event we are using. Be it “click”,”keydown”,” submit”, “focus”, etc.

Event handler: It is a function that responds to an event. This function is invoked by the browser. This gets triggered once we make contact with the event target.


Having this down, let’s start with the problems:




## You are not looking at the big picture type of issue.

Given the below form:

 

```
<div id ="container1"> 
    <form id = "inputs" ><input id = "search"type = text label = "name" >
        <input id = "sub" type = submit label = "submit ">
    </form>
   </div>
```




If my intention was to add a submit event to this form, the intuitive thing will be to grab the Submit button:

`let submitBtn = document.querySelector(“#sub”)`


So when I click on the submit button the Event will trigger and our handler will cancel out refreshing the page with preventDefault().

  

```
submitBtn.addEventListener(“submit”, event => 
     event.preventDefault())
```

**It will not work** this way.


**_What is the issue?_**

 The browser's default action of refreshing the page is targeting the form itself, not only the button. 

We need to target the whole form.

`let formulario = document.querySelector(“#inputs”)`

```
formulario.addEventListener(“submit”, event => 
  event.preventDefault())
```



Problem solved!





## Solving an issue with fetch and form data.

Now that we have the refresh of the form solved we might encounter some minor headaches while trying to use the text input of the form.

But first, let’s go back to basics.

_what is an API? _
It stands for Application Programming Interface. Basically, it is data from other people/companies that the public is given access to.

This data is usually packed in Json.


_what is JSON?_
It stands for JavaScript Object Notation.
JSON is a form of data format which is largely used on the web.
Ex of JSON format:

```
 `
    {{% embed  %}
        "name":"Penguin",
        "imageurl":"https://external-content.duckduckgo.com/iu/?u=http%3A%2F%2Fcdn.roaring.earth%2Fwp-content%2Fuploads%2F2016%2F03%2FMagellanic_penguin_Valdes_Peninsula-Photo-by-longhorndave.jpg&f=1&nofb=1&ipt=ce483fcdf5447fffef6460a3054096805e8546f89cd919fcb08f98bc4b6d18d2&ipo=images",
        "description":"are a group of aquatic flightless birds. They live almost exclusively in the Southern Hemisphere",
        "donations": "0"
    },
 
    {
        "name":"Bald eagle",
        "imageurl":"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Furbanraptorconservancy.org%2Fwp-content%2Fuploads%2F2019%2F03%2FBE3g.jpg&f=1&nofb=1&ipt=f966af2a73c049b28f680a28877b6271aeffe1f3447aebaeecf31c51333222e3&ipo=images",
        "description":" a bird of prey found in North America. ",
        "donations":"0"
 
    },
    {
        "name":"Red bird of paradise",
        "imageurl":"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fc2.staticflickr.com%2F8%2F7239%2F7188557664_1230086a7b_b.jpg&f=1&nofb=1&ipt=56253f9696e04f2990ed10501f36a090d38a456bc0f0af85938d85bb337ee5d1&ipo=images",
        "description":"up to 33 cm long, brown and yellow with a dark brown iris, grey legs and yellow bill.",
        "donations":"0"
 
    },
    {
        "name":"Snow Leopard",
        "imageurl":"https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fidsb.tmgrup.com.tr%2Fly%2Fuploads%2Fimages%2F2020%2F05%2F25%2Fthumbs%2F800x531%2F37398.jpg%3Fv%3D1590571602&f=1&nofb=1&ipt=96668444752a472d250a282bd208ce016ad1645ef96a8b275a47c3de95360c92&ipo=images",
        "description":"native to the mountain ranges of Central and South Asia. It is listed as Vulnerable on the IUCN Red List because the global population is estimated to number fewer than 10,000",
        "donations":"0"
 
    }
 
`
```

_What is a  fetch request?_

It’s a method to retrieve data from the net. We retrieve JSON data with this method.
 Example :  

```
function getData (){
            fetch(URL)
            .then(response => response.json())
            .then(data => {
                console.log( data ))

```



## You are looking at the elephant from afar type of issue.

Let us say we want to fetch some data with a user's input.

we can start by getting the form input text element.

 

```
<form id='forms'>
      <input id='searchit' type='text' name='search'>
      <input id="sub" type='submit' name='submit'/>
    </form>
```


`let texto = document.querySelector(“#searchit”)`

We could send it over to fetch with :
`getdata(texto)`

assuming: 

```
function getData (input){
            fetch('https://soemwhere.com/nothere/${input}')
            .then(response => response.json())
            .then(data => {
                console.log( data ))
```

as you see we do some interpolation to inject input text in the fetch request

` fetch('https://soemwhere.com/nothere/${input}')`

**This will not work** as intended.


 **_What's the issue?_**

we are targeting the text input alright but the thing is we are actually grabbing the element itself:

`<input id='searchit' type='text' name='search'>
`

What we really want is the value of whatever the user writes in the input type text

So instead of this :   
`getdata(texto)`

We will do something like this:


`getdata(texto.value)`.

 In this case, I want to focus on the elephant's writings instead of the whole elephant.

Problem solved!




These issues are not as difficult once you see them, but in my learning experience as a beginner, issues like this will trip you over and make you spend a lot of time in your code because you missed them.




_**RESOURCES:**_
Flanagan,D.(2020)._JavaScript The Definite Guide: Master the World's Most-Used Programming language.
https://developer.mozilla.org/en-US/.