I have the following script which populates a table with data when a dropdown value is selected :
<script>
$(document).ready(function(){
$('#commodity_name').change(function (){
//picks the value of the selected commodity_name from the dropdown
option = $(this).find('option:selected').val();
html='';
htmlhead='';
// alert(option)
$.ajax({
type:"GET",
//gets data from the url specified based on the selected commodity_name in the dropdown
url:"<?php echo base_url();?>user_transactions/return_details/"+option,
dataType:"json",
success:function(data){
for(i=0;i<data.length;i++){
//Loops through the data to give out the data in a table format
//alert(data[i].transaction_type)
html += '<tr>\n\
<td><input type="text" id="commodity_name' + i + '" name="commodity_name[]" value="'+data[i].commodity_name+'"/></td>\n\
<td><input type="text" id="transaction_type' + i + '" name="transaction_type[]" value="'+data[i].transaction_type+'"/></td>\n\
<td><input type="text" id="total_quantity' + i + '" name="total_quantity[]" value="'+data[i].total_quantity+'"/></td>\n\
<td><input type="text" id="remarks' + i + '" name="remarks[]" value="'+data[i].remarks+'"/></td>\n\
<td><input type="text" id="unit_cost' + i + '" name="unit_cost[]" value="'+data[i].unit_cost+'"/></td>\n\
<td></td><td></td></tr> ';
}
htmlhead+='\n\
<th>Commodity Name</th>\n\
<th>Transaction Type</th> \n\
<th>Available Quantity</th> \n\
<th>Available Quantity</th> \n\
<th>Department</th>\n\
<th>Requestor Name</th>\n\
';
//alert(html);
//alert(htmlhead);
$('#thead').append(htmlhead);
$('#you').append(html);
//delegated submit handlers for the forms inside the table
$('#issue_1').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url()?>transactions/issues', $('#Issues_Form').serialize(), function () {
//success do something
alert("Success");
var url = "<?php echo base_url()?>transactions/view_request";
$(location).attr('href',url);
}).fail(function () {
//error do something
alert("Failed please try again later or contact the system Administrator");
})
})
},
error:function(data){
}
})
});
});
</script>
How can I clear the data from the html table that has been appended when I select the next commodity_name in the drop down list , I get only the data returned from the new select I have picked from the drop down list.
Just empty the html before appending.
...
$('#thead').empty();
$('#you').empty();
$('#thead').append(htmlhead);
$('#you').append(html);
...
Try to use the .detach() method of Jquery. Here the link: http://api.jquery.com/detach/
Related
Good Afternoon All,
This is my first project in asp.net mvc. I want to display a list of product with available stock quantity from database from controller to view.It is display properly but in product name only first word is displaying Ex. (Raw Steel) then only Raw is displaying .But If I update it as RawSteel then it is display as RawSteel .
Method in controller to get data and pass it to view :
[HttpGet]
public JsonResult Get_StkData(int id=0)
{
Session["Outwordid"] = id;
Outword obj_Outword = new Outword();
List<Outword> outword_list = new List<Outword>();
outword_list = obj_stckdb.Get_MaterialwiseStock();
return Json(outword_list, JsonRequestBehavior.AllowGet);
}
function get_Materialstock(id) {
$.ajax({
url: "/SalesStock/Get_StkData/" + id,
type: "GET",
contentType: "application/json;charset=UTF-8",
dataType: "json",
success: function (data) {
var row;
$.each(data, function (i, v1) {
row += "<tr><td><input class='nm form-control' readonly id='nm' value=" + v1.Material_nm + " /></td><td><input class='quantity form-control' readonly id='quantity' value=" + v1.Avail_Qty + " /></td><td><input class='rq form-control' id='rq' value='0' /></td><td style='visibility: collapse'><input class='mid form-control' readonly id='mid' value=" + v1.Material_Id + " /></td></tr>"
});
$("#custTable").append(row);
$('#modal-updateStock').modal('show');
}
});```
Product Name
<th style="width:150px;text-align:center">Available <br />Quantity</th>
<th style="width:150px;text-align:center">Used <br />Quantity</th>
<th style="visibility:collapse">Material_Id</th>
</tr>
</table>```
Sorry for my english.
Use jquery template. Creating a template with plain jquery/javascript appending rows is a pain in the ass. Basicly what you have to do (if you don't want to use a plugin) is give your tbody an id (tbodyItems in this example) and then:
var html = "";
for(var i = 0; i < data.length; i++){
html += "<tr>";
html += `<td>${data[i].something}</td>`;
html += `<td>${data[i].otherSomething}</td>`;
html += `<td>${data[i].anotherSomething}</td>`;
html += "</tr>";
}
$("#tbodyItems").html(html);
I have this JavaScript
function pickdet(Id) {
//alert(Id);
var dd = Id;
$.ajax({
cache: false,
url: "/PVSigns1/GetDetails",
data: { 'Id' : Id },
type: "GET",
dataType: "json",
success: function (data) {
//alert('i dey here')
var row = "";
var baseurl = '#Url.Action("Edit","PVSigns1")' + '?Id=';
$.each(data, function (index, item) {
var clickUrl = baseurl + item.PVSignId;
//row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue + "</td><td> <input type= 'button' onclick= location.href = + '<Url.Action("Create", "PVSigns1", new { Id = item.PVSignId }) ' />" + "</td></tr>";
row += "<tr><td>" + item.VitalSigns.Sign + "</td><td>" + item.SignValue +
"</td><td> <button class='editbtn btn btn-xs btn-success' data-url = '" + clickUrl + "'> <i class='fa fa-edit fa-lg'></i> Edit</button></td></tr>";
});
$("#pvv").html(row);
},
error: function (result) {
$("#pvv").html('Nothing to show <br /> <p />' + result);
}
});
}
$(function () {
$("button.editbtn").click(function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
});
When I run it, it display perfectly on the browser, but the link created don't work, and when I view the page source, the tbody part which the code above is supposed to inject, doesn't get rendered.
This is what I get, Click on any of the green buttons
in the top table, it loads the second table. The issue is with the second table.
Note: I am using JQuery Datatables.
This the rendered output from page source
<div>
<h3> Details</h3>
<table id="Pv" class="table table-condensed">
<thead>
<tr>
<th>Sign</th>
<th> Value </th>
<th></th>
</tr>
</thead>
<tbody id="pvv">
</tbody>
</table>
Notice <tbody id="pvv"> is empty, not table elements there. What is the issue?
You need to use delegation of dom element for click event. which element generated after binding event after existing dom
$("#Pv").on('click','button.editbtn', function (e) {
alert("url");
e.preventDefault();
//e.defaultPrevented();
window.location.href = $(this).attr("url");
});
I am taking the data from textbox and option field using AJAX request to the server storing it to db, creating the row and attaching it to table.
$("#addRecord").click(function(e) {
e.preventDefault();
var question_id = $("#questionId").val();
var question_text = $("#questionText").val();
$.ajax({
url: "addContestAnswer.html",
type: "post",
dataType: "json",
data: {"questionId": question_id, "contestText": question_text},
success: function(data){
addRows(data.questionId,data.contestText);
// calling the function to create row
},
error: function (request, status, error) {
console.log("error" + status);
}
});
});
creating the row
function addRows(questionId ,questionText) {
var deleteButton = 'delete';
var fileUpload = '<input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc" />';
var row = "<tr><td class=\"ques_id\">"+questionId+"</td><td class=\"ques_text\">"+questionText+"</td><td class=\"ques_file\">"+fileUpload+"</td><td></td><td>"+deleteButton+"</td></tr>";
$('#recordTable tr:last').after(row);
$("#questionId").val("-1");
$("#questionText").val("");
}
So far the html generated is looking good.
But when I'm refreshing the page, none of the html IDs,classes and Names of generated row are getting preserved.
generated row after ajax call
<tr>
<td class="ques_id">17</td>
<td class="ques_text">asddgfdg</td>
<td class="ques_file"><input type="file" name="supportingDocument" accept="application/pdf" id="uploadSupportingDoc"></td>
<td></td>
<td>delete</td>
</tr>
After refreshing the page
<tr>
<td>17</td>
<td>asddgfdg</td>
<td><input type="file" name="" id=""></td>
<td></td>
<td>delete</td>
</tr>
why is it happening? am I missing some tweak while generating the row, if not what's the solution?
i have dropdown boxes for user_id and er and once both selected i want to load all the data as rows. please advice.
below is my controller
$getShifts = Shifts::Where('user_id','=',$user_id)->Where('week_id','=',$week)->get();
how can i proceed
table
<table class="table table-hover">
<tr class="table-header">
<th>Day</th>
<th>Date</th>
<th>Start</th>
<th>End</th>
<th>Total
<br/> Hours
</th>
<th>Run
<br/> Type
</th>
<th>Edit
<br/> / Delete
</th>
</tr>
EDIT
plese check below code which i have tried
success: function(data) {
var json_obj = $.parseJSON(data);//parse JSON
var output="<tr>";
for (var i in json_obj)
{
output+=
"<td>" + json_obj[i].id + "</td>"+
"<td>" + json_obj[i].bus_no + "</td>"+
"<td>" + json_obj[i].shift_no + "</td>"
;
}
output+="</tr>";
$('#span').html(output);
}
You should call your controller function in ajax and in controller you will get the selected data, so based on that run required query.
$(document).ready(function() {
$("#combo, #user_id").change(function(){
var combo = $('#combo option:selected').val();
var user_id = $('#user_id option:selected').val();
if(combo && user_id) {
$.ajax({
url: "path to controller function",
type: "POST",
dataType: "HTML",
async: false,
data:{combo:combo.user_id:user_id},
success: function(data) {
alert(data) // here you ll see the data from controllen, you can manipulate according to your requirement.
}
});
}
});
});
in controller
echo "
<tr>
<td>$day</td>
<td>$date</td>
<td>$start</td>
<td>$end</td>
<td>$end</td>
<td>$end</td>
</tr> ";
manipulate all fields in to a tr in controller and in ajax success() append the data to table.
I want to create hidden field to put id in it and i have never done that before...
Here is my code:
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table id="mytable" class="t"> </table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId))
$row.append($('<td/>').html(row.CountryName));
$hidden = $(' <input type="hidden" name="hid" value=""' + row.CountryId + '">');
$row.append($hidden);
and please tell me how to get id from the hidden field something like this:
$(document).on("click", '.editbtn', function () {
var associateID = $(this).parents("tr").find('td').find(":input").val();
alert(associateID);
});
Thanks in Advance
You can get the value of <input name='hid'> by using the selector $('input[name="hid"]').val(). However, it seems that you have an .editBtn in every row, so you can try using the selector
var associateID = $(this).parents('tr').find('input[name="hid"]').val();
I noticed there's an extra " after the assignment of value, there should only be one, e.g.
$hidden = $(' <input type="hidden" name="hid" value="' + row.CountryId + '">');