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:
isn’t creating an element and appending data to it, it’s just concatenating the
rowvariable and a string literal (that contains jQuery code).Why not make
rowan actual row – rather than a string that contains the contents of a row – then append that in thesuccesscallback handler instead:Then: