0

I am a very early beginner who is trying to do something in JavaScript.

Basically I have an HTML form where I am collecting user input. I have a submit button. When on submit, I want my values from the input to be appended to a table as a new row.

I have spent hours trying to find a direction, can someone point me in the right direction?

Fenton
  • 241,084
  • 71
  • 387
  • 401
pinklotus
  • 101
  • 2
  • 13

6 Answers6

4

Since nobody else wants to (or can) provide a pure JS answer, here's how you can do it with pure JavaScript. If some things are unclear, let me know and I'll be happy to provide you with useful links and explain what this code does:

HTML:

<table id='targetTbl'>
    <tbody>
        <tr><th>Name</th><th>First name</th></tr>
    </tbody>
</table>
<form id='inForm'>
    <input type='text' name='name' id='name'/>
    <input type='text' name='first' id='first'/>
    <input type='submit' value='add row'/>
</form>​

JavaScript:

document.getElementById('inForm').onsubmit = function(e)
{
    var newRow,i;
    e = e || window.event;
    if (e.preventDefault)
    {
        e.preventDefault();
        e.stopPropagation();
    }
    e.returnValue = false;
    e.cancelBubble = true;
    newRow = '<tr>';
    for(i=0;i<this.elements.length;i++)
    {
        if (this.elements[i].tagName.toLowerCase() === 'input' && this.elements[i].type === 'text')
        {
            newRow += '<td>'+this.elements[i].value+'</td>';
        }
    }
    document.getElementById('targetTbl').innerHTML += newRow + '</tr>';
    return false;
};

In order for this to work, you need to either include this code at the bottom of your HTML file (not reccomended) to ensure the DOM has loaded before you're trying to change things, or you'll have to put this code inside an event handler:

window.onload = function()
{
    //above code goes here
};

