Dynamically created elements having the different values but the same index - javascript

My code is to create search suggestions after triggering the 'keyup' event, hence creating dynamic elements with a class "suggestion-box". On clicking any of "suggestion-box" classes, new dynamic elements, each with parent class "transaction-entry", are created. Each of the dynamically created "transaction-entry" classes has child class 'quantityInput' which is an input element. The major problem is this, each of the 'quantityInput' classes display their corresponding input values when delegated to a static element through the 'keyup' event trigger but not their corresponding indexes (displays only 0).
HTML CODE
<div class="col-sm-1">
<button type="button" id="delete-transact" class="btn btn-default" data-toggle="tooltip" title="Delete All Entries" data-placement="right">
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
</button>
</div>
<!-- Input field for search suggestion -->
<form method="POST" action="{{URL::to('/search/transaction')}}" id="transAction">
{{ csrf_field() }}
<div class="col-sm-12">
<div class="form-group">
<input type="text" name="searchItem" id="transProductSearch" class="form-control" value="" title=""
placeholder="Search product">
<!--Container for dynamically created class "suggestion-box"-->
<div id="suggestion-container"></div>
</div>
</div>
</form>
<div class="cover">
<div class="table-responsive">
<form action="" method="">
<table class="table table-hover">
<thead>
<tr>
<th>Product</th>
<th>Quantity purchased</th>
<th>Quantity Available</th>
<th>Price</th>
</tr>
</thead>
<!--Container for dynamically created class "transaction entry"-->
<tbody id="transaction-body">
</tbody>
<tfoot>
<tr class="tfoot">
<td>Total</td>
<td class="transactionTotal"></td>
<td></td>
<td></td>
</tr>
</tfoot>
</table>
</form>
</div>
</div>
JQUERY CODE
$('#transProductSearch').on('keyup',function (e) { //Event listener for ajax request
e.preventDefault();
if($(this).val() !== ""){
$.ajax({
type: "POST",
url: $('#transAction').attr('action'),
data: $('#transAction').serialize(),
success: function (response) {
$(".suggestion-box").remove();//Removing every dynamically created "suggestion-box" class on every successful AJAX request;
pEntities = [];
response = jQuery.parseJSON(response);
$.each(response, function (indexInArray, value) {
$("#suggestion-container").append($('<div>',{class:"suggestion-box", text:value.productName}));
pEntities[indexInArray] = {prodQuantity:"",prodId:"",prodPrice:"",prodName:""};
pEntities[indexInArray].prodQuantity = value.quantity;
pEntities[indexInArray].prodId = value.id;
pEntities[indexInArray].prodPrice = value.price;
pEntities[indexInArray].prodName = value.productName;
});
},
error: function () {
console.log($('#transAction').val());
}
});
}
else{
$('.suggestion-box').remove()//Removing every suggestion box if input field is empty
}
});
$('#suggestion-container').on("click",'.suggestion-box', function (e) { // Event delegation to append new "transaction-entry" class
var index = $(this).index();
$('#transaction-body').append('<tr class="transaction-entry"><input hidden class="prodId" value="'+pEntities[index].id+'"/><td>'+pEntities[index].prodName+'</td><td><input class="quantityInput" style="color:black" type="number"></td><td>'+pEntities[index].prodQuantity +'</td><td class="productPrice">'+pEntities[index].prodPrice +'</td></tr>');
$('.suggestion-box').remove();
})
$('#delete-transact').click(function (e) {//Event listener to remove all transaction entry classes
e.preventDefault();
$('#transaction-body').empty();
})
$('#transaction-body').on("keyup",'.quantityInput',function (e) {//Event Delegation to output quantityInput value and index
console.log($(this).val()+" "+$(this).index());
});

Related

Hiding and un-hiding table div based off of data being returned

