How to edit and update table row dynamically in jquery and HTML - javascript

I am adding rows to table dynamically,now i am trying to edit table rows.
I click on edit, values are getting in text boxes after edit values i am clicking the add button but i created like new row not updated.
Any mistakes in my code
<form class="form-horizontal" role="form" id="chargesForm">
<div class="col-md-6">
<div class="form-group ">
<label for="minAmt" class="col-lg-4 control-label">MinAmmount</label>
<div class="col-lg-6">
<input type="text" class="form-control" id="minAmt" name="minAmt" />
</div>
</div>
<div class="form-group ">
<label for="maxAmt" class="col-lg-4 control-label">MaxAmmount</label>
<div class="col-lg-6">
<input type="text" class="form-control" id="maxAmt" name="maxAmt"/>
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group ">
<label for="type" class="col-lg-4 control-label">Type</label>
<select size="1" id="type" name="type">
<option value="Flat" selected="selected">
Flat
</option>
<option value="Percentage">
Percentage
</option>
</select>
</div>
</div>
<div class="col-md-12">
<div class="form-actions btnzone">
<button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" ><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
<a class="btn btn-danger" ><i class=""></i>Back</a>
</div>
</div>
</form>
<form class="form-horizontal" role="form" id="chargestableForm">
<div class="col-md-12" style="height:150px;overflow:auto;margin-top:5px;">
<table id="charges" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
<thead style="background-color:#CCE5FF">
<tr>
<th>MinAmmount</th>
<th>MaxAmmount</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</form>
i added rows with the help of jquery
var i=0;
$("button#savebutton").click(function(){
var minAmt=$("#minAmt").val();
var maxAmt=$("#maxAmt").val();
var type=$("#type").val();
i++;
var new_row = "<tr id='row"+i+"' class='info'><td class='minAmt'>" + minAmt + "</td><td class='maxAmt'>" + maxAmt + "</td><td class='type'>" + type + "</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'></a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''></a></span></tr>";
$("table tbody").append(new_row);
$("#minAmt").val($('td.maxAmt').last().text()).prop("disabled","disabled");
$("#maxAmt").val('');
//$("#type").val('');
});
$(document).on('click', 'span.deleterow', function () {
$(this).parents('tr').remove();
return false;
});
$(document).on('click', 'span.editrow', function () {
$("#minAmt").val($(this).closest('tr').find('td.minAmt').text()).prop("disabled","disabled");
$("#maxAmt").val($(this).closest('tr').find('td.maxAmt').text()).prop("disabled","disabled");
$("#type").val($(this).closest('tr').find('td.type').text());
});

Hi you can follow this link, I have used your code and updated it a lil.
link: https://jsfiddle.net/u7ycrxph/
Updated Code :
currentRow = null;
$("button#savebutton").click(function(){
//....
if(currentRow){
$("table tbody").find($(currentRow)).replaceWith(new_row);
currentRow = null;
}
else{
$("table tbody").append(new_row);
}
....//
});
$(document).on('click', 'span.editrow', function () {
currentRow= $(this).parents('tr');
//....
});

Use replaceWith()
Add a hidden field to denote which row is being edited.
<input type="hidden" id="currentRow"/>
On Edit
$(document).on('click', 'span.editrow', function () {
$("#currentRow").val($(this).closest("tr").attr("id"));
}):
On the click of Save in Edit mode create a new row template with the updated values and replace the existing row with the new one.
$("button#savebutton").click(function(){
if($("#currentRow").val()){
var row = $("table tbody").find('#'+$("#currentRow").val());
// var updated_row = //Updated template of the existing row
row.replaceWith (updated_row);
$("#currentRow").val("");
}
});

Related

how to compare listbox values and table values in javascript?

