Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Jeremy Barbe
Jeremy Barbe
8,728 Points

How do I get this function to work?!?!?!

I'm trying to build my first application. I'm on my first day, and all my studying without practice is proving to be a gigantic waste of time. I'm simply trying to use a JS function to add a row of data to an HTML table upon the click of a submit button. When I click the button, the data I desire to go into the table shows up only during the split second that I'm actually clicking on the button.

This is the HTML:

<form id=activityInput>
                  Activity<br>
                  <input type="text" name="activity">
                  <br>
                  <input type="radio" name="activityType" value="Recreation">Recreation
                  <br>
                  <input type="radio" name="activityType" value="Work">Work
                   <br>
                  <input type="radio" name="activityType" value="Fitness">Fitness
                   <br>
                   <input type="radio" name="activityType" value="Self-Improvement">Self-Improvement
                   <br>
                  <input type="submit" onclick='getTableData()' value="Add">
                </form>


                <div id="list">
                <table id="activityTable"></table>
                </div>

And this is the JS function:

function getTableData() {
$('#activityTable').append("<tr> <td>activity</td> <td>activityType</td> </tr>");
}

I'm not trying to get the function to actually submit the user input to the table at this point (as you can see). I just want the button to actually have the capacity to input a table row upon it being clicked. Please help!!!

P.S. I feel so, so stupid.

3 Answers

my guess is because your button is a submit inside a form, after the javascript runs the page is reloaded and the table is empty again, use the browser inspect tool to se if the page is reloaded. and try to change to a normal button, not a submit, or you can try to return false from the getTableData, it might prevent the page reload

Jeremy Barbe
Jeremy Barbe
8,728 Points

Yes, that was the answer, thank you. I was supposed to get an email upon a response but never got one. Thank you!

no problem, glad I could help