What I'd like to do is this : when the user clicks on send, I want the data to be displayed in a <tr/>
(with each field nested in its own <td/>
).
I already wrote a script that actually does this, but the system is not dynamic yet.
HTML :
<form name="contact" method="post" action="">
<p>
<label for="name">Name</label>
<input type="text" name="name" id="name" />
</p>
<p>
<label for="age">Age</label>
<input type="text" name="age" id="age" />
</p>
<p>
<label for="mail">Mail</label>
<input type="text" name="mail" id="mail" />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" />
</p>
</form>
<table id="results"></table>
JS :
$(function() {
$("#submit").click(function() {
var name = $("input#name").val();
var age = $("input#age").val();
var mail = $("input#mail").val();
var dataString = [name, age, mail];
var n = dataString.length;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$('#results').append(
$('<tr>')
.append($('<td>').append(dataString[0]))
.append($('<td>').append(dataString[1]))
.append($('<td>').append(dataString[2]))
);
}
});
return false;
});
})
As you can see, I grab the fields manually with dataString[x]
, but how can I make this system dynamic?
I was thinking of using a loop like the following but I can't seem to make it work :
for(var i = 0; i < n; i++){
row += "$('<td>').append("+dataString[i]+")";
}
$('#results').append(
$('<tr>')
.append(row)
);
Any hint on how to do this? Or would you have a cleaner solution?
This line of code:
row += "$('<td>').append("+dataString[i]+")";
isn't creating an element and appending data to it, it's just concatenating the row
variable and a string literal (that contains jQuery code).
Why not make row
an actual row - rather than a string that contains the contents of a row - then append that in the success
callback handler instead:
var row = $('<tr>');
for(var i = 0; i < n; i++) {
row.append($('<td>').html(dataString[i]));
}
Then:
$('#results').append(row);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With