In my scenario just select the list box options, that values and text going to append to the table rows, but im facing small issues, user not allow to select same options (already selected options) and user not allow to append same values in the table.. if user select same option show alert messages like, 'you are already selected, select another option' like that..
here is my sample code fiddle..
Fiddle
Sample snippet here..
$("#excist_supp").on("change", function() {
$(".indexDrop").hide();
var newText = $("#excist_supp option:selected").text();
var newValue = $("#excist_supp option:selected").val();
$("#letterTable tbody").append('<tr><td><input type="text" id="sm_supp" value="' + newText + '" class="form-control newStyle1" name="sm_supp" readonly></td><td><input type="text" id="sm_code" value="' + newValue + '" class="form-control newStyle2" name="sm_code" readonly></td><td><button type="button" class="adRow ibtnDel newExcist" style="width:30%;position: relative;right: 25%; margin-bottom:0px">x</button></a></td></tr>');
$("#letterTable tr").each(function(i) {
var count = (i) - 1;
if (i === 0) return;
var input1 = $(this).find('.newStyle1');
var input2 = $(this).find('.newStyle2');
// id
input1.eq(0).attr("id", "sm_supp" + count); // Text fields
input2.eq(0).attr("id", "sm_code" + count);
// name
input1.eq(0).attr("name", "sm_supp[" + count + "]"); // Text fields
input2.eq(0).attr("name", "sm_code[" + count + "]");
});
});
/* compare two fields */
$('#excist_supp').change(function() {
$("#letterTable tr").each(function(i) {
var listVal = $('#excist_supp').val();
var tableVal = $('.newStyle2').val();
var nawTab = JSON.stringify(tableVal);
if (listVal == nawTab) {
alert('Matching!');
return true;
} else {
alert('Not matching!');
return false;
}
});
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<div class="row">
<!-- Existing Suppliers -->
<div class="col-sm-6">
<div class="col-12">
<div class="row">
<div class="col-12">
<input class="form-control serch" id="supSearch" type="search" placeholder="Search Existing Suppliers..">
<div class="selector">
<select class="col-12 listbox newBox" name="List_0" size="20" id="excist_supp" style="height: 125px !important;">
<option class="indexDrop">Choose Existing Suppliers</option>
<option value="0000">Komal </option>
<option value="0001">Ranjeet</option>
<option value="0002">Vishal </option>
<option value="0003">Gaurav</option>
<option value="0004">Dhanpat</option>
<option value="0005">Joe</option>
<option value="0006">Gowri</option>
<option value="0007">shankar</option>
<option value="0008">Dhanpat</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!-- Table -->
<div class="col-5">
<div class="container">
<div class="row clearfix">
<div class="table-wrapper">
<div class="table-scroll">
<table id="letterTable" class="table table-bordered table-striped order-scroll order-list" style="width: 95%;">
<thead>
<tr style="background-color: #680f79;color: #fff;">
<th class="text-center">Supplier Name</th>
<th class="text-center">Supplier Code</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody id="mytbody" style="text-align: center;">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
With $("#excist_supp").on("change".... and $('#excist_supp').change(function()... you are attaching the same event to the same element twice.
You can create a temporary array of all the used list values and create a function to check if the current value is exist in that array or not using Array.prototype.includes().
Try the following way:
$("#excist_supp").on("change", function() {
if(!checkValue()){
$(".indexDrop").hide();
var newText = $("#excist_supp option:selected").text();
var newValue = $("#excist_supp option:selected").val();
$("#letterTable tbody").append('<tr><td><input type="text" id="sm_supp" value="' + newText + '" class="form-control newStyle1" name="sm_supp" readonly></td><td><input type="text" id="sm_code" value="' + newValue + '" class="form-control newStyle2" name="sm_code" readonly></td><td><button type="button" class="adRow ibtnDel newExcist" style="width:30%;position: relative;right: 25%; margin-bottom:0px">x</button></a></td></tr>');
$("#letterTable tr").each(function(i) {
var count = (i) - 1;
if (i === 0) return;
var input1 = $(this).find('.newStyle1');
var input2 = $(this).find('.newStyle2');
// id
input1.eq(0).attr("id", "sm_supp" + count); // Text fields
input2.eq(0).attr("id", "sm_code" + count);
// name
input1.eq(0).attr("name", "sm_supp[" + count + "]"); // Text fields
input2.eq(0).attr("name", "sm_code[" + count + "]");
});
}
});
/* compare two fields */
var temp = [];
function checkValue() {
var listVal = $('#excist_supp').val();
var tableVal = $('.newStyle2').val();
var nawTab = JSON.stringify(tableVal);
if (temp.includes(listVal)) {
alert('Matching!');
return true;
} else {
alert('Not matching!');
temp.push(listVal)
return false;
}
}
<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.4.1/css/bootstrap.min.css">
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js"></script>
<div class="row">
<!-- Existing Suppliers -->
<div class="col-sm-6">
<div class="col-12">
<div class="row">
<div class="col-12">
<input class="form-control serch" id="supSearch" type="search" placeholder="Search Existing Suppliers..">
<div class="selector">
<select class="col-12 listbox newBox" name="List_0" size="20" id="excist_supp" style="height: 125px !important;">
<option class="indexDrop">Choose Existing Suppliers</option>
<option value="0000">Komal </option>
<option value="0001">Ranjeet</option>
<option value="0002">Vishal </option>
<option value="0003">Gaurav</option>
<option value="0004">Dhanpat</option>
<option value="0005">Joe</option>
<option value="0006">Gowri</option>
<option value="0007">shankar</option>
<option value="0008">Dhanpat</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!-- Table -->
<div class="col-5">
<div class="container">
<div class="row clearfix">
<div class="table-wrapper">
<div class="table-scroll">
<table id="letterTable" class="table table-bordered table-striped order-scroll order-list" style="width: 95%;">
<thead>
<tr style="background-color: #680f79;color: #fff;">
<th class="text-center">Supplier Name</th>
<th class="text-center">Supplier Code</th>
<th class="text-center">Action</th>
</tr>
</thead>
<tbody id="mytbody" style="text-align: center;">
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>

Create dynamic input in dynamic form when I select an option

I am trying to create a dynamic form that adds another field when choosing Verification select, the problem is that when I add fields of options in Verification at the time of adding another form, the options that I previously added appear, as I do to add a new form and don't show added options? I appreciate your help thanks!
$(document).ready(function() {
$('.verificar-free').hide();
$('.duplicate-free').hide();
$('.optionRow').hide();
var count = 2;
//duplicate
$('a.add-free').on('click', function() {
//clone
var row = $('.duplicate-free').clone();
$(row).insertAfter('.aditional-box-free');
$(row).show();
//add new ids
$(row).find('select').attr('id', 'select-free_' + count);
//remove duplicate class
$(row).removeClass('duplicate-free');
//onchange of select
$('select').on('change', function() {
var value = $(this).val();
var select = $(this).parent();
if (value == 1) {
$(select).siblings('.input-free').show();
$(select).siblings('.ocultar-free').hide();
} else {
$(select).siblings('.input-free').hide();
}
if (value == 2) {
$(select).siblings('.ocultar-free').show();
$(select).siblings('.verificar-free').show();
} else {
$(select).siblings('.verificar-free').hide();
}
});
//add option
$(".addRow-free").click(function() {
var html = "<div class='option-free' id='" + count + "'><div class='form-group'><div class='input-group select'><input type='text' class='form-control' placeholder='Añade opción' /><span class='input-group-btn'><button class='btn btn-primary remove-option' type='button'><a class='remove-tipe' href='javascript: void(0)'><span class='glyphicon glyphicon-trash' style='color:white'></span></a></button></span></div></div></div>";
var form = $(html);
$(this).closest(".verificar-free").find(".optionRow-free").append(form);
});
count++;
});
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="aditional-questions text">
<div class="aditional-box-free">
<p class="aditional-text" for=""><b>Add Question</b>
<a class="btn btn-primary agregar add-free" href="javascript: void(0)" type="button"><span></span>Add</a>
</p>
</div>
<div class="duplicate-free all-free" style="text-align: center">
<div class="box-question">
<div class="row">
<label class="type-question-text" for="">Question Type</label>
<div class="col-md-12">
<select class="form-control select">
<option value="1">Text</option>
<option value="2">Verification</option>
</select>
</div>
<div class="row ocultar-free">
<div class="col-md-12">
<label class="type-question-text" for="">Title</label>
<div class="form-group">
<input type="text" id="" class="form-control text general" placeholder="Question">
</div>
</div>
</div>
<!--aditional option-->
<div class="row verificar-free">
<div class="text">
<div class="col-md-6">
</div>
</div>
<div class="text option text" style="margin-top:10px;">
<a class="btn btn-primary addRow-free" href="javascript: void(0)" type="button"><span></span>Add Option</a>
</div>
<br>
<div class="form-group optionRow-free">
</div>
</div>
</div>
<br>
</div>
</div>
</div>
If I'm not wrong with your question.
The problem is you got same(duplicate) added input right? (If more than 1 question)
Change this line
$(".optionRow-free").append(form);
To
$(this).closest(".verificar-free").find(".optionRow-free").append(form);

How to insert the dynamic multiple row values into a database

<script src=" https://code.jquery.com/jquery-3.2.1.js" type="text/javascript"></script>
<script>
var i=0;
currentRow = null;
$("button#savebutton").click(function(){
var cat = $("#cat-list").val();
var display = $("#displayname").val();
var subcat = $("#subcat-list").val();
var order = $("#privilage").val();
i++;
var new_row = "<tr id='row"+i+"' class='info'><td class='cat'>" + cat + "</td><td class='display'>" + display + "</td><td class='type'>" + subcat +"</td><td>"+order +"</td><td><span class='editrow'><a class='fa fa-edit' href='javascript: void(0);'>Edit</a></span></td><td><span class='deleterow'><a class='glyphicon glyphicon-trash' href=''>Delete</a></span></tr>";
if(currentRow){
$("table tbody").find($(currentRow)).replaceWith(new_row);
currentRow = null;
}
else{
$("table tbody").append(new_row);
}
});
$(document).on('click', 'span.deleterow', function () {
$(this).parents('tr').remove();
return false;
});
$(document).on('click', 'span.editrow', function () {
currentRow= $(this).parents('tr');
});
</script>
<script>
$(document).ready(function(){
$("#secondbtn").click (function(){
var category = $("#cat-list").val();
var display = $("#displayname").val();
var subcat = $("#subcat-list").val();
var privilage = $("#privilage").val();
alert(category);
$.ajax({
type:"POST",
url:"query1.php",
data:{display:display_name,category:category,subcat:pagename,privilage:privilage},
success:function(data){
alert("successfully updated");
}
});
});
});
</script>
<html>
<body>
<form method="POST" action="">
<label>Select your Category:</label>
<input type="text" id="cat-list"/>
</br>
<label> Display Name:</label>
<input type="text" name="display_name" id="displayname" d />
</div>
<label> Select your Subcategory:</label>
<input type="text" id="subcat-list" >
<label>Set Order</label>
<select name="privilage" id="privilage" required>
<option value="">Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
</form>
<div class="col-md-12">
<div class = "panel1">
<button type="button" class="btn btn-success savebtn" style="padding: 6px 12px;margin-left: 40%;" id="savebutton" onclick="getFirstClicked()" ><i class="icon-check-sign" aria-hidden="false"></i>Add</button>
</div>
</div>
</form>
<form class="form-horizontal" role="form" id="chargestableForm">
<div class="col-md-12">
<table id="pTable" class="table table-hover" width="100%" cellspacing="0" style="border: 1px; height:10px;" >
<thead style="background-color:#CCE5FF">
<tr>
<th>Category</th>
<th>DisplayName</th>
<th>Subcategory</th>
<th>Order</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class = "panel2">
<button type="submit" name="import" id="secondbtn" > Import Database</button>
</div>
</div>
</form>
Context:In this code there is an html form,when adding the details in the form and clicks the add button there is a table row is created which is editable and delete. Then we can add the number of rows and that rows are added upto the table.I want to enter these table row values to a database when clicking the import button.

Ajax not working on multiple inserts - CI

I want to save multiple data in one go using codeigniter and then on success load the data on my datatable wihtout refreshing the whole page. I am able to do this successfully if I use modal and insert a single value but when I try to save multiple values, it doesn't work. I produce my input boxes on button click. Below are my codes:
CONTROLLER
public function add_multiple_orders(){
$dataset=[];
$item_name=$this->input->post('m_item_name');
$quantity=$this->input->post('m_quantity');
$amount=$this->input->post('m_amount');
$order_comment=$this->input->post('m_order_comment');
$branch_name=$this->input->post('m_branch_name');
$date_added=$this->input->post('m_date_added');
for($i=0;$i<sizeof($item_name);$i++){
$dataset[$i]=array(
'date_added'=>$date_added,
'item_name'=>$item_name[$i],
'quantity'=>$quantity[$i],
'amount'=>$amount[$i],
'ordered_by'=>$this->session->userdata['username'],
'order_status'=>'ordered',
'order_comment'=>$order_comment[$i],
'branch_name'=>$branch_name
);
}
$result=$this->sales_model->insert_mult_orders($dataset);
}
VIEW
<a name="mult_page">
<button class="btn btn-info" data-toggle="collapse" data-target="#add_multiple" style="margin-left: 20px;">Add Multiple Orders</button>
<div class="collapse" id="add_multiple" style="width: 95%; margin: 0 auto; margin-top: 10px;">
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
</div>
<div class="panel-body">
<form class="form_mult_ordrs form-inline" method="post">
<div class="form-group">
<label for="m_date_added">Date</label>
<input type="date" name="m_date_added" required>
</div>
<div class="form-group">
<label for="m_branch_name" class="control-label">Branch Name</label>
<select name="m_branch_name" class="form-control">
<option value="superdome">Superdome</option>';
<option value="seaside">Sea Side</option>
<option value="robinsons">Robinsons</option>
</select>
</div>
<div class="btn btn-warning pull-right" onclick="add_new_row()">Add more</div>
<hr>
<div style="font-weight: bold;">Total Php <input type="text" id="total_result" placeholder="0.00" class="form-control"></div>
<br>
<table id="mult_ord_tbl" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th class="ui-help-center">Item Name</th>
<th class="ui-help-center">Quantity</th>
<th class="ui-help-center">Amount</th>
<th class="ui-help-center">Comment</th>
<th class="ui-help-center">Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<select name="item_name[]" class="form-control">
<?php foreach($items as $item){
echo '<option value"='.$item->item_name.'">'.$item->item_name.'</option>';
} ?>
</select>
</td>
<td><input type="text" name="m_quantity[]" placeholder="Quantity"></td>
<td><input type="text" name="m_amount[]" id='m_amount[]' placeholder="Amount" onblur="total_values()"></td>
<td><input type="text" name="m_order_comment[]" placeholder="Commment"></td>
<td>
<button class="btn btn-danger" onclick="delete_row(this)"><i class="glyphicon glyphicon-remove"></i></button>
</td>
</tr>
</tbody>
</table>
<tr>
<td colspan="12">
<button id="btn_mult_ordrs" class="btn btn-success" onclick="save_mult_ordrs()" value="">Submit All</button>
</td>
</tr>
</form>
</div> <!-- end of panel body -->
<div class="panel-footer">
footer
</div>
</div> <!-- end of panel primary -->
</div> <!-- end of column 12 -->
</div> <!-- end of row -->
</div> <!-- end of collapse -->
<script type="text/javascript">
$(document).ready(function(){
$('#table_id').DataTable({
"order":[[0,"desc"]]
});
});
function save_mult_ordrs(){
if(confirm("Are you done?")){
var url="<?php echo site_url('sales/add_multiple_orders')?>";
add_new_row();
// $("#form_mult_ordrs").submit();
$.ajax({
url:url,
type:"POST",
data:$('#form_mult_ordrs').serialize(),
datatype:"JSON",
success:function(data)
{
alert('All data has been saved.');
location.reload();
},
error:function(jqXHR, textStatus, errorThrown){
alert('Error in saving.');
}
});
}
}
function add_new_row(){
var arrTables = document.getElementById('mult_ord_tbl');
var oRows = arrTables.rows;
var numRows = oRows.length;
var newRow = document.getElementById('mult_ord_tbl').insertRow( numRows );
var cell1=newRow.insertCell(0);
var cell2=newRow.insertCell(1);
var cell3=newRow.insertCell(2);
var cell4=newRow.insertCell(3);
var cell5=newRow.insertCell(4);
cell1.innerHTML = "<tr><td><select name='m_item_name[]' class='form-control'>" +
<?php
foreach($items as $item){
echo ('"<option value=\"'.$item->item_name.'\">'.$item->item_name.'</option>"+');
}
?>
+ "</select></td>";
cell2.innerHTML="<td height='5'><input type='text' name='m_quantity[]' placeholder='Quantity'></td>";
cell3.innerHTML="<td height='5'><input type='text' name='m_amount[]' placeholder='Amount' onblur='total_values()'></td>"
cell4.innerHTML="<td height='5'><input type='text' name='m_order_comment[]' placeholder='Comment'></td>";
cell5.innerHTML="<td><button class='btn btn-danger' onclick='delete_row(this)''><i class='glyphicon glyphicon-remove'></i></button></td></tr>";
}
</script>
MODEL
public function insert_mult_orders($data){
$this->db->insert_batch('piercapitan.sls_ordrs',$data);
return $this->db->affected_rows();
}
Your help is immensely appreciated.
Never mind guys. I found what's wrong. It's my form id! I somehow placed the name on the class and not on the id.
<form class="form_mult_ordrs form-inline" method="post">
It should have been:
<form id="form_mult_ordrs" class="form-inline" method="post">

Array items are not appending to the HTML Table tbody with jQuery

I have a table that is formatted and I want the contents of my array to be displayed in them, but nothing is displayed when I load my web page. It seems to not be adding anything to the tbody id that I have created in my html code. Here is my code that I have.
var Movie = function (movieTitle, movieYear, length, format, rating, favorite) {
this.movieTitle = movieTitle;
this.movieYear = movieYear;
this.length = length;
this.format = format;
this.rating = rating;
this.favorite = favorite;
};
var movies = new Array();
movies[0] = new Movie("Hangover", 2009, 210, "Dvd", 4, "Yes");
movies[1] = new Movie("Taken", 2008, 200, "BluRay", 5, "Yes");
movies[2] = new Movie("Avengers", 2011, 242, "Cloud", 3, "No");
movies[3] = new Movie("Iron Man", 2010, 311, "Computer", 4, "Yes");
movies[4] = new Movie("Rounders", 1990, 252, "Dvd", 5, "Yes");
movies[5] = new Movie("42", 2013, 202, "BluRay", 4, "No");
movies[6] = new Movie("Water Boy", 1988, 211, "Dvd", 5, "Yes");
movies[7] = new Movie("21", 2010, 192, "Cloud", 3, "No");
movies[8] = new Movie("I am Legend", 2009, "Computer", 5, "Yes");
movies[9] = new Movie("Titanic", 1997, 320, "Dvd", 2, "No");
$("#add").click(function(event){
var movie = new Movie(
$("#movieTitle").val(),
$("#movieYear").val(),
$("#lengthInMins").val(),
$("#formatSelections").val(),
$("#ratingSelections").val(),
$("#favoriteSelction").val()
);
movies[movies.length] = movie;
updateTableData();
$("#formMovieData").hide(500, function() {
$("#showMovies").show();
});
event.preventDefault(); // Prevents the defualt anchor actions
});
function updateTableData() {
//$("#movieData").empty();
var tbody = $("#movieData");
for (var i = 0; i < movies.length; i++) {
var id = i + "_" + movies[i]["movieTitle"];
var tr = "<tr>";
for (var key in movies[i]) {
tr += "<td>" + movies[i][key] + "</td>";
}
tr += "<td><a id='" + id + "' href='#'" + "> Edit </a></td>";
tr += "<td><a id='" + id + "' href='#'" + "> Delete </a></td>";
tr += "</tr>";
tbody.append(tr);
$("#" + id).click(function () {
var elementId = $(this).attr("id");
var idx = elementId.indexOf("_");
var index = parseInt(elementId.substr(0, idx));
$("#movieTitle").val(movies[index].movieTitle);
$("#movieYear").val(movies[index].movieYear);
$("#lengthInMins").val(movies[index].length);
$("#formatSelections").val(movies[index].format);
$("#ratingSelections").val(movies[index].rating);
$("#favoriteSelection").val(movies[index].favorite);
$("#showMovies").hide(500, function() {
$("#formMovieData").show();
});
});
}
}
Here is my html code I have hard coded some items that I want to show in my tables also I have the ability to add a new one as well. I am working on the process to add or delete the information as well, but I need to show items first.
<!DOCTYPE html>
<html>
<head>
<title>Homework 3</title>
<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<link href="../Content/StyleSheet.css" rel="stylesheet" />
<script src="../Scripts/jquery-2.1.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>
</head>
<body>
<header><h1 class="bg-primary">The Movie Collection</h1></header>
<nav id="navigation" class="col-sm-3">
<ul class="nav navbar-default">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">Movie Options
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a id="addMovieDataCmd" href="#">Add New Movies</a></li>
<li><a id="showMoviesCmd" href="#">Show All Movies</a></li>
<li><a id="browseNewMoviesCmd" href="http://www.fandango.com/new-dvd-releases">Browse New Release Movies</a></li>
</ul>
</li>
</ul>
</nav>
<div id="mainContent" class="col-sm-9">
<form id="formMovieData" class="form-horizontal">
<fieldset>
<legend>Add New Movie</legend>
<div class="form-group">
<label for="movieTitle" class="col-sm-1 control-label">Movie Title</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="movieTitle" name="movieTitle" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="movieYear" class="col-sm-1 control-label">Year of Movie</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="movieYear" name="movieYear" type="text" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="lengthInMins" class="col-sm-1 control-label">Length In Minutes</label>
<div class="col-sm-offset-1 col-sm-5">
<input id="lengthInMins" name="lengthInMins" type="number" class="form-control" />
</div>
</div>
<div class="form-group">
<label for="format" class="col-sm-1 control-label">Format</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="formatSelections" name="selections" class="form-control">
<option>Dvd</option>
<option>BluRay</option>
<option>Computer</option>
<option>Cloud</option>
</select>
</div>
</div>
<div class="form-group">
<label for="rating" class="col-sm-1 control-label">Rating</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="ratingSelections" name="selections2" class="form-control">
<option>1</option>
<option>2</option>
<option selected>3</option>
<option>4</option>
<option>5</option>
</select>
</div>
</div>
<div class="form-group">
<label for="favorites" class="col-sm-1 control-label">Favorite</label>
<div class="col-sm-offset-1 col-sm-5">
<select id="favoriteSelection" name="selections3" class="form-control">
<option>Yes</option>
<option>No</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-5">
<input id="clear" name="clear" type="reset" value="Clear" class="btn btn-default" />enter code here
<input id="add" name="submit" type="submit" value="Add" class="btn btn-primary" />
</div>
</div>
</fieldset>
</form>
<div id="showMovies">
<fieldset>
<legend>List of Movies</legend>
<table class="table table-striped">
<thead>
<tr>
<th>Movie Id</th>
<th>Movie Title</th>
<th>Movie Year</th>
<th>Movie Length</th>
<th>Movie Format</th>
<th>Movie Rating</th>
<th>Favorite Movie</th>
</tr>
</thead>
<tbody id="movieData">
</tbody>
</table>
</fieldset>
</div>
</div>
<script src="../Scripts/homework3.js"></script>
</body>
</html>
You are forgetting to call function updateTableData() when loading page:
Make sure you are doing it by:
$(document).ready(function(){
updateTableData();
});
Also, your button shouldn't be submit type in order to not submit form, just throw Javascript events:
<input id="add" name="submit" type="button" value="Add" class="btn btn-primary" />
Finally, there's a method call to a non existant function:
hideshow("#formMovieData", 500, "#showMovies", 500);
You can just remove it from code. (I'm not seeing any advantage in using some hide/show effect on click "Add")
See an example in jsFiddle

Categories