I have a table that I want to be hidden there is no data to be displayed.
I have a controller action that returns data to display for the table. If data is returned, I want the table to be show, otherwise I want it hidden. I have tried several approaches to this and it seems like my fix is working (for a few seconds) but then once the controller returns the model, the table becomes hidden again. I am doing something wrong. How can I fix this? Below is my code:
HTML:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "submitForm"}))
{
<div class="row">
<div>
#Html.DropDownList("CasinoID", Model.TerminalReceiptPostData.CasinoIdDDL, "Select Casino", new { id = "cIdSearch", #class = "custom-class-for-dropdown card" })
</div>
<div>
<input id="datepicker" class="datepicker-base card" name="Date" placeholder="MM/DD/YYY" type="text"/>
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="search"> Search Transactions</button>
</div>
</div>
}
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Controller action:
[HttpPost]
public ActionResult Index(string CasinoID, DateTime Date)
{
//var id = Int32.Parse(Request.Form["CasinoID"].ToString());
var Cid = Request.Form["CasinoID"];
Cid = GetNumbers(Cid);
var id = Int32.Parse(Cid);
var model = TRBL.GetTransactionTestsData(id, Date);
model.TerminalReceiptPostData = TRBL.GetCasinosDDL();
return View(model);
}
and finally my JS function:
window.onload = function () {
$("#ReceiptsMainDiv").toggle();
var rowCount = $("#rowindex").length;
console.log(rowCount);
if (rowCount > 0) {
$("#ReceiptsMainDiv").toggle();
}
};
As you can see, the Form at the top contains the button, and the block below is the table that needs to be toggled.
Let me know if there is anything else you guys would need.
When you have results to show, <tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))"> will not produce ids of "rowIndex" (unlike what you might be expecting). Instead, you will have "rowIndex0", "rowIndex1", etc. Therefore, after rowCount will be zero, and your will not toggle.

html table response is not displayed in MVC view on button click jquery function

I am working on asp.net MVC application.
On button click below jQuery function gets called.
I get status === "success" and in response all rows are available in the .html(response) but he same data not showing in the view where html is defined (html is nothing but an modal pop up window).
jQuery function call:
var url = '#Url.Action("UserDetails", "CompanyUsage")';
var data1 = { dateTime: data.getValue(chart.getSelection()[0].row, 0), Company: company, serverID: ServerID, Organisation: Organisation, BusinessArea: BusinessArea, ApplicationName: ApplicationName, AppVersion: AppVersion, ADCheck: ADCheck }
$.post(url, data1)
.done(function (response, status, jqxhr) {
if (status === "success") {
$('#modal .modal-body').html(response);
$('#modal').modal('show');
$("#exportPopUpUserToExcel").show();
$(".multiselect").click(function () {
$(".btn-group").toggleClass("open");
});
}
else {
/* your "email doesn't exist" action */
var pan = 0;
}
})
.fail(function (jqxhr, status, errorThrown) {
/* do something when request errors */
});
};
return false;
};
View :
<div id="modal" class="modal fade">
<div class="modal-dialog" style="overflow-y: scroll; max-height:80%; width: 1200px; margin-top: 50px; margin-bottom:50px;left: 0px;">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<p>One fine body…</p>
#if (Model.UserList != null)
{
<div>
<table id="tableid" class="table table-striped table-hover3">
<tr>
<th>User ID</th>
<th>User Name</th>
<th>Company</th>
<th>License ID</th>
<th>Server ID</th>
<th>Start Time</th>
</tr>
#foreach (var item in Model.UserList)
{
<tr>
<td>
#item.UserID
</td>
<td>
#item.UserName
</td>
<td>
#item.Company
</td>
<td>
#item.LicenseId
</td>
<td>
#item.ServerID
</td>
<td>
#item.StartTime
</td>
</tr>
}
</table>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
I get the below resut with modal pop up data as blank body.
Update:
.html(response) contains the following data.
Also now I am using tbody tag instead of tr and th but getting the blank record same as previous.
Below is the updated code,
<div class="modal-body">
<p>One fine body…</p>
Hi
#if (Model.UserList != null)
{
<div>
<table id="tableid" class="table table-striped table-hover3">
<thead>
<tr>
<th>User ID</th>
<th>User Name</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.UserList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.UserName)
</td>
</tr>
}
</tbody>
</table>
</div>
}
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
The problem seem coming from this line:
$('#modal .modal-body').html(response);
According to the documentation, jQuery.html() used to replace existing HTML content with HTML string passed as its argument. Hence, it replaces all child HTML elements which uses modal-body CSS class with response object data including the table element, even response doesn't contain HTML elements. That's the reason why the table element disappear inside modal popup.
If your objective is to replace existing data inside table with data provided from AJAX response, you need to iterate response object, then create <tr> & <td> row elements for each iteration, and append each row to <tbody> element as provided in example below:
var url = '#Url.Action("UserDetails", "CompanyUsage")';
var data1 = { dateTime: data.getValue(chart.getSelection()[0].row, 0), Company: company, serverID: ServerID, Organisation: Organisation, BusinessArea: BusinessArea, ApplicationName: ApplicationName, AppVersion: AppVersion, ADCheck: ADCheck }
$.post(url, data1).done(function (response, status, jqxhr) {
if (status === "success") {
// set tbody selector
var $tbody = $('#tableid tbody');
// remove previous table entries
$tbody.empty();
var row = $('<tr>');
var cell = $('<td>');
// iterate the response and create table elements
$.each(response, function(i, item) {
row.append(
cell.text(item.UserId),
cell.text(item.UserName)
).appendTo($tbody);
});
// show the modal with table inside
$('#modal').modal('show');
$("#exportPopUpUserToExcel").show();
$(".multiselect").click(function () {
$(".btn-group").toggleClass("open");
});
}
else {
/* your "email doesn't exist" action */
var pan = 0;
}
})
.fail(function (jqxhr, status, errorThrown) {
/* do something when request errors */
});
Related issues:
Using jQuery to build table rows from Ajax response (Json)
Convert JSON array to an HTML table in jQuery

