Button for Update Table jquery - javascript

I am trying to make an update button for my Table Rows.
My Add button Open the Form Input Fields, My Hide button Hide it, The Edit Button edits the Table TR Fields.
The Submit Button Creates a new TR with the new text that I put in the Fields.
I want also an Update Button aside the Submit one. When I edit a TR Raw and put something else in them. When I press update to change that TR Text.
Help me to fix this.
Here is my current HTML/Jquery.js Script
<!DOCTYPE html>
<html >
<head >
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<title ></title >
</head >
<body >
<form class="a" action="" method="post" hidden>
<input type="text" name="nume" id="btd1" value="" >
<input type="text" name="prenume" id="btd2" value="" >
<input type="text" name="email" id="btd3" value="" >
<input type="text" name="telefon" id="btd4" value="" >
<input type="text" name="parola" id="btd5" value="" >
<input type="button" id="submit" value="Submit" name="submit" />
</form >
<table border="2" >
<tr >
<td >Vlad</td >
<td >Andrei</td >
<td >vTask</td >
<td >Ceva</td >
<td >Alceva</td >
<td class="buttons">
<button class="add" >Add</button >
<button class="hide" >Hide</button >
<button class="edit" >Edit</button >
</td >
</tr >
</table >
</body >
</html >
$(document).ready(function () {
$('#submit').on('click', function () {
var valid = true,
message = '';
$('form input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table').append('' +
'<tr>' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons" style="vertical-align: top"><button class="add" >Add</button><button class="hide" >Hide</button><button class="edit">Edit</button></td >'+
'</tr>' +
'');
for(var x = 1; x < $('input').length; x++) {
$('#btd' + x ).val('');
}
}
});
$("body").on('click','.hide',function () {
$("form").hide();
});
$("body").on('click','.add',function () {
$("form").show();
});
$("body").on('click','.edit',function () {
$("form").show();
$.each($(this).closest('tr').find('td:not(".buttons")'), function (key, val) {
$("form input[type=text]").eq(key).val($(val).text());
})
});
$("#show").click(function () {
//$("form").show();
//$("#btd1").val("Vlad");
//$("#btd2").val("Andrei");
//$("#btd3").val("vTask");
// $("#btd4").val("Ceva");
//$("#btd5").val("Alceva");
});
});

Check this code
Why dont you add other field for save and edit
<!DOCTYPE html>
<html >
<head >
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<title ></title >
</head >
<body >
<form class="a" action="" method="post" hidden>
<input type="text" name="nume" id="btd1" value="" >
<input type="text" name="prenume" id="btd2" value="" >
<input type="text" name="email" id="btd3" value="" >
<input type="text" name="telefon" id="btd4" value="" >
<input type="text" name="parola" id="btd5" value="" >
<input type="button" id="submit" value="Submit" name="submit" />
<input type="button" id="save" value="Save" style="display:none;" name="save" />
</form >
<table border="2" >
<tr>
<td >Vlad</td >
<td >Andrei</td >
<td >vTask</td >
<td >Ceva</td >
<td >Alceva</td >
<td class="buttons">
<button class="add">Add</button >
<button class="hide">Hide</button >
</td >
</tr >
</table >
</body >
</html >
Javascript Code
$(document).ready(function(){
$(".add").on("click",function(){
$(".a").show();
});
$(".hide").on("click",function(){
$(".a").hide();
});
$(document).on("click",".editEle",function(){
row = $(this).parents("tr")
var field1 = row.find("td:nth-child(1)").html();
var field2 = row.find("td:nth-child(2)").html();
var field3 = row.find("td:nth-child(3)").html();
var field4 = row.find("td:nth-child(4)").html();
var field5 = row.find("td:nth-child(5)").html();
update(field1,field2,field3,field4,field5);
});
var update = function(field1,field2,field3,field4,field5){
$("#btd1").val(field1);
$("#btd2").val(field2);
$("#btd3").val(field3);
$("#btd4").val(field4);
$("#btd5").val(field5);
$("#submit").hide();
$("#save").show();
};
$("#save").on("click",function(){
var val1 = $("#btd1").val();
var val2 = $("#btd2").val();
var val3 = $("#btd3").val();
var val4 = $("#btd4").val();
var val5 = $("#btd5").val();
row.find("td:nth-child(1)").html(val1);
row.find("td:nth-child(2)").html(val2);
row.find("td:nth-child(3)").html(val3);
row.find("td:nth-child(4)").html(val4);
row.find("td:nth-child(5)").html(val5);
});
$("#submit").on("click",function(){
var val1 = $("#btd1").val();
var val2 = $("#btd2").val();
var val3 = $("#btd3").val();
var val4 = $("#btd4").val();
var val5 = $("#btd5").val();
var ele = "<tr><td>"+val1+"</td><td>"+val2+"</td><td>"+val3+"</td><td>"+val4+"</td><td>"+val5+"</td><td><button class='editEle'>Edit</button></tr>";
$("table").append(ele);
});
});

