I have a dynamic table that I will be submitted to database.
The html is looked like this :
<form id="upload">
<div class="box-body">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="tableReport">
<thead>
<th>TYPE</th>
<th>ITEM</th>
<th>DAMAGE</th>
<th>REPAIR</th>
<th>REMARKS</th>
<th>MANHOUR</th>
<th><button class="btn btn-block btn-primary" id="addRow" type="button">ADD</button></th>
</thead>
<tbody>
<!--GENERATED BY JQUERY-->
</tbody>
</table>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-info" type="submit">Upload</button>
</div>
</form>
See, on my <th>, I have a button with id addRow that have a function to add a row on a last row.
This is the code :
$(document).on('click', '#addRow', function () {
var selType = '<select class="form-control" name="type">';
var selItem = '<select class="form-control" name="item">';
var selDamage = '<select class="form-control" name="damage">';
var selRepair = '<select class="form-control" name="repair">';
$.each(<?php echo json_encode($type); ?>, function (i, elem) {
selType += '<option>' + elem.NAMA_TYPE + '</option>';
});
$.each(<?php echo json_encode($item); ?>, function (i, elem) {
selItem += '<option>' + elem.NAMA_ITEM + '</option>';
});
$.each(<?php echo json_encode($damage_codes); ?>, function (i, elem) {
selDamage += '<option>' + elem.NAMA_DAMAGE + '</option>';
});
$.each(<?php echo json_encode($repair_codes); ?>, function (i, elem) {
selRepair += '<option>' + elem.NAMA_REPAIR + '</option>';
});
selType += '</select>';
selItem += '</select>';
selDamage += '</select>';
selRepair += '</select>';
$("#tableReport").find('tbody').append('<tr><td>' + selType +
'</td><td>' + selItem +
'</td><td>' + selDamage +
'</td><td>' + selRepair +
'</td><td><input type="text" class="form-control name="remarks" placeholder="Describe it..">' +
'</td><td><input type="text" class="form-control time" name="manhour">' +
'</td><td><button class="btn btn-block btn-danger">Delete</button>' +
'</td></tr>');
$(".time").inputmask("hh:mm");
});
Now, this is the problem. How to handling the form. When <button class="btn btn-info" type="submit">Upload</button> is clicked to submit, I will handled it use jquery ajax. The code looked like this
$(document).on('submit', '#upload', function(){
/*First, How to handled the dynamic row ?? */
/* Commonly, I use var aVar = $('selector').val(); */
/* Ex, I have two rows, How bout to handle two select option in different row ?*/
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : {/*dynamic row that will be passed : data*/}
dataType: 'json',
success: function(obj) {
})
return false;
});
How can I handle that dynamic row, and how can I debug if the post have success ?
UPDATED
This code to check the condition of a ship container. If a container have many damage, it will be representated with one row as one damage. If the container have 3 damage, it will be have 3 rows. I want to submit it on a table in my database in tbl_damage_detail. I have plan to multiple insert. So, I Imagine to store that rows into an array. with foreach, I will be inserted them.
JSFIDDLE
If the inputs are added correctly to the form you just need to submit the form with AJAX, no need for anything special, one way is to use the jQuery serialize() method like this.
$(document).on('submit', '#upload', function(event){
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : $(this).serialize(),
dataType: 'json',
success: function(obj) {
})
event.preventDefault();
});
with your code,i really don't know what you want to do .
first, "on" is used to bind event with dynamic dom ,but id=addRow is not a dynamic dom,it is unnecessary to use on
"$(document).on('click', '#addRow', function () {"
just use $("#addRow").click( function () {...})
and then, <form id="upload">, i am not sure you have decide to post date to service with submit, in fact ,here is a dynamic table ,if you use submit to post your data ,it may complex with your whole table data .(using submit , input must set the name tag)
i suggest you should handle each row data
//get every row data
var tableData = [] ;
$("#tableReport tbody tr").each( function(){
var tr = &(this);
var text2 = tr.find(".time").val(); //should use more clean tag
var data = {test2:test2}//...
tableData.push(data)
//use ajax with the data
});
//next handle the tableData with ajax
this scene is very fat to mvvm like: angular , vue.js or avalon.js ,use one of them,with more clean but less code .
Related
I am using CouchCMS. In CouchCMS there is a concept of repeatable regions. This in fact generates tables and displays the repeatable contents in it.
I have the repeatable region defined as:
<cms:repeatable name="item_detail" label="Item Detail" order="10" >
<cms:editable name="product" label="Product" type="dropdown" opt_values="Select =- | <cms:pages masterpage='product/product.php' order='asc' orderby='product_name'><cms:show product_name /><cms:if '<cms:not k_paginated_bottom />'>|</cms:if></cms:pages>" order="1" />
<cms:editable name="product_hsn" label="HSN" type="text" order="2" />hsn,qty,price,gst,amount
<cms:editable name="product_qty" label="Quantity" type="text" order="3" />
<cms:editable name="product_price" label="Price" type="text" order="4" />
<cms:editable name="product_tax" label="Tax" type="text" order="5" />
<cms:editable name="product_line_total_amount" label="Amount" type="text" order="6" />
</cms:repeatable>
Where the editables are the regions where we can fill in the data by bounding them to the respective textboxes/ selects, etc.
Now What I am trying to do is:
Select a value from the dropdown of the editable named "product".
When an option is selected, an AJAX is called. This AJAX in turn returns some data.
I am able to get the data, console log it or display it in a div or a table.
But what I really want to do is:
Since the repeatable region is shown is the form of a table, the exists. I want to be able to just get the AJAX JSON data displayed in the of the existing data.
If you see the editables above, a table exists with each editables' select/textbox in the , there are:
product (select, for product name)
product_hsn (textbox, with to be created and be filled by AJAX JSON)
product_qty (textbox, with to be created but needs to be blank)
product_price (textbox, with to be created and be filled by AJAX JSON)
product_tax (textbox, with to be created and be filled by AJAX JSON)
product_line_total_amount (textbox, with to be created but needs to be blank)
Now the repeatable region creates a structure as follows ( for the above defined repeatable region):
Product
HSN
Quantity
Price
Tax
Amount
Delete
<div>
<p class="addRow" id="addRow_f_item_detail"><a>Add a Row</a></p>
</div>
I can add new rows also right out of the box when using repeatable regions. If one observes ids and the names have a zero [0] this keeps on incrementing as one would add the new rows.
The script helping in this above code generation is:
if ( !window.COUCH ) var COUCH = {};
$(function(){
$('table.rr > tbody').sortable({
axis: "y",
handle: ".dg-arrange-table-rows-drag-icon",
helper: function (e, ui) {
// https://paulund.co.uk/fixed-width-sortable-tables
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
},
update: function( event, ui ){
var row = ui.item;
var tbody = $( row ).closest( 'tbody' );
tbody.trigger('_reorder');
},
start: function( event, ui ){
var row = ui.item;
row.trigger('_reorder_start');
},
stop: function( event, ui ){
var row = ui.item;
row.trigger('_reorder_stop');
},
});
});
COUCH.rrInit = function( field_id, default_row ){
var $field = $('#'+field_id);
$field.tableGear({addDefaultRow:default_row, stackLayout:1});
$field.on('click', '.col-actions .add-row', function(){
var $this = $(this);
var row_id = $this.attr('data_mosaic_row');
var add_btn = $('#addRow_'+field_id+' a');
add_btn.trigger("click", [row_id]);
});
}
COUCH.t_confirm_delete_row = "Delete this row?";
COUCH.t_no_data_message = "- No Data -";
Just in case if required this is my AJAX code, using which I am able to add a new but it is in a New while I want the to be appended to the same that contains the existing repeatable regions.
AJAX CODE:
$(document).on('change','select',function() {
var data = "";
$.ajax({
type:"GET",
url : "<cms:show k_site_link />generate/quotation-ajax.php",
data:
"select_id="+$(this).val(),
async: false
}).done(function(data) {
console.log(data);
var trHTML = '';
$.each(data.product_details, function (i, item) {
trHTML += "<tr id='f_item_detail-" + i + "'>" + '<td class="editable k_element_product_hsn"><div style="position:relative;"><input type="bound" name=" f_item_detail[0][product_hsn]" id="f_item_detail-[0]-product_hsn" class="form-control" value="' + item.product_hsn + '"/></div></td>' +
// '<td style="position:relative;"><input type="bound" name=" f_item_detail[0][product_price]" id="f_item_detail-[0]-product_price" class="form-control" value="' + item.product_price + '"/></td>' +
// '<td style="position:relative;"><input type="bound" name=" f_item_detail[0][product_tax]" id="f_item_detail-[0]-product_tax" class="form-control" value="' + item.product_tax + '"/></td>' +
'</tr>';
});
$('#f_item_detail').append(trHTML);
})
});
And my AJAX file has the code:
<?php require_once('../couch/cms.php'); ?>
<cms:set selected_product="<cms:gpc 'select_id' method='get' />" scope="global" />
<cms:content_type 'application/json'/>
<cms:template title="Quotation AJAX" hidden='1' parent="_generate_" />
{
"product_details":
[
<cms:pages masterpage='product/product.php' custom_field="product_name=<cms:show selected_product />" >
{
"product_hsn": "<cms:addslashes><cms:show product_hsn/></cms:addslashes>",
"product_price": "<cms:addslashes><cms:show min_selling_cost/></cms:addslashes>",
"product_tax": "<cms:addslashes><cms:show tax_on_purchase/></cms:addslashes>"
}<cms:if "<cms:not k_paginated_bottom/>">,</cms:if>
</cms:pages>
]
}
<?php COUCH::invoke(); ?>
What I am looking for:
Add the AJAX success JSON values to the respective textboxes in the existing , and rather than adding a new or or . I am unable to set the correct jQuery. Any help would be really appreciated.
Thanks in advance.
Regards!
#Swati:
Full HTML in this fiddle (with some changes in the AJAX part, which partially works and outputs what I want to achieve. The value is put into the textbox but for each new row the same textbox value is updated from the first row, if i could update the textbox values row wise it would be great)
EDIT #1
I have used your code (#Swati) as follows and yes it works fine (to an extent).
<script type="text/javascript">
$(document).ready(function(){
$("#f_item_detail-0-product").select2();
$('input#f_item_detail-0-product_hsn').attr('readonly', true).addClass("form-control");
$('input#f_item_detail-0-product_qty').attr('onchange', 'line_total()');
$('input#f_item_detail-0-product_price').attr('onchange', 'line_total()');
$('input#f_item_detail-0-product_tax').attr('readonly', true).addClass("form-control");
$('input#f_item_detail-0-line_tax_amount').attr('readonly', true).addClass("form-control");
$('input#f_item_detail-0-product_line_total_amount').attr('readonly', true).addClass("form-control");
});
var counter = 0;
$(document).ready(function() {
$(".addRow").click(function(){
counter++;
$("#f_item_detail-" + counter + "-product").select2();
});
});
$(document).on('change','select',function() {
var data = "";
var i = 0;
var indexs = $(this).closest("tr").index();//get index no
console.log(indexs);
$.ajax({
type:"GET",
url : "<cms:show k_site_link />generate/quotation-ajax.php",
data:
"select_id="+$(this).val(),
async: false
}).done(function(data) {
$('#f_item_detail-' + indexs + '-product_hsn').val(data.product_details[i].product_hsn).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_qty').attr('onchange', 'line_total()');
$('#f_item_detail-' + indexs + '-product_price').val(data.product_details[i].product_price).attr('onchange', 'line_total()');
$('input#f_item_detail-' + indexs + '-product_tax').val(data.product_details[i].product_tax).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-line_tax_amount').attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_line_total_amount').val(data.product_details[i].product_line_total_amount).attr('readonly', true).addClass("form-control");
});
});
function line_total(){
var line_qty = $('input#f_item_detail-' + indexs + '-product_qty').val();
var line_tax = $('input#f_item_detail-' + indexs + '-product_tax').val();
var line_cost = $('input#f_item_detail-' + indexs + '-product_price').val();
var line_tax_amount = parseFloat(((line_cost * line_tax)/100) * line_qty).toFixed(2);
var result = parseFloat((+line_qty * +line_cost) + +line_tax_amount).toFixed(2);
$('#f_item_detail-' + indexs + '-line_tax_amount').val(line_tax_amount).attr('hidden',true);
$('#f_item_detail-' + indexs + '-product_line_total_amount').val(result);
}
</script>
It is solving the issue of going back and editing the product and hence updating the line item value as you had suggested.
But if you see the function line_total() it breaks. And the total are not calculated. What do you suggest? How can we use the indexs value or something else. Also, I would be greatful if you could also suggest me how can we display the GST Amount total and Amount Total at the end with a Grand Total (GST Amount Total + Amount Total), I would be really greatful.
I am not good with javascript or jQuery at all.
Whenever your select-box gets change you can simply get closest tr from that select-box then .find() to find required inputs and add value there .
Demo Code :
$(document).on('change', 'select', function() {
var selector = $(this).closest("tr") //get closest tr
/* $.ajax({
type: "GET",
url: "<cms:show k_site_link />generate/quotation-ajax.php",
data: "select_id=" + $(this).val(),
async: false
}).done(function(data) {*/
//find your input and add value there
selector.find('.k_element_product_hsn input').val("ac"); //data.product_details[i].product_hsn
selector.find('.k_element_product_price input').val(124); //data.product_details[i].product_price
selector.find('.k_element_product_tax input').val(23); //data.product_details[i].product_tax
selector.find('.k_element_product_line_total_amount input').val(4356); //data.product_details[i].product_line_total_amount
selector.find('.k_element_product_qty input').val(2); //data.product_details[i].product_qty
/*}
})*/
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<table>
<tbody>
<tr id="newDataRow_f_item_detail" class="newRow even">
<td class="dg-arrange-table-rows-drag-icon"> </td>
<td class="editable k_element_product">
<div style="position:relative;">
<select name="data[xxx][product]" idx="data-xxx-product" id="data-xxx-product">
<option value="-">Select</option>
<option value="3Ply Mask">3Ply Mask</option>
<option value="Laptop i3 4th Gen">Laptop i3 4th Gen</option>
</select>
</div>
</td>
<td class="editable k_element_product_hsn">
<div style="position:relative;"><input type="text" idx="data-xxx-product_hsn" id="data-xxx-product_hsn" name="data[xxx][product_hsn]" value="">
</div>
</td>
<td class="editable k_element_product_qty">
<div style="position:relative;"><input type="text" idx="data-xxx-product_qty" id="data-xxx-product_qty" name="data[xxx][product_qty]" value="">
</div>
</td>
<td class="editable k_element_product_price">
<div style="position:relative;"><input type="text" idx="data-xxx-product_price" id="data-xxx-product_price" name="data[xxx][product_price]" value="">
</div>
</td>
<td class="editable k_element_product_tax">
<div style="position:relative;"><input type="text" idx="data-xxx-product_tax" id="data-xxx-product_tax" name="data[xxx][product_tax]" value="">
</div>
</td>
<td class="editable k_element_product_line_total_amount">
<div style="position:relative;"><input type="text" idx="data-xxx-product_line_total_amount" id="data-xxx-product_line_total_amount" name="data[xxx][product_line_total_amount]" value="">
</div>
</td>
<td class="delete"><input type="checkbox" name="delete[]" value="" id="deleteNULL_STRING" style="display: none;" /><label for="deleteNULL_STRING"> <img src="http://localhost/CTO/GXCPL-Billing/couch/addons/repeatable/tablegear/delete.gif" alt="Delete Row" /></label></td>
</tr>
<tr id="newDataRow_f_item_detail" class="newRow even">
<td class="dg-arrange-table-rows-drag-icon"> </td>
<td class="editable k_element_product">
<div style="position:relative;">
<select name="data[xxx][product]" idx="data-xxx-product" id="data-xxx-product">
<option value="-">Select</option>
<option value="3Ply Mask">3Ply Mask</option>
<option value="Laptop i3 4th Gen">Laptop i3 4th Gen</option>
</select>
</div>
</td>
<td class="editable k_element_product_hsn">
<div style="position:relative;"><input type="text" idx="data-xxx-product_hsn" id="data-xxx-product_hsn" name="data[xxx][product_hsn]" value="">
</div>
</td>
<td class="editable k_element_product_qty">
<div style="position:relative;"><input type="text" idx="data-xxx-product_qty" id="data-xxx-product_qty" name="data[xxx][product_qty]" value="">
</div>
</td>
<td class="editable k_element_product_price">
<div style="position:relative;"><input type="text" idx="data-xxx-product_price" id="data-xxx-product_price" name="data[xxx][product_price]" value="">
</div>
</td>
<td class="editable k_element_product_tax">
<div style="position:relative;"><input type="text" idx="data-xxx-product_tax" id="data-xxx-product_tax" name="data[xxx][product_tax]" value="">
</div>
</td>
<td class="editable k_element_product_line_total_amount">
<div style="position:relative;"><input type="text" idx="data-xxx-product_line_total_amount" id="data-xxx-product_line_total_amount" name="data[xxx][product_line_total_amount]" value="">
</div>
</td>
<td class="delete"><input type="checkbox" name="delete[]" value="" id="deleteNULL_STRING" style="display: none;" /><label for="deleteNULL_STRING"> <img src="http://localhost/CTO/GXCPL-Billing/couch/addons/repeatable/tablegear/delete.gif" alt="Delete Row" /></label></td>
</tr>
</tbody>
</table>
Updated 1 :
You can get index of tr which is change then using that index we can update that input values .
Updated Jquery code :
$(document).on('change', 'select', function() {
var data = "";
var i = 0;
var indexs = $(this).closest("tr").index();//get index no
console.log(indexs)
$.ajax({
type: "GET",
url: "<cms:show k_site_link />generate/quotation-ajax.php",
data: "select_id=" + $(this).val(),
async: false
}).done(function(data) {
$('#f_item_detail-' + indexs + '-product_hsn').val(data.product_details[i].product_hsn).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_qty').attr('onchange', 'add_number()');
$('#f_item_detail-' + indexs + '-product_price').val(data.product_details[i].product_price).attr('onchange', 'add_number()');
$('input#f_item_detail-' + indexs + '-product_tax').val(data.product_details[i].product_tax).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-line_tax_amount').attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_line_total_amount').val(data.product_details[i].product_line_total_amount).attr('readonly', true).addClass("form-control");
});
});
Update 2 :
You can pass this as a parameter to your line_total() then use that to get closest tr index and then do calculation according to that .
Updated Jquery code :
$(document).on('change', 'select', function() {
var indexs = $(this).closest("tr").index();
var selector = $(this); //save selector
var i = 0;
$.ajax({
type: "GET",
url: "<cms:show k_site_link />generate/quotation-ajax.php",
data: "select_id=" + $(this).val(),
async: false
}).done(function(data) {
console.log("de");
$('#f_item_detail-' + indexs + '-product_hsn').val(data.product_details[i].product_hsn).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_qty').attr('onchange', 'line_total(this)'); //pass this here ...
$('#f_item_detail-' + indexs + '-product_price').val(data.product_details[i].product_price).attr('onchange', 'line_total(this)'); //pass this here
$('input#f_item_detail-' + indexs + '-product_tax').val(data.product_details[i].product_tax).attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-line_tax_amount').attr('readonly', true).addClass("form-control");
$('#f_item_detail-' + indexs + '-product_line_total_amount').val(data.product_details[i].product_line_total_amount).attr('readonly', true).addClass("form-control");
line_total(selector); //call this
});
});
function line_total(selector) {
//do same here
var indexs = $(selector).closest("tr").index()
var line_qty = $('input#f_item_detail-' + indexs + '-product_qty').val() != "" ? $('input#f_item_detail-' + indexs + '-product_qty').val() : 1;
var line_tax = $('input#f_item_detail-' + indexs + '-product_tax').val();
var line_cost = $('input#f_item_detail-' + indexs + '-product_price').val();
var line_tax_amount = parseFloat(((line_cost * line_tax) / 100) * line_qty).toFixed(2);
var result = parseFloat((+line_qty * +line_cost) + +line_tax_amount).toFixed(2);
$('#f_item_detail-' + indexs + '-line_tax_amount').val(line_tax_amount).attr('hidden', true);
$('#f_item_detail-' + indexs + '-product_line_total_amount').val(result);
grand_total(); //call this
}
function grand_total() {
var grand = 0;
$(".k_element_product_line_total_amount input").each(function() {
grand += $(this).val() != "" ? parseFloat($(this).val()) : 0
})
$("#grand_total").text(grand + 100); //100 is gst change it...according to your need and change id where you need to display grand total
}
So I have been trying to get things on track. Finally, I have been able to do it:
The jQuery AJAX code that I was looking for to solve my problem is as below:
var counter = 0;
$(document).ready(function() {
$(".addRow").click(function(){
counter++;
});
});
$(document).on('change','select',function() {
var data = "";
var i = 0;
$.ajax({
type:"GET",
url : "<cms:show k_site_link />generate/quotation-ajax.php",
data:
"select_id="+$(this).val(),
async: false
}).done(function(data) {
$('#f_item_detail-'+ counter +'-product_hsn').val(data.product_details[i].product_hsn);
$('#f_item_detail-'+ counter +'-product_qty').val(data.product_details[i].product_qty);
$('#f_item_detail-'+ counter +'-product_price').val(data.product_details[i].product_price);
$('#f_item_detail-'+ counter +'-product_tax').val(data.product_details[i].product_tax);
$('#f_item_detail-'+ counter +'-product_line_total_amount').val(data.product_details[i].product_line_total_amount);
})
});
I am actually creating a global counter using:
var counter = 0;
$(document).ready(function() {
$(".addRow").click(function(){
var globalcounter = parseFloat(counter);
counter++;
});
});
And then passing the value of the global counter as "counter" to the ajax(). Everytime the "Add Row" is clicked, the counter value in passed then incremented. This helps me in giving the numbers to the id's of each rows input as:
$('#f_item_detail-'+ counter +'-product_hsn').val(data.product_details[i].product_hsn);
Here i in "data.product_details[i]" remains zero because the AJAX returns details for only one product per line-item.
I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {
Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );
Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>
Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});
I have a table element that is loaded by jQuery and have a hidden input element on each row of my table and a button to open a pop up.
My problem is that when I try to get the value of hidden input when the button is clicked, I am not getting the value and it says undefined (I have used a jQuery function to get the value in click event of the button)
// function to get the hidden input value
$(document).on("click", '#registerhere', function(event) {
var id = $(this).find('#gameid').val();
console.log(id);
alert(id);
$colinforeg = $('#exampleModal');
$colinforeg.modal('show');
});
// ajax function to load the table
$.ajax({
url: 'allevents.php',
dataType: 'json',
type: 'post',
success: function(data, textStatus, jQxhr) {
console.log(data);
$.each(data, function (i, item) {
console.log(item[0]);
var events = '<tr>';
events += '<td>'+item[1]+'</td>';
events += '<td>'+item[4]+'</td>';
events += '<td>'+item[5]+'</td>';
events += '<td>'+item[6]+'</td>';
events += '<td>'+item[2]+'</td>';
events += '<td>';
events += '<button type="button" class="btn btn-primary" id="registerhere"> Register Here';
events += '</button>';
events += '<input type="hidden" id="gameid" value="'+item[0]+'">';
events += '</td>';
events += '</tr>';
$('#events').append(events);
});
},
Firstly, you are repeating the same id attributes in each appended row which is invalid. If you want to group common elements use classes instead.
With regard to the DOM traversal issues, note that the #gameid element isn't a child of the button, so find() isn't going to work there. You could instead get the closest('tr') and use find() from there:
// function to get the hidden input value
$(document).on("click", '.registerhere', function(e) {
var id = $(this).closest('tr').find('.gameid').val();
console.log(id);
// work with your modal here...
});
// ajax function to load the table
var events = '<tr>';
events += '<td>';
events += '<button type="button" class="btn btn-primary registerhere">Register Here</button>';
events += '<input type="hidden" class="gameid" value="foo">';
events += '</td>';
events += '</tr>';
$('#events').append(events);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table>
<tbody id="events"></tbody>
</table>
I am trying to create a table in HTML that as a button on each row that acts a delete button. So when the button is click it will delete the html row as well as a row in the DB. What is the easiest way to do this?
This is what i have so far but it doesn't look good at all:
function GetSongs(id) {
$.ajax(
{
type: "Get",
url: "#Url.Action("GetSongs", "Game")",
data: { playlistId: id },
success: function (data) {
json = data;
var obj = JSON.parse(json);
for (var i in obj) {
songCount++;
playlist.push(obj[i].SongURL);
$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"editbtn" +">edit</button>"+ "</td></tr>");
}
$('#song-count').empty();
$('#song-count').append('Song Count: ' + songCount);
}
});
}
Here is my table:
<div id="player-playlist" style="height: 300px; overflow:scroll; overflow-x: hidden">
<table class="zebra" id="song-table" style="width:400px;">
<tr>
<th>Song</th>
</tr>
</table>
</div>
You can add delete buttons the same way you're adding edit buttons:
$("#song-table").append("<tr><td>" + obj[i].SongURL + "<button class=" +"delbtn" +">delete</button>"+ "</td></tr>");
$('button.delbtn').click(function(){
$(this).parent().remove();
});
http://jsfiddle.net/qGGPZ/2/
Give your button an onclick Javascript function that includes the id as a parameter:
"<button type='button' onclick='deleteThisItem(" + id + ")' >delete</button>"
Javascript function:
function deleteThisItem(theID){
// ajax call to delete theID from database
// refresh the table
}
Hey guys and gals I'm having some major issues trying to get my application to work. I've been trying to hack through this and am missing the very first part which is sending the correct input value (button value) to get the ball rolling, I'm sure this is something simple but I've been having an issue getting it working. I'd appreciate it if someone could pick out the error(s) to help me along.
This is extremely easy to do in PHP, but since this is a standalone offline
app I cannot use PHP =( I need to do all my fetching and parsing in JQuery
or Javascript....
We start with a very basic form with some buttons that have unique values.
<form>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
which triggers this function
$(function() {
$("form").submit(function() {
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
// $this.button.val() never makes it through?
queryJsonServer($(this), "class/");
return false;
});
});
I've tried things like
var button = $(this).attr("value");
var button = $('button').attr("value"); // ends up with the first buttons value,
// but never the selected or $(this).val()
$('button').click(function() { // which WILL console.log the buttons val,
console.log($(this).val()); // but will not let me turn it into a var?
return false; // ALSO this looks like it only reads the
}); // value the SECOND click?
The Mission here is to send the buttons value as a $_POST type over to a parser which will return the appropriate JSON array to be parsed, or to be stored in a Local SQLite DB.
Either way, here's the full code of the page, could someone please give me a hand, or if I need to clarify please let me know.
<?php
ini_set('display_errors', 1);
error_reporting(E_ERROR | E_PARSE);
var_export($_POST);
?>
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> </title>
<script src='http://www.google.com/jsapi'></script>
<script> google.load('jquery', '1.7.1'); </script>
<script>
$(function(){
$("form").submit(function()
{
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
var state = $(this).val();
return true;
});
// state is undefined. L29
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
});
// query json server for
function queryJsonServer(form, state, path)
{
// on first return or refresh inputs will be returrned
var view = $('input[name="orders"]:checked').val();
var url = path + "json.php?" + state; // status = button.val()
var state = $(this).attr("value"); // ends up class/json.php?undefined
// we have data, lets post to json parser and
$.getJSON(url, view, function(data)
{
$('form').unbind('submit').trigger('submit');
var items = [];
switch(state)
{
case 'load' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push((key == "report_number")
? '<td class="check" ><input type="checkbox" name="' + val + '" /></td><td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>'
: '<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
case 'down' :
// populate SQLite Database
break;
case 'view' :
$.each(data, function(index, obj) {
items.push('<tr>');
$.each(obj, function(key, val) {
items.push('<td><label class="caps" for="'+ key +'">'+ key.replace("_", " ") +'</label><input disabled="disabled" type="text" id="' + key + '" value="' + val + '" /></td>')
});
items.push('</tr>');
});
$('<div/>', {
'class': 'jsonOutput',
html: items.join('')
}).appendTo('#master');
break;
default:
return false;
break;
}
});
}
});
</script>
<style type="text/css">
p, ul {width:100%; text-align:left;font-size:80%;}
.reports_box {width:auto; padding:25px 20px 20px 20px;border:1px solid #91bce6;background-color:#eff5fb;}
.inputs {width:300px; font-size:15px;padding:5px;}
.check input {padding:0 !important;}
.caps {text-transform:capitalize;}
#reports_list td, #reports_list tr {padding:10px 0 10px 2px;color:#34567b;}
</style>
</head>
<body>
<div class="reports_box">
<form id='submit'>
<fieldset>
<legend>Select Orders</legend>
<table id='master'></table>
</div> <!-- end input1 -->
<div>
<button name="select" type="submit" id="btnLoad" value="load">Refresh</button>
<button name="select" type="submit" id="btnJson" value="down">Download JSON</button>
<button name="select" type="submit" id="btnView" value="view">View/Enter</button>
</div>
</fieldset>
</form>
</div> <!-- end reports_box -->
</body>
</html>
Block form submission unless triggered by a button.
When form submission is triggered by a button:
Use $(form).serialize() to serialize the form
add "&select=ButtonValue" to the serialized string
Use $.getJSON to send a get request to your server page and get a JSON object back.
FINAL EDIT: Here's a working fiddle where I use serialize correctly: http://jsfiddle.net/YYZGG/5/
(When using the code change the form action to your correct page)
$(function(){
$("form").submit(function()
{
var state;
/* what obj are we recieving?
$.each($(this), function(index, obj) {
console.log('Index: ' + index + ' Obj: '+ obj);
// returns this B/S: Index: 0 Obj: [object HTMLFormElement]
});
*/
$('button').click(function() {
state = $(this).val();
return true;
});
// state is NOW DEFINED
console.log(state);
// $this.button.val() never makes it through?
queryJsonServer($(this), state, "class/");
return false;
.......................
Also, if having trouble getting the right values, try:
$('button').on('click', function(e) {
console.log(e.target.value);
});
EDIT:
Are you sure it should'nt just be:
$("form").submit(function(e) {
var state = e.target.value;
console.log(state);
---------
Why does your submit not include a post inside it? The method your using is GET that's why it's not a POST, either use .submit() and .post() together or just use an entire different approach working all together using GET and .click() functions, but here's an example of what using .post() looks like:
<script>
/* attach a submit handler to the form */
$("#searchForm").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
term = $form.find( 'input[name="s"]' ).val(),
url = $form.attr( 'action' );
/* Send the data using post and put the results in a div */
$.post( url, { s: term },
function( data ) {
var content = $( data ).find( '#content' );
$( "#result" ).empty().append( content );
}
);
});
</script>
http://api.jquery.com/jQuery.post/