Display icon when at least one checkbox is checked

I display checkboxes in my table. Now when i check at least one checkbox, the icon must appear if not, it should be hidden. My icon is not hidden.
What am i doing wrong?
This is my code
<div class="row">
<div class="col-sm-12 ">
<a data-toggle="modal" id="btnAdd" data-target="#myModal" class="btn"> Add Items </a>
<i type="icon" class="fa fa-trash " ></i>
<div>
</div>
<table class="table" id="table">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
</tr>
</thead>
<tbody>
<td><input type="checkbox"></td>
//table data here
</tr>
#endforeach
</tbody>
</table>
var checkboxes = $("input[type='checkbox']"),
hideIcon = $("i[type='icon']");
checkboxes.click(function() {
hideIcon.attr("disabled", !checkboxes.is(":checked"));
});
You'll need to iterate through all your checkboxes on each click. Also, I would recommend using the prop function to check for the "checked" status. Then, to hide it, either use the hide function, or set the display property to hidden:
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});

Conditional validation for a form inputs

Starting off there is a append button that generates a row with 1 select box, 1 inputbox, and 4 checkboxes. The limit of adding this would be 1-10 rows at max. I have no idea how to make a jquery validation using for example http://formvalidation.io/ - or a standalone jquery code. The rules I would like to apply:
If the role chosen is user (not an admin) , I must validate that there is at least one checkbox checked and the user doesn't appears twice in the selections
The thing is I don't even know where to start from, can you point me any hints?
Live example :: http://jsfiddle.net/Yy2gB/131/
Append method onClick
$(document).ready(function(){
var obj = {"1":"Admin istrator","2":"User2"};
//$('.selectpicker').selectpicker();
$(".addCF").click(function(){
count = $('#customFields tr').length + 1;
var sel = $('<select name="user'+count+'">');
for(key in obj){
// The key is key
// The value is obj[key]
sel.append($("<option>").attr('value',key).text(obj[key]));
}
$('.selectpicker').selectpicker();
$("#customFields").append('<tr><td>'+sel[0].outerHTML
+'</td><td><input class="form-control" class="valid_role"'
+' data-fv-field="emails" type="text" name="role'+count
+'" /></td><td><input type="checkbox" class="mycheckbox"'
+' name="can_edit'+count+'"></td><td><input type="checkbox" '
+'class="mycheckbox" name="can_read'+count+'"></td><td><input '
+'type="checkbox" class="mycheckbox" name="can_execute'+count+'">'
+'</td><td><input type="checkbox" class="mycheckbox" '
+'name="is_admin'+count+'"></td><td><a href="javascript:void(0);"'
+'class="remCF">Remove</a></td></tr>');
$('.mycheckbox').iCheck({
checkboxClass: 'icheckbox_square-blue',
radioClass: 'iradio_square-blue'
});
$('.selectpicker').selectpicker();
});
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
});
HTML Form
<div class="col-md-12 col-lg-12">
<table class="table table-user-information" id="customFields">
<thead>
<tr>
<th class="standardTable_Header">User</th>
<th class="standardTable_Header">Role</th>
<th class="standardTable_Header">
<span title="administrator projektu">Can read</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
edit
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do odczytu danych projektu oraz przypisanych do niego zadań">
excute
</span>
</th>
<th class="standardTable_Header">
<span title="uprawnienie do edycji danych projektu">
admin
</span>
</th>
</tr>
</thead>
<tbody>
<button type="button" class="btn btn-default addCF">
Append
</button>
</div>
</tbody>
</table>
Using this jQuery Validation Plugin and through this demo, We could do the following:
Assumption: Roles check boxes must have at least one checked if - and only if - the select tag have the value User2
1- wrap your table with form tag that has a submit button:
<div class="col-md-12 col-lg-12">
<form id="myform">
<table class="table table-user-information" id="customFields">
...
</table>
<input type="submit" value="submit" />
</form>
</div>
2- We need to edit the checkboxes html to make them all have the same name but with different values, for example:
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_edit' ...>
<input type="checkbox" class="mycheckbox" name="ourRoles" value="can_read' ...>
and so on.
3- Add the following script:
// just for the demos, avoids form submit
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
$("#myform").validate({
rules: {
ourRoles: {
required: function () {
if ($("select[name=user2]").val() == 2) {
return true;
} else {
return false;
}
}
}
}
});
See all together with this fiddle

