I needed to get the values of each dynamically created rows and print those values. What the current code does is that it can alert the all the added values or print to console. Now, how can I print those values?
For instance user has added one more row and selected the following:
After the user clicks Get Values, all the values (Female, Lady, Male and Schertz) must be printed to a generated table and page should look like this:
Now what I have are the following code.
HTML view:
<button>Add More Order</button>
<button>Delete Added Order</button>
<div id="wrap" class="order-container">
<p>
<select class="getThis">
<option>--Gender--</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<input type="text" class="getThis" placeholder="Name"/>
<br>
</p>
</div>
<input type="submit" id="getValues" value="Get Values"></input>
jQuery:
$(document).ready(function(){
//Add new row
$("button:nth-of-type(1)").click(function(){
$("#wrap").append("<p><select class='getThis'><option>--Gender--</option><option>Male</option><option>Female</option></select><input type='text' class='getThis' placeholder='Name'/><br></p>").trigger('create');
});
//Remove last added row
$("button:nth-of-type(2)").click(function(){
$("p:last-of-type").remove();
});
//alert values
$("#getValues").click(function() {
$(".getThis").each(function() {
var getThis = $(this).val();
//console.log(getThis);
alert(getThis);
});
});
}); // Document Ready End
Here's a JSfiddle for a demo.
Any ideas? Kamsahamnida!
You could use e.g:
$("#getValues").click(function () {
var $table = $('#resultTable').length ? $('#resultTable').find('tr:gt(0)').remove().end() : $('<table/>').append('<tr><th>Gender</th><th>Name</th>').appendTo('body').attr('id', 'resultTable');
var getValues = $("p:has(select.getThis)").find('select.getThis').map(function () {
return {
gender: this.value,
name: $(this).next().val()
}
}).get();
$.each(getValues, function (_, fields) {
$table.append($('<tr/>', {
html: '<td>' + fields.gender + '</td><td>' + fields.name + '</td>'
}))
});
});
try this:
$("#getValues").click(function() {
$("select.getThis").each(function() {
var getThis = $(this).val();
$(this).next().val(getThis);
});});
try
document.getElementById('getValues').value;
Change your inputs class to something else as it might start confilcting and then try this:
$("#getValues").click(function() {
$(".getThis").each(function() {
var getThis = $(this).val();
$(this).closest("p").find("input[type='text']").val(getThis);
});
});
What it does is it goes from the current target to the closest parent paragraph tag and from there it finds the input[type='text'] and gives it the value