Creating buttons in JavaScript that will submit form input value
How I figured it out.
The project was to fetch images from an API and create a card for each of those images. The card has a ‘like’ button and a form to submit a comment. Every element in the card is created using JavaScript.
Fetching the data from the API, creating the ‘like’ button, form, and ‘submit’ button were straightforward and I was able to render those elements to the DOM. I created my event handlers so every time the ‘like’ button was clicked, the number of likes increased. When ‘enter’ was pressed on the keyboard, the text in the input box was added to the list below.
Then came the submit button. I could not figure out why it would not work. Using HTML format for guidance when writing my JavaScript code, everything seemed correct. Here’s the form with a button I created in my HTML file.
And here is the form with the button I created in my JavaScript file (as seen in the console).
I noticed that even though I added an input.value = ‘ ’ to my input element and submitButton.type = ‘submit’ to my button element in my JavaScript code, neither of those showed up in the console. I’m not quite sure why that is, but it got me thinking that maybe the way the HTML handles the button is different than the way JavaScript handles the button. For whatever reason, the way I created the button and appended it to the form in JavaScript made it so the button didn’t inherit the submit property the way it does in HTML. There very well could be an error in my code and changing the syntax might fix that issue, but I found another solution.
Rather than thinking that my submit button would inherit the event listener I added to my form event listener, instead I separated the two events and put a separate ‘click’ event listener on my submit button.
I got stumped again. How do I get the value of the form input out of the form so I could use it in my submit button event listener to be added to the list below?
I knew both the submit form and submit button would use the same text input value, so I made a function in the global scope that would take a form and an input as parameters and create the list item based on the value of the input.
Then all I needed to do was add event listeners to my form and submit button, pass in the function, and it worked! Now I have a functional submit form and submit button.
Phew! If anyone has other solutions, let me know!