Here's a working fiddle

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
  • Gracious in defeat ;), it shows strength of character, admitting too something like that, in return I'll undo the downvote I gave you. But for that, you need to edit it first, it says. After all: your answer isn't wrong (technically), and you did make an effort – Elias Van Ootegem Sep 06 '12 at 22:03
  • Thank you Elias. While I was waiting for answer, I got to know more about Jquery, and through a previous post figured out how to do it! But you guys are amazing for helping a beginner out like this. – pinklotus Sep 06 '12 at 23:56
  • Previous post: [link](http://stackoverflow.com/questions/171027/add-table-row-in-jquery) – pinklotus Sep 07 '12 at 00:14
  • @pinklotus: You're welcome. I must stress that learning pure JS is well important, too. jQuery is good, but it isn't perfect. JS is a very interesting language, and worth to learn. BTW: if an answer is helpful, you either vote it up or accept it. If you don't know how: read the FAQ of this site – Elias Van Ootegem Sep 07 '12 at 06:45
  • Ok Alias, even thought I used jQuery (see my answer), I am going to accept your answer because it helped me learn javascript more. – pinklotus Sep 07 '12 at 08:38
0

Few points to consider:

  • You do not want your submit button to work. That means you do not want it to take you to the action you specified in the form element. So you either add an onclick event which (<input type="submit" onclick="dosomething();return false;" />) returns false, or you make it of type "button" (<input type="button" onclick="dosomething();" />).

  • You need to define a function that should be called when the button is pressed:

Example:

function dosomething() {
    alert("I did something");
    // do something useful
}
  • You need to create a <table> tag, and add rows to it based on your data. You could use jQuery for that, and I would recommend that to get you starting quickly. DOM manipulation in javascript is a pain. You know what, forget jQuery. Check @Elias's answer for a better, cleaner, faster approach. And also, it teaches you much more. It might be a valuable asset when/if you do use a library, and it certainly will, if you can do without one.

Example (in jQuery):

var table = $("<table></table>");
for (var i=0; i<data.length; i++) {
    var tr = $("<tr></tr>");
    var td = $("<td></td>");
    $(td).text(data[i]);
    $(tr).append(td);
    $(table).append(tr);
}
$("body").append(table);

Community
  • 1
  • 1
jadkik94
  • 7,000
  • 2
  • 30
  • 39
  • Sorry, you've obviously taken the time to answer decently, bunt don't go all jQuery-crazy. There is no jQuery tag here, and the OP explicitly says he's new to JS. Let him get to grips with the basics, he'll find out what libs to use soon enough. Hence: this answer wasn't useful – Elias Van Ootegem Sep 06 '12 at 21:21
  • 1
    @Elias I've explicitly noted that I would have found it easier to use jQuery myself, than going through DOM manipulation in Javascript. I would have preferred NOT to go through DOM manipulation if I were a beginner. – jadkik94 Sep 06 '12 at 21:24
  • 1
    and btw @EliasVanOotegem I wonder if you still can do such a thing in pure JS :P because I honestly forgot, and don't want to remember... – jadkik94 Sep 06 '12 at 21:27
  • Maybe, but that's not your call, that's up to the OP to decide. Besides: tags are supposed to be indicative of the sort of answer you're looking for: no jQ-tag, no jQ answer. If you want to know how to _efficiently_ know what the dom is, you should know about nodes, and how JS works with them. jQ is a great tool once you're past all that, but not so good if you want to learn the language – Elias Van Ootegem Sep 06 '12 at 21:28
  • Of course you can: jQuery **IS** JavaScript, if you can do it with jQuery, you can do it with JavaScript. The only difference is that pure JS code will be faster – Elias Van Ootegem Sep 06 '12 at 21:29
  • @EliasVanOotegem I would argue a beginner does not even know about jQuery to tag it as such, but that is going out of topic. Let OP decide. (I meant *can* as capability, not possibility, but never mind). – jadkik94 Sep 06 '12 at 21:30
  • of course I still know how to do this, I've ditched jQuery about 4 months ago in favor of pure JavaScript, check out my answer and fiddle if you feel like a reminder of how it can be done. Not too much code to write, and no huuuge and slow lib required – Elias Van Ootegem Sep 06 '12 at 21:50
  • I am sorry I didnt add jQuery tag here. I didnt even know I can do this with jQuery or much about it. But after a few hours of playing around, I think I get it. Now I realize that I should have added the tag. – pinklotus Sep 06 '12 at 23:57
0

Ok Guys, After reading some more and asking a friend to explain, i was able to do this with jQuery. I am sorry I didnt add jQuery tag at the beginning, because I didn't know. But I was exposed to jQuery from the very first exercise in js. So I was able to grasp this eventually. So this is what I have and it works for me. If this is right, might be useful for a learner like me.

The ids of my input fields are "firstname" and "lastname". getElementById().value gets the value input by the user.

var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value; 
$("#myTable tr:last").after("<tr><td>" + firstname + "</td><td>" + lastname + "</td></tr>" );

And I am calling this function through button onclick(). Thank you for the support.

Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
pinklotus
  • 101
  • 2
  • 13
-1

You have two choices:

Classical: You submit the form. The server reads the form, and generates the HTML for a new copy of the form with the new row added and sends it back to the browser.

Ajax: You submit the form in the background using AJAX, then using JavaScript, you append a new row to the HTML client-side.

Which you choose depends on your comfort level with back-end vs. front-end coding.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
-1

You can use this function. You need to send as a parameter the id of the table and change valueInputForm with the variables in which you have the values of the inputs

function addRow(tableID) {      

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    cell1.innerHTML = valueInputForm;

    var cell2 = row.insertCell(1);
    cell2.innerHTML = valueInputForm;

    var cell3 = row.insertCell(2);
    cell2.innerHTML = valueInputForm;
}
Furqan Safdar
  • 16,260
  • 13
  • 59
  • 93
-2

Lets say you have this html HTML:

<form id="target">
  form-field1: <input type="text" id="form-field1" value="Hello there" />
  form-field2: <input type="text" id="form-field2" value="How are you" />
  <input type="submit" value="Go" />
</form>
<div id='targettable'><table><thead></thead><tbody></tbody></table></div>

You can use jquery:

$("#target :input").each(function(){
 var input = $(this); // This is the jquery object of the input, do what you will
  $("#targettable >tbody:last').append($(this).val());
})

Add jquery script to your code in <head> tag

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
Vikram
  • 4,162
  • 8
  • 43
  • 65
  • Come on people: **I am a very early beginner who is trying to do something in javascript.** + _NO jQuery Tag_! Stop giving jQuery answers, it's not helpful. Let the OP get to grips with pure JS before confusing him with libs – Elias Van Ootegem Sep 06 '12 at 21:16
  • @EliasVanOotegem the question asker did not specifically mention he/she did not want a jQuery solution...it maybe your personal opinion that jQuery is confusing. If given the right kind of information, I believe jQuery is very intuitive and less cumbersome. There is learning curve in both cases: pure Javascript as well as jQuery so why not learn the better one? for this reason I am flagging your comment as unconstructive – Vikram Sep 06 '12 at 22:05
  • Flag away... Saying jQuery is the better one is your opinion, and it is unfounded in IMO: it's like saying Zend is better than PHP... My point is: the OP didn't use the jQuery tag, and you're answering with jQuery. The tags were created to organize questions properly, not to be ignored. That, and the OP is learning JavaScript, what you're saying is: don't use the language, use the most commonly used lib. I find that bad advice, sorry – Elias Van Ootegem Sep 06 '12 at 22:13
  • I am not allowed to post answer till 8 hours cause I'm new here. But I did get the answer with jQuery. Maybe Elias is right in saying that I should get good at plain js before using a lib. But for now, I get what I doing. I used $("#myTable tr:last").after(value) – pinklotus Sep 07 '12 at 00:54