Related

Generate Serial Number on adding new line and adjust serial no when any line removed

I am cloning four field (sl no,stationery type ,quantity, Remove ) of a form by using java script.I can very well append or remove these field
I am not able to generate the serial no on the first column and if I delete any row in between this should also adjust the serial no.How can i achieve this My code is below
$(document).ready(function() {
$(document).on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
$(document).on('keypress', '.number_only', function(e) {
return isNumbers(e, this);
});
function isNumbers(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (
(charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode < 48 || charCode > 57))
return false;
return true;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<br />
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;>
<div class=" row ">
<div class="col-md-4 ">
</div>
<div class="col-sm-12 ">
<h4 align="center "><b><u>Add Stationery Stock<b></u></h4>
<br />
<form method="post " id="insert_form ">
<div class="col-sm-6 ">
<input type="text " name="Order No. " class="form-control " placeholder="Order NO "/>
</div>
<div class="col-sm-6 ">
<input type="date " name="Date " class="form-control " placeholder="Date " />
</div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center "><b><u>Stationery Details<b></u></h4>
<div> </div>
<div class="table-repsonsive ">
<span id="error "></span>
<table class="table table-bordered " id="item_table ">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button " name="add " class="btn btn-success btn-sm add "><span class="glyphicon glyphicon-plus "></span></button></th>
</tr>
</table>
<div align="center ">
<input type="submit " name="submit " class="btn btn-info "style="margin-bottom:20px " value="Insert " />
</div>
</div>
</form>
</div>
</div>
</div>
</body>
</html>
Using
html += '<td><input type="text" name="item_name[]" class="form-control item_name"></td>';
you can do
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
when needed
I fixed your invalid HTML (u and b not correctly closed and a missing quote on the first inline style)
I ALSO remove the name="submit" - you never want to have name="submit" on a form you plan to submit using script
const renum = () => {
let cnt = 0;
$(".item_name").each(function() {
this.value = ++cnt;
})
};
$(function() {
$("#item_table").on('click', '.add', function() {
var html = '';
html += '<tr>';
html += '<td><input type="text" name="item_name[]" class="form-control item_name" ></td>';
html += '<td><select name="item_unit[]" class="form-control item_unit" id="datalist"><option value="">Select Stationery Type</option><option value="A4 Green Ream">A4 Green Ream</option><option value="A4 Green Ream">A4 Green Ream</option><option value="Cellotape(Brown)">Cellotape(Brown)</option><option value="Cellotape(Transparent)">Cellotape(Transparent)</option><option value="Gluestick">Gluestick</option><option value="Highlighter">Highlighter</option><option value="Marker(Thick)">Marker(Thick)</option><option value="Marker(Thin)">Marker(Thin)</option><option value="Meeting Pen">Meeting Pen</option><option value="Normal Envelope">Normal Envelope</option></select></td>';
html += '<td><input type="text" name="item_quantity[]" class="form-control number_only item_quantity" /></td>';
html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
renum()
});
$(document).on('click', '.remove', function() {
$(this).closest('tr').remove();
renum()
});
$('#insert_form').on('submit', function(event) {
event.preventDefault();
var error = '';
$('.item_name').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Name at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_quantity').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Enter Item Quantity at " + count + " Row</p>";
return false;
}
count = count + 1;
});
$('.item_unit').each(function() {
var count = 1;
if ($(this).val() == '') {
error += "<p>Select Unit at " + count + " Row</p>";
return false;
}
count = count + 1;
});
var form_data = $(this).serialize();
if (error == '') {
$.ajax({
url: "insert.php",
method: "POST",
data: form_data,
success: function(data) {
if (data == 'ok') {
$('#item_table').find("tr:gt(0)").remove();
$('#error').html('<div class="alert alert-success">Item Details Saved</div>');
}
}
});
} else {
$('#error').html('<div class="alert alert-danger">' + error + '</div>');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
<div class="container" style="border: 2px solid #B22222;border-radius: 10px;margin-top: 25px;margin-bottom: 15px;">
<div class="row">
<div class="col-md-4"></div>
<div class="col-sm-12">
<h4 align="center"><b><u>Add Stationery Stock</u></b></h4>
<form method="post" id="insert_form">
<div class="col-sm-6"><input type="text" name="Order No." class="form-control" placeholder="Order NO " /></div>
<div class="col-sm-6"><input type="date" name="Date" class="form-control" placeholder="Date" /></div>
<div> </div>
<div> </div>
<div> </div>
<h4 align="center"><b><u>Stationery Details</u></b></h4>
<div> </div>
<div class="table-repsonsive"><span id="error"></span>
<table class="table table-bordered" id="item_table">
<tr>
<th>Sl.No.</th>
<th>Select Stationery Type</th>
<th>Enter Quantity</th>
<th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
</tr>
</table>
<div align="center"><input type="submit" class="btn btn-info" style="margin-bottom:20px" value="Insert" /></div>
</div>
</form>
</div>
</div>
</div>

dynamically add input field value jQuery

html code we can get the value
<input type="text" name="value1[]" id="value1"/>
<input type="mail" name="value2[]" id="value2"/>
<input type="text" name="total[]" id="total" />
i can try with this in jQuery i can get only html value result, after add new row i can't get the value
$(document).ready(function () {
var counter = 0;
$("#addrow").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item1</td>';
cols += '<td><input type="text" class="form-control" name="value1[]" id="value2' + counter + '"></td>';
cols += '<td><input type="text" class="form-control" name="foreign_milion[]" id="foreign_milion_' + counter + '"></td>';
cols += '<td><input type="text" readonly class="form-control" name="total_milion[]" id="total_"' + counter + '"></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
$("#value2").keyup(function () {
var value1 = $("#value1").val();
var value2 = $("#value2").val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
$("#total").val(totalincome);
})
});
First of all the id must be unique in the same document, else you'll end up with incorrect HTML code, so you need to replace the ids with common classes instead in your code as a first step.
Then you need to use event delegation to attach the event to your inputs since the must of them are created dynamically with the JS code.
I prefer the use of input event instead of keyup when you track the user inputs, so the event will be something like:
$(document).ready(function() {
var counter = 1;
$("body").on("input", ".calculated_value", function() {
var parent_row = $(this).closest('tr');
var totalincome = 0;
parent_row.find('.calculated_value').each(function() {
totalincome += parseInt($(this).val() || 0);
});
parent_row.find(".total").val(totalincome);
});
$("#addrow").on("click", function() {
var newRow = $("<tr>");
var cols = "";
cols += '<td>Item ' + counter + '</td>';
cols += '<td><input type="text" class="form-control calculated_value" name="value1[]"></td>';
cols += '<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>';
cols += '<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
counter++;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="order-list">
<tr>
<td>Item </td>
<td><input type="text" class="form-control calculated_value" name="value1[]"></td>
<td><input type="text" class="form-control calculated_value" name="foreign_milion[]"></td>
<td><input type="text" class="form-control total" name="total_milion[]" readonly></td>
</tr>
</table>
<button id="addrow">Add row</button>
I have tried this one, may be this is what you are looking into.
please take a look at the snippet.
jQuery(document).ready(function () {
var count = 1;
jQuery('#add').on('click', function(){
var el = `<section id="inpFields">
<input type="text" name="value1[]" id="value`+count+`" placeholder="value `+count+`"/>
<input type="text" name="value2[]" id="value2`+count+`" placeholder="value `+count+`"/>
<input type="text" name="total[]" id="total`+count+`" placeholder="total" />
<button class="totalBtn" data-id="`+count+`">Total</button>
</section>`;
jQuery('#inpFields').append(el);
count++;
});
jQuery('#add').click();
jQuery(document).on('click', '.totalBtn', function(){
var i = this.dataset.id;
var value1 = jQuery('#value'+i).val();
var value2 = jQuery('#value2'+i).val();
var totalincome = parseInt(value1) + parseInt(value2);
//alert(totalincome);
jQuery('#total'+i).val(totalincome);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="add">Add Fields</button>
<section id="inpFields">
</section>

How to add/delete 2 or more fields in a form dynamically

I would want to have two or more fields in a form to be dynamically added and deleted as per requirement. Say for, a person can have more than 1 phone numbers and more than 1 email address. The idea is to let the user add more than one phone number and email address if they have
This down below is what I did (only a rough example)
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container2");
var add_button = $(".add_form_field_1");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="text[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
//I repeated the javascript for the first field which was this
$(document).ready(function() {
var max_fields = 10;
var wrapper = $(".container1");
var add_button = $(".add_form_field");
var x = 0;
$(add_button).click(function(e){
e.preventDefault();
if(x < max_fields){
x++;
$(wrapper).append('<div><input type="text" name="mytext[' + x + ']"/>Delete</div>'); //add input box
}
else
{
alert('You Reached the limits')
}
});
$(wrapper).on("click",".delete", function(e){
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container1">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[]">
</div>
</div>
<div class="container2">
<button class="add_form_field_1">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[]">
</div>
</div>
And the JsFiddle.
I am not a javascript coder hence do not know if this is how you do it or is there a better way.
P.S. I asked the same question an hour ago and had to rephrase it as it was causing confusion.
You can simplyfy so much your code, check this:
$(document).ready(function() {
$("button.add_form_field").click(function(e) {
e.preventDefault();
var name = $(this).closest(".container").find("input:first").attr("class")
var numInputs = $(this).closest(".container").find("input").size()
if (numInputs < 10) {
numInputs++;
if (name=="mytext"){
$(this).closest(".container").append('<div><input type="text" name="mytext[' + numInputs + ']"/>Delete</div>');
}
if (name=="text"){
$(this).closest(".container").append('<div><input type="text" name="text[' + numInputs + ']"/>Delete</div>');
}
} else alert('You Reached the limits')
});
$(document).on("click", ".delete", function(e) {
e.preventDefault();
$(this).parent('div').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="mytext[1]" class="mytext">
</div>
</div>
<div class="container">
<button class="add_form_field">Add New Field <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div>
<input type="text" name="text[1]" class="text">
</div>
</div>
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".input_fields_wrap"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div><input type="text" name="mytext[]"/>Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>
Here is a working example, Hope this will helps you.
This may help you Mecom
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function removeUserDetail(index)
{
var rows=jQuery("#user_info tr").length;
jQuery("#user_info tr:nth-child("+(index+1)+")").remove();
if(index==(rows-1))
{
jQuery("#user_info tr:nth-child("+(index)+")").children().eq(4).append('<a class="mc_plus_button" id="plus_1" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a>');
}
jQuery("#user_info tr").each(function(i,e){
if(i>1)
{
jQuery(this).children().eq(4).children().eq(0).attr("onclick","removeUserDetail("+i+");");
}
});
}
function addUserDetail() {
var row_count1 = jQuery("#user_info tr").length;
var row_count = 0;
jQuery(".tr_clone").each(function(index, value) {
var rowid = jQuery(this).data('rowid');
if (rowid > row_count) {
row_count = rowid;
}
});
row_count = row_count + 1;
jQuery("#user_info tr").eq(row_count1 - 1).find(".mc_plus_button").remove();
var html = '<tr class="tr_clone" data-rowid="' + row_count + '"><td>' + row_count + '</td>';
html += '<td style="text-align: center"><input type="text" name="user_info[name][]" id="name_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[email][]" id="email_'+row_count+'" aria-invalid="false" /></td>';
html += '<td style="text-align: center"><input type="text" name="user_info[contact][]" id="contact_'+row_count+'" aria-invalid="false" /></td>';
html += '<td><a class="mc_minus_button" id="minus_' + row_count + '" href="javascript:void();" onclick="removeUserDetail(' + row_count + ');" title="remove"><strong>–</strong></a><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td></tr>';
jQuery("#user_info").append(html);
}
</script>
<table id="user_info">
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Contact</th>
</tr>
<tr class="tr_clone" data-rowid="1">
<td align="center">1</td>
<td style="text-align: center">
<input type="text" name="user_info[name][]" id="name_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[email][]" id="email_1" aria-invalid="false" />
</td>
<td style="text-align: center">
<input type="text" name="user_info[contact][]" id="contact_1" aria-invalid="false" />
</td>
<td><a class="mc_plus_button" href="javascript:void();" onclick="addUserDetail();" title="add"><strong>+</strong></a></td>
</tr>
</table>

How to Create a Loop Jquery

I have this HTML + this JQuery.JS
The Script works like this. When you Press the Add Button a Form will appear over the Table, when you press the hide button it will hide it When you press the Edit button any text that you will add in the form input cases will be added to a new TR that will be created with the Submit button.
What I want to do now is. On each TD line, I want my ADD/HIDE/Edit buttons to reappear but this time when I push Edit. I want to edit the new text that is in the new TR.
For Example, I have in first TR a, a, a, a, a I press Edit I put b, b, b, b, b, Submit it a new TR will be created with the bbbbb and when I push the Edit button again that is on the bbbbb tr. I want it to edit the bbbbb Line. I don't know how to explain it better than this. I can reach via skype if you guys want idk.
$(document).ready(function () {
$('#submit').on('click', function () {
var valid = true,
message = '';
$('form input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table').append('' +
'<tr>' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'</tr>' +
'');
for(var x = 1; x < $('input').length; x++) {
$('#btd' + x ).val('');
}
$('.buttons').attr('rowspan', $('tr').length);
}
});
$(".hide").click(function () {
$("form").hide();
});
$(".add").click(function () {
$("form").show();
});
$(".edit").click(function () {
$("form").show();
$.each($(this).parent().parent().find('td'), function (key, val) {
$("form input[type=text]").eq(key).val($(val).text());
})
});
$("#show").click(function () {
//$("form").show();
//$("#btd1").val("Vlad");
//$("#btd2").val("Andrei");
//$("#btd3").val("vTask");
// $("#btd4").val("Ceva");
//$("#btd5").val("Alceva");
});
});
<!DOCTYPE html>
<html >
<head >
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<title ></title >
</head >
<body >
<form class="a" action="" method="post" hidden>
<input type="text" name="nume" id="btd1" value="" >
<input type="text" name="prenume" id="btd2" value="" >
<input type="text" name="email" id="btd3" value="" >
<input type="text" name="telefon" id="btd4" value="" >
<input type="text" name="parola" id="btd5" value="" >
<input type="button" id="submit" value="Submit" name="submit" />
</form >
<table border="2" >
<tr >
<td >Vlad</td >
<td >Andrei</td >
<td >vTask</td >
<td >Ceva</td >
<td >Alceva</td >
<td class="buttons" style="vertical-align: top">
<button class="add" >Add</button >
<button class="hide" >Hide</button >
<button class="edit" >Edit</button >
</td >
</tr >
</table >
</body >
</html >
Thanks for the help in advance
My fellow romanian you need something like this:
$(document).ready(function () {
$('#submit').on('click', function () {
var valid = true,
message = '';
$('form input').each(function () {
var $this = $(this);
if (!$this.val()) {
var inputName = $this.attr('name');
valid = false;
message += 'Please enter your ' + inputName + '\n';
}
});
if (!valid) {
alert(message);
} else {
$('table').append('' +
'<tr>' +
'<td>' + $('#btd1').val() + '</td>' +
'<td>' + $('#btd2').val() + '</td>' +
'<td>' + $('#btd3').val() + '</td>' +
'<td>' + $('#btd4').val() + '</td>' +
'<td>' + $('#btd5').val() + '</td>' +
'<td class="buttons" style="vertical-align: top"><button class="add" >Add</button><button class="hide" >Hide</button><button class="edit">Edit</button></td >'+
'</tr>' +
'');
for(var x = 1; x < $('input').length; x++) {
$('#btd' + x ).val('');
}
}
});
$("body").on('click','.hide',function () {
$("form").hide();
});
$("body").on('click','.add',function () {
$("form").show();
});
$("body").on('click','.edit',function () {
$("form").show();
$.each($(this).closest('tr').find('td:not(".buttons")'), function (key, val) {
$("form input[type=text]").eq(key).val($(val).text());
})
});
$("#show").click(function () {
//$("form").show();
//$("#btd1").val("Vlad");
//$("#btd2").val("Andrei");
//$("#btd3").val("vTask");
// $("#btd4").val("Ceva");
//$("#btd5").val("Alceva");
});
});
<!DOCTYPE html>
<html >
<head >
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<title ></title >
</head >
<body >
<form class="a" action="" method="post" hidden>
<input type="text" name="nume" id="btd1" value="" >
<input type="text" name="prenume" id="btd2" value="" >
<input type="text" name="email" id="btd3" value="" >
<input type="text" name="telefon" id="btd4" value="" >
<input type="text" name="parola" id="btd5" value="" >
<input type="button" id="submit" value="Submit" name="submit" />
</form >
<table border="2" >
<tr >
<td >Vlad</td >
<td >Andrei</td >
<td >vTask</td >
<td >Ceva</td >
<td >Alceva</td >
<td class="buttons">
<button class="add" >Add</button >
<button class="hide" >Hide</button >
<button class="edit" >Edit</button >
</td >
</tr >
</table >
</body >
</html >

How to get Javascript method to print in my HTML

I'm really frustrated trying to get my html and javascript code to work together. I am trying to get the user information from the storeClientData() to print on top of the reservationMessage. I have been working on it for the last 4 hours with no luck. Any help would be much appreciated.
I want to get a output that would show like:
Mr. Firstname, Lastname, street, city, province/state, country, contact info.
Then:
Car size and price, options(ex. navigation), duration in days, cost of rental.
<!DOCTYPE html>
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern ="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type = "email" pattern = "[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onClick="showReservations(); return false;">
<input type = "reset" value = "Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name=type value=25>Small $25.00<br>
<input type=radio name=type value=35>Midsize $35.00<br>
<input type=radio name=type value=45>Full-sized $45.00<br>
<input type=radio name=type value=50 >Van $50.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox name=navigationSystem value= "10" >Navigation System $10.00<br>
<input type=checkbox name=childSeat value="5" >Child Seat $5.00<br>
<input type=checkbox name=roofRack value="15" >Roof Rack $15.00<br>
<input type=checkbox name=bicycleRack value="15" >Bicycle Rack $15.00<br>
</center>
</td>
</tr>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onClick="calculateRental(); showFinal(); return false;">
</center>
</td>
</tr>
</table>
</div>
<div id="showFinal" style="display:none;">
<h3><span id="reservationResult"; </span></h3>
</div>
</form>
</center>
</body>
</html>
var customerData=[];
function storeClientData(){
var honorific=document.getElementById("honorific").value
customerData[0]=honorific;
var firstName=document.getElementById("firstName").value;
customerData[1]=firstName;
var lastName=document.getElementById("lastName").value;
customerData[2]=lastName;
var street=document.getElementById("street").value;
customerData[3]=street;
var city=document.getElementById("city").value;
customerData[4]=city;
var stateProvince=document.getElementById("stateProvince").value
customerData[5]=stateProvince;
var country=document.getElementById("country").value;
customerData[6]=country;
var businessNumber=document.getElementById("businessNumber").value;
customerData[7]=businessNumber;
var homeNumber=document.getElementById("homeNumber").value;
customerData[8]=homeNumber;
var emailAddress=document.getElementById("emailAddress").value;
customerData[9]=emailAddress;
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]);
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental(){
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x<document.costEstimation.type.length; x++){
if(document.costEstimation.type[x].checked){
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if(document.costEstimation.navigationSystem.checked){
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
}if (document.costEstimation.childSeat.checked){
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
}if (document.costEstimation.roofRack.checked){
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
}if (document.costEstimation.bicycleRack.checked){
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration*carSize)+(duration*extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly=false;
document.getElementById("firstName").readOnly=false;
document.getElementById("lastName").readOnly=false;
document.getElementById("street").disabled=false;
document.getElementById("city").readOnly=false;
document.getElementById("stateProvince").readOnly=false;
document.getElementById("country").disabled=false;
document.getElementById("homeNumber").readOnly=false;
document.getElementById("businessNumber").readOnly=false;
document.getElementById("emailAddress").disabled=false;
}
function showReservations() {
document.getElementById("reservations").style.display = "block";
}
function showFinal() {
document.getElementById("showFinal").style.display = "block";
}
var customerData = [];
function storeClientData() {
var honorific = document.getElementById("honorific").value
customerData[0] = honorific;
var firstName = document.getElementById("firstName").value;
customerData[1] = firstName;
var lastName = document.getElementById("lastName").value;
customerData[2] = lastName;
var street = document.getElementById("street").value;
customerData[3] = street;
var city = document.getElementById("city").value;
customerData[4] = city;
var stateProvince = document.getElementById("stateProvince").value
customerData[5] = stateProvince;
var country = document.getElementById("country").value;
customerData[6] = country;
var businessNumber = document.getElementById("businessNumber").value;
customerData[7] = businessNumber;
var homeNumber = document.getElementById("homeNumber").value;
customerData[8] = homeNumber;
var emailAddress = document.getElementById("emailAddress").value;
customerData[9] = emailAddress;
var CarSize = document.querySelector('input[name="type"]:checked').value;
customerData[10] = CarSize;
var prices = document.getElementsByClassName('addtionClass');
var str = "";
for (var i = 0; i < prices.length; i++) {
if (prices[i].checked)
{
str += prices[i].value + ",";
}
}
customerData[11] = str;
var duration = document.getElementById('duration').value;
customerData[12] = duration;
duration = parseFloat(duration)
var customerMessage = (customerData[0] + customerData[1] + " " + customerData[2]
+ "<br>" + customerData[3]
+ "<br>" + customerData[4]
+ "<br>" + customerData[5]
+ "<br>" + customerData[6]
+ "<br>" + customerData[7]
+ "<br>" + customerData[8]
+ "<br>" + customerData[9]
+ "<br>" + customerData[10]
+ "<br>" + customerData[11]
+ "<br>" + customerData[12]
);
calculateRental();
document.getElementById("customerResult").innerHTML = customerMessage;
setFormToEdit();
}
function calculateRental() {
var carSize = parseFloat(0);
var extraAmount = parseFloat(0);
var totalCost = parseFloat(0);
var message = " ";
var reservationMessage = " ";
var duration = parseFloat(0)
for (x = 0; x < document.costEstimation.type.length; x++) {
if (document.costEstimation.type[x].checked) {
carSize = document.costEstimation.type[x].value;
}
}
carSize = parseFloat(carSize);
if (document.costEstimation.navigationSystem.checked) {
extraAmount += parseFloat(document.costEstimation.navigationSystem.value);
message = (message + " Navigation system");
} if (document.costEstimation.childSeat.checked) {
extraAmount += parseFloat(document.costEstimation.childSeat.value);
message = (message + " Child seat");
} if (document.costEstimation.roofRack.checked) {
extraAmount += parseFloat(document.costEstimation.roofRack.value);
message = (message + " Roof rack");
} if (document.costEstimation.bicycleRack.checked) {
extraAmount += parseFloat(document.costEstimation.bicycleRack.value);
message = (message + " Bicycle rack");
}
duration = (document.getElementById("duration").value);
duration = parseFloat(duration)
totalCost = (duration * carSize) + (duration * extraAmount);
reservationMessage += ("Car Information:" + "<br>" + "Rental cost: " + carSize + "<br>" + "Additional Options: " + message + "<br>" + "Total cost: " + totalCost);
document.getElementById("reservationResult").innerHTML = reservationMessage;
}
function setFormToEdit() {
document.getElementById("honorific").readOnly = false;
document.getElementById("firstName").readOnly = false;
document.getElementById("lastName").readOnly = false;
document.getElementById("street").disabled = false;
document.getElementById("city").readOnly = false;
document.getElementById("stateProvince").readOnly = false;
document.getElementById("country").disabled = false;
document.getElementById("homeNumber").readOnly = false;
document.getElementById("businessNumber").readOnly = false;
document.getElementById("emailAddress").disabled = false;
}
debugger;
function showReservations() {
document.getElementById('reservations').style.display = 'block';
}
function showFinal() {
document.getElementById('showFinalResult').style.display = 'block';
}
<html>
<head>
<title>Dodgy Brakes Car Rental</title>
<meta charset="utf-8" />
<link href="new.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="processregistration.js"></script>
</head>
<center>
<img src="logo.jpg" height="250" width="auto">
</center>
<body>
<center>
<form name=costEstimation>
<input type="button" value="Print HTML" onclick="storeClientData(); return false;" />
<div id="customerResult">
</div>
<table>
<tr>
<td>
<select required id="honorific">
<option value=None>None</option>
<option value=Mr.>Mr.</option>
<option value=Mrs.>Mrs.</option>
<option value=Ms.>Ms.</option>
<option value=Dr.>Dr.</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="First Name" id="firstName">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,20}$" placeholder="Last Name" id="lastName">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Street" id="street">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="City" id="city">
</td>
</tr>
<tr>
<td>
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="State/Province" id="stateProvince">
<input type="text" pattern="[a-zA-Z0-9-\s]{2,25}" placeholder="Country" id="country">
</td>
</tr>
<tr>
<td>
<input type="text" placeholder="Business Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="businessNumber">
<input type="text" placeholder="Home Number" pattern="\d{3}[\-]\d{3}[\-]\d{4}" id="homeNumber">
</td>
</tr>
<tr>
<td>
<input type="email" pattern="[a-z0-9._%+-]+#[a-z0-9.-]+\.[a-z]{2,5}$" placeholder="E-mail" id="emailAddress">
</td>
</tr>
<tr>
<td>
<center>
<input type=button value="Register" onclick="showReservations(); return false;">
<input type="reset" value="Reset">
</center>
</td>
</tr>
</table>
<div id="reservations" style="display:none;">
<h3>Reservation Form</h3>
<table>
<tr>
<td>
<center>
<h4><u>Type of Vehicle</u></h4>
<input type=radio name="type" value=25>Small $25.00<br>
<input type=radio name="type" value=35>Midsize $35.00<br>
<input type=radio name= "type" value=45>Full-sized $45.00<br>
<input type=radio name="type" value=50>Van $50.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<h4><u>Additional Options</u></h4>
<input type=checkbox class="addtionClass" name=navigationSystem value="10">Navigation System $10.00<br>
<input type=checkbox class="addtionClass" name=childSeat value="5">Child Seat $5.00<br>
<input type=checkbox class="addtionClass" name=roofRack value="15">Roof Rack $15.00<br>
<input type=checkbox class="addtionClass" name=bicycleRack value="15">Bicycle Rack $15.00<br>
</center>
</tr></td>
<tr>
<td>
<center>
<br>
<input type="text" placeholder="Enter Days" id="duration">
<input type=button value="Calculate" onclick="calculateRental(); showFinal(); return false;">
</center>
</table>
</div>
<div id="showFinalResult" style="display:none;">
<h3><span id="reservationResult" > </span></h3>
</div>
</form>
</center>
</body>
</html>
You didn't add id="customerResult" attribute in HTML and also you didn't invoke storeClientData() function from HTML. That's the reason why you couldn't get user information from storeClientData() function and couldn't print it top of the reservation form.
I added <input type=button value="storeClientData" onClick="storeClientData(); return false;"> element before registeration button element in HTML and <div id="customerResult"></div> element top of the reservation form.
You can refer final code in jsfiddle link http://jsfiddle.net/ADukg/10171/.

Categories

Resources