I'm trying insert dynamic multiple rows textboxes generated value in a variable to send it through ajax json to server side.
Code for generating multiple dynamic values.
$('#btnASize').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var ToleranceMin = "<input type='text' ID='TolMin'+i value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax'+i value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnASizeR').click(function() {
var sizerangeMin = "<input type='text' ID='SizeMin' value='2.00' />";
var sizerangeMax = "<input type='text' ID='SizeMax' value='3.00' />";
var ToleranceMin = "<input type='text' ID='TolMin' value='1' />";
var ToleranceMax = "<input type='text' ID='TolMax' value='1' />";
var markup = "<tr><td>" + sizerangeMin + "</td><td>" + sizerangeMax + "</td><td>" + ToleranceMin + "</td><td>" + ToleranceMax + "</td></tr>";
$("#WireDimTbl tbody").append(markup);
});
$('#btnWdDelete').click(function() {
$("#WireDimTbl tbody>tr:last").remove();
})
Ajax code for sending data
<script type="text/javascript" src="http://cdn.jsdelivr.net/json2/0.1/json2.js"></script>
<script type="text/javascript">
$(function() {
$(document).on("click", "[id*=btnFrmSubmit]", function() {
var user = {};
user.PRODUCT_ID = 1;
user.TDC_NO = $("[id*=Tdc_No]").val();
$.ajax({
type: "POST",
url: "TDC.aspx/SaveFrmDetails",
data: JSON.stringify({
user: user
})
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
alert("Data has been added successfully.");
window.location.reload();
},
error: function(response) {
alert(response.responseText);
}
});
});
});
</script>
In the above ajax method i want to store values of dynamically generated multiple textboxes value in "var user" to send it through ajax method to server side but not getting any idea how to achieve it i have shown in above code only for a particular input box
"<th class='text-center'>TDC No.</th>" +
"<th><input id='Tdc_No' type='text' value='7y'/></th>".
how to achieve it for multiple dynamically generated input textboxes.
Code at server side i am just showing few items how am i doing.
public class User
{
public decimal PRODUCT_ID { get; set; }
public string TDC_NO { get; set; }
.
.
}
[WebMethod]
public static void SaveFrmDetails(User user)
{
string connectionString = ConfigurationManager.ConnectionStrings["condb"].ConnectionString;
using (OracleConnection con = new OracleConnection(connectionString))
{
using (OracleCommand cmd = new OracleCommand("INSERT INTO TDC_PRODUCT1(TDC_NO) VALUES (:TDC_NO)",con)
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue(":TDC_NO", user.TDC_NO);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
try like this , make use of .serializeArray() and find()
$( "#target" ).click(function() {
alert(JSON.stringify($("#WireDimTbl tbody").find(":input").serializeArray()));
});
jsfiddle working : https://jsfiddle.net/pranayamr/odja5te0/
Related
I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
I have an html table on my webpage that is displaying data that I am pulling from a MySql database. When a user clicks on one of the table rows, depending on the data in the row, another div on the page is supposed to update displaying other information. The problem is, when I try to update the inner html of the div from my c# code-behind page, nothing happens. No errors in the dev console, no exceptions thrown, nothing. Why is this happening and how can I fix it? What am I doing wrong?
HTML table data that is being produced through c# code:
protected void PopulateUsers(bool active)
{
ArrayList userList = new ArrayList();
Query query = new Query();
StringBuilder userListHTML2 = new StringBuilder();
string userListHTML = "" +
"<table runat=\"server\" id=\"userListTable\" class=\"table table-striped table-bordered table-hover\">" +
"<thead>" +
"<tr>" +
"<th>User ID</th>" +
"<th>Name</th>" +
"<th>E-Mail</th>" +
"<th>Phone</th>" +
"<th>IsActive</th>" +
"</tr>" +
"</thead>" +
"<tbody>";
string userListHTML3 = "" +
"</tbody>" +
"</table>";
switch (active)
{
case true:
userList = query.GetUserList(true);
break;
case false:
userList = query.GetUserList(false);
break;
}
foreach (User user in userList)
{
userListHTML2.Append(string.Format(#"
<tr>
<td>{0}</td>
<td>{1}</td>
<td>{2}</td>
<td>{3}</td>
<td>{4}</td>
</tr>", user.userID, user.displayName, user.email, user.phone, user.isActive));
}
userListDiv.InnerHtml = userListHTML + userListHTML2 + userListHTML3;
}
jQuery/javascript code capturing click:
function viewUserSpecifics(id) {
var data = id;
var xmlHttpRequest;
xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("testing.XMLHTTP");
if (xmlHttpRequest == null) {
alert("ajax not supported");
return null;
}
xmlHttpRequest.open("GET", "ManagerPopup.aspx?ID=" + data, true);
xmlHttpRequest.send(null);
//document.getElementById('userDataDiv').innerHTML.
}
$(document).ready(function () {
$('#userListTable tbody').on('click', 'tr', function () {
var tableData = $(this).children("td").map(function () {
return $(this).text();
}).get();
//$("#< %= userIDHidden.ClientID %>").val($.trim(tableData[0]));
//alert($.trim(tableData[0]));
viewUserSpecifics($.trim(tableData[0]));
return false;
});
});
Receiving the http request:
protected void Page_Load(object sender, EventArgs e)
{
PopulateUsers(true);
if (Request.QueryString["ID"] != null)
{
string ID = Request.QueryString["ID"];
SpecificUser(ID);
}
}
Method that is supposed to be updating div inner html:
protected void SpecificUser(string id)
{
System.Windows.Forms.MessageBox.Show(id);
Query query = new Query();
User specificUser = new User();
specificUser = query.GetUserSpecifics(Convert.ToInt32(id));
string newFormRow = "<div runat=\"server\" class=\"form-row\">";
string newFormGroup = "<div runat=\"server\" class=\"form-group\">";
string newFormGroupCol = "<div runat=\"server\" class=\"form-group col-md-6\">";
string closeDiv = "</div>";
string UserDataHTML1 = string.Format("" +
newFormRow +
"<label id=\"userIDLabel1\">User ID:</label>" +
"<label id=\"userIDLabel2\">{0}</label>" +
closeDiv +
newFormRow +
newFormGroupCol +
"<label id=\"lblFName\" for=\"txtFName\">First Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={1} />" +
closeDiv +
newFormGroupCol +
"<label id=\"lblLName\" for=\"txtLName\">Last Name: </label>" +
"<input id=\"txtFName\" class=\"form-control\" runat=\"server\" type=\"text\" value={2} />" +
closeDiv +
closeDiv, id, specificUser.fName, specificUser.lName);
userDataDiv.InnerHtml = UserDataHTML1;
}
Any help would be greatly appreciated! Thanks!
To update the html content you should send back a response from your C# route to the client, and update the html part by using jQuery with received data
This is code i have written to get checkbox value and add rows
can anyone have look on this and find what's the problem with this code
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
});
}
});
});
Rows are getting multipe if i checked thrice please go through image
I will suggest create a hashmap which contains checked elements. Triggering Onchange will just update your hashmap and call a function to create/delete rows. hashmaps are way faster and easy to code.Make your keys as id of table row. Depending on check or uncheck condition, call function which is required.
Before you create a new element and append, just check whether it exists. If does not exist, then add it. Just add id for text box and if condition. Below code may have syntax error, i just tested in browser. Maybe little tweaks needed.
$('.dm_list_data').on('change', function() {
var $sel = $(this);
val = $(this).val();
$opts = $sel.children();
prevUnselected = $sel.data('unselected');
var currUnselected = $opts.not(':selected').map(function() {
return this.value
}).get();
var currSelected = $('.dm_list_data').val();
var post_data = {
'deliver_id': currSelected
}
console.log(post_data);
$.ajax({
type: "POST",
url: base_url + 'curriculum/topicadd/get_deliver_method_details',
data: post_data,
datatype: "JSON",
success: function(msg) {
var JSONObject = JSON.parse(msg);
JSONObject.forEach(function(element) {
var delivery_mtd_name = element.delivery_mtd_name;
var ftfl_hours = element.ftfl_hours;
var assessment_hours = element.assessment_hours;
var slt_hours = element.slt_hours;
if($('#'+delivery_mtd_name).length==0)///added this line
{
//updated below line
var markup = "<tr><td><input type='text' name='record' value='" + delivery_mtd_name + "' id='" + delivery_mtd_name + "'></td><td><input type='text' name='record' value='" + ftfl_hours + "'></td><td><input type='text' name='record' value='" + assessment_hours + "'></td><td><input type='text' name='record' value='" + slt_hours + "'></td></tr>";
$("table tbody").append(markup);
}
});
}
});
});
My goal is get the attribute "nombreSubdireccion" of the table "subdireccion" show when insert/update a new registry of "area" via AJAX, the only way I got it is reloading the page because of DB::table. I don´t know where declare the join, pls help me (sorry for my speak)
there are the models:
class subdireccion extends Model
{
public $table = "subdireccion";
protected $primaryKey = 'idSubdireccion';
public $timestamps = false;
public $fillable=['nombreSubdireccion'];
}
class area extends Model
{
public $table = "area";
protected $primaryKey = 'idArea';
public $timestamps = false;
public $fillable = [
'nombreArea',
'subdireccion_idSubdireccion',
];
}
The AJAX file:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
console.log(data);
var area = '<tr id="area' + data.idArea + '">';
area += '<td>' + data.idArea + '</td><td>' + data.subdireccion_idSubdireccion + '</td><td>' + data.nombreArea + '</td>';
area += '<td><button class="btn btn-primary btn-detail open_modal" value="' + data.idArea + '">Editar</button>';
area += '<button class="btn btn-danger btn-delete delete-subdir" value="' + data.idArea + '">Eliminar</button></td>';
area += '</tr>';
if (state == "add") {
notify('¡ Área creada con éxito !', 'success');
$('#area-list').append(area);
} else {
notify('¡ área actualizada con éxito !', 'success');
$("#area" + area_id).replaceWith(area);
}
$('#form_area').trigger("reset");
$('#myModal').modal('hide')
},
error: function (data) {
notify('¡ ERROR !', 'error');
console.log('Error:', data);
}
});
The web.php (controller)
Route::get('areas', function () {
$subdirecciones = App\subdireccion::All();
$areas = DB::table('subdireccion as s')
->join('area as a', 's.idSubdireccion', '=', 'a.subdireccion_idSubdireccion')
->select('a.*', 's.nombreSubdireccion as subdireccion')
->paginate(10);
return view('admAreas', compact('areas','subdirecciones'));
});
Route::get('areas/{area_id?}',function($area_id){
$area = App\area::find($area_id);
return response()->json($area);
});
Route::post('areas',function(Request $request){
$area = App\area::create($request->input());
return response()->json($area);
});
Route::put('areas/{area_id?}',function(Request $request, $area_id){
$area = App\area::find($area_id);
$area->subdireccion_idSubdireccion = $request->subdireccion_idSubdireccion;
$area->nombreArea = $request->nombreArea;
$area->save();
return response()->json($area);
});
page-view
Best way is to define method in controller and make model calls for DB queries there so that you can use laravel functionalities properly.
Good day,
I have a table where you can dynamically add/remove rows, on each row you can add an select an item from the list its working perfectly at the moment, what I want to add is for it to retain the added rows and its values even if I page reload my browser?
I have seen on my research that you can attain it by using cookies/localStorage,but would be okay if I store many items on it?
heres my table looks like:
my JS:
function addRow(){
var rowCount = document.getElementById('tblItemList').rows.length - 1 ;
var rowArrayId = rowCount ;
var toBeAdded = document.getElementById('toBeAdded').value;
if (toBeAdded=='')
{ toBeAdded = 2; }
else if(toBeAdded>10)
{
toBeAdded = 10;
}
for (var i = 0; i < toBeAdded; i++) {
var rowToInsert = '';
rowToInsert = "<tr><td><input id='itemName"+rowArrayId+"' required name='product["+rowArrayId+"][name]' class='form-control col-lg-5 itemSearch' type='text' placeholder='select item' />"+
"<input type='hidden' class='rowId' value='"+rowArrayId+"'>"+
"<input type='hidden' name='product[" + rowArrayId + "][itemId]' id='itemId'></td>";
$("#tblItemList tbody").append(
rowToInsert+
"<td><textarea readonly name='product["+rowArrayId+"][description]' class='form-control description' rows='1' ></textarea></td>"+
"<td><input type='number' min='1' max='9999' name='product["+rowArrayId+"][quantity]' class='qty form-control' required />"+
"<input id='poItemId' type='hidden' name='product[" + rowArrayId + "][poContentId]'></td>"+
"<td><input type='number' min='1' step='any' max='9999' name='product["+rowArrayId+"][price]' class='price form-control' required /></td>"+
"<td class='subtotal'><center><h3>0.00</h3></center></td>"+
"<input type='hidden' name='product["+rowArrayId+"][delete]' class='hidden-deleted-id'>"+
"<td class='actions'><a href='#' class='btnRemoveRow btn btn-danger'>x</a></td>"+
"</tr>");
var rowId = "#itemName"+rowArrayId;
$(rowId).select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
formatNoMatches: function( term ) {
$('.select2-input').on('keyup', function(e) {
if(e.keyCode === 13)
{
$("#modalAdd").modal();
$(".select2-input").unbind( "keyup" );
}
});
return "<li class='select2-no-results'>"+"No results found.<button class='btn btn-success pull-right btn-xs' onClick='modal()'>Add New Item</button></li>";
},
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
rowArrayId = rowArrayId + 1;
};
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
$(".qty, .price").bind("keyup change", calculate);
};
the problem here is whenever Im refreshing the page the Items that I added will also be lost as well as those rows that I've added, any suggestions please? Thanks you very much for your time! Have a nice Day!
Your best bet here would be to cookies to store json data.
Your best bet here would be to cookies to store json data.
function storeRowData() {
var data = [];
$('.TABLE_NAME tr').each(function () {
var $this = $(this),
pname = $this.find(PRODUCT_NAME_INPUT).val(),
desc = $this.find(PRODCUT_DESC_INPUT).val(),
quant = $this.find(PRODUCT_QUANTITY_INPUT).val(),
price = $this.find(PRODUCT_PRICE_INPUT).val();
var temp = { productName: pname, description: desc, quantity: quant, price: price };
data.push(temp);
});
$.cookie('Table_Rows', JSON.stringify(data), {OPTIONS});
}
Now whenever you add or remove rows, you can call this. And when you reload page just read the cookie and parse the string back to JSON and traverse and call addrow for each row.
NOTE: Be sure to read full documentation on jquery.cookie() Here
You can use window.location.reload(true) and $( document ).ready function where you can get current no. of rows.Define row count & column count variable as a global variable.
location.reload(true);
var rowCount,rowArrayId,toBeAdded ;
$(document).ready(function() {
rowCount= document.getElementById('tblItemList').rows.length - 1 ;
rowArrayId = rowCount ;
toBeAdded = document.getElementById('toBeAdded').value;
});