Trying to serialize a form with dynamically created input elements, but values of elements aren't posted

I am dynamically adding elements. However when I try and serialize the form, none of the dynamically generated elements are serialized.
This is the function I'm using to add elements to the page :
function addObjects(IDname,classname)
{
//to add more objects
var number;
switch(classname)
{
case "name":
number = no_Name++;
break;
case "part":
number = no_part++;
break;
}
var id = classname + number;
$("#"+IDname).append('<tr class="'+id+'"><td><input id="'+id+'" class="'+id+'" type="text"> <button class="'+id+'" onclick=removeAdditions("'+id+'")>x</button></td></tr>');
}
The page looks like this:
<html>
<head>
<script src="Controller.js" type="text/javascript"></script>
<script type="text/javascript" src="https://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//in order to prevent form reload when button click occurs
$(document).ready(function(){
document.getElementById("ReportForm").onsubmit = function (event) { event.preventDefault(); }
});
</script>
</head>
<body>
<div class="detailsPane" id="detailsPane1" >
<form id="ReportForm" name="ReportForm" >
<table style="width: 100%;">
<tbody>
<tr>
<td>
1. Describe the Status briefly-
</td>
<td>
<textarea id="StatDescp" name="StatDescp"></textarea>
</td>
</tr>
</tbody>
</table>
<br>
<table style="width: 100%;">
<thead>
<tr>
<th colspan="4" align="top">
Part Status
</th>
</tr>
</thead>
<tbody>
<tr>
<td style="vertical-align:top;">
Part Name:
</td>
<td style="vertical-align:top;">
<table >
<tbody id="PartName">
<tr class="partname0">
<td><input class="part_name" type="text"> <button onclick='addObjects("PartName","part_name");'>+</button></td>
</tr>
</tbody>
</table>
</td>
<tbody>
</table>
</form>
</div>
<div id="buttonDiv" >
<a class="bottomLeftResultDiv" id="messageBox"></a>
<input type="button" id="saveButton" value="Save" style="width:85px" onclick="save();" />
</div>
</body>
</html>
And finally here is the save Button.
function save() {
var select = document.getElementById('newReportPane');
var contents = $('#ReportForm').serialize();
contents = contents.replace(/=on/g, "=checked");
contents = contents.replace(/\+/g, " ");
$("#messageBox").html("Saving report...");
console.log(contents);
$.post("/Report/Report1", { action: "save", content: contents }, function (data) {
if (data != "ACK")
$("#messageBox").html("Unable to save.");
else
$("#messageBox").html("Report saved successfully");
});
}
When I click on the save button, it only posts this StatDescp= without any of the dynamically generated elements.
I really can't figure out why.
Any help would be appreciated.
Give a name= attribute to each of your added inputs.
From http://api.jquery.com/serialize/
For a form element's value to be included in the serialized string,
the element must have a name attribute.

Categories

Resources