Dynamically generated Radio button from json data - html

I am developing an application for selecting the PASS/FAIL option for the value generated from the json data.
My problem is that I am not able to select value per row.The selected value applies in all rows.
HTML:
<table id="records" cellspacing="0">
JQUERY:
(function () {
var url = "http://www.filltext.com/?callback=?";
$.getJSON(url, {
'rows': 5,
'fname': '{firstName}',
'lname': '{lastName}',
'tel': '{phone|format}',
})
.done(function (data) {
$.ajaxSetup({
cache: false
});
var t;
$.each(data, function (i, item) {
var html =
"<td>" + item.fname + "</td>" +
"<td>" + item.lname + "</td>" +
"<td>" + item.tel + "</td>" +
"<td><input type='text' name='PASS' placeholder='" + i + "' /></td>" +
"<td><input type='radio' value='Pass' name='PASS'/>PASS</td>" +
"<td><input type='radio' value='Fail' name='PASS'/>FAIL</td>";
$("<tr/> </table>").html(html).appendTo("#records");
});
$('input[name="PASS"]').on('change', function () {
$('input[type="text"]').val($(this).val());
});
});
})();
JSFIDDLE: http://jsfiddle.net/rutvij111/hUAWF/

working fiddle
first you need to add the same name only to the two radiobuttons that you want to associate (pass and fail) for each row
something like this:
"<td><input type='radio' value='Pass' name='PASS" + i + "'/>PASS</td>"+
"<td><input type='radio' value='Fail' name='PASS" + i + "'/>FAIL</td>";
then assign the change handler to the radio buttons using the type instead of the name
$('input[type="radio"]').on('change', function() { });
and get to the parent tr and look for the input[type=text] from there
$(this).parent().parent().find('input[type=text]').val($(this).val());

That's because you assign the same name="PASS" to every radio button. You ought to select a different one for each row. You could number it like name = "PASS1" or so. Demo for recommended method:
http://jsfiddle.net/hUAWF/7/
Alternatively you could only update a single row if it's only for showing the data (and not writing it) by selecting a children of that row:
$('input[name="PASS"]').
on('change', function() {
$(this).
parents("tr").
find('input[type="text"]').
val($(this).val());
Demo for easy alternative:
http://jsfiddle.net/hUAWF/4/

This is not the optimal solution , but it is working
(function() {
var url = "http://www.filltext.com/?callback=?";
$.getJSON( url, {
'rows': 5,
'fname': '{firstName}',
'lname': '{lastName}',
'tel': '{phone|format}',
})
.done(function( data ) {
$.ajaxSetup ({ cache: false});
var t;
$.each( data, function( i, item ) {
var html =
"<td>" + item.fname + "</td>" +
"<td>" + item.lname + "</td>" +
"<td>" + item.tel + "</td>" +
"<td><input id="+i+" type='text' name='PASS' placeholder='"+i+"' /></td>" +
"<td><input id="+i+" type='radio' value='Pass' name='PASS'/>PASS</td>"+
"<td><input id="+i+" type='radio' value='Fail' name='PASS'/>FAIL</td>";
$("<tr/> </table>").html(html).appendTo("#records");
});
$('input[name="PASS"]').on('change', function() {
var id= $(this).attr('id');
$('input[type="text"]#'+id).val($(this).val());
});
});
})();

Working DEMO
Try this,
The problem was since you have specified $('input[type="text"]')it will select all input of type text, so all the textboxes' value will be effected, However the code below gets the corresponding textbox in the same row of the clicked radio button.
$('input[name="PASS"]').on('change', function() {
$(this).parents('tr').find('input[type="text"]').val($(this).val());
});
Hope this helps, thank you

Related

Is there a good package/library to add Pagination/Sorting/Searching to my table? ASP.NET Core

I am new to web development in ASP.NET Core. I have a table with information, I would like to add pagination/sorting/searching to the table. Is there an easy way to add this using some sort of library/package? Thanks
I need pagination, sorting, and searching for my ASP.NET Core table.
I would like to add pagination/sorting/searching to the table. Is
there an easy way to add this using some sort of library/package?
Well, considering all the requirement you can go for jquery data table regardless of simplicity, quick implementation and free subscription. Importantly, its light weight and easy to use.
Here is the compplete example how you can implement that:
Controller:
[HttpGet]
public IActionResult ConAction()
{
var controlleractionlist = _context.Controller.ToList();
return Json(controlleractionlist);
}
Note: I am returning a simple list to demonstrate you , sorting, searching and paging functionality.
View:
<table id="userTable_info" >
<thead>
<tr>
<th>action </th>
<th>controller </th>
<th>returnType</th>
<th>Action</th>
</tr>
</thead>
<tbody id="tBody"> </tbody>
</table>
#section scripts {
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/css/jquery.dataTables.css">
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.4/jquery.dataTables.min.js"></script>
<script>
//Button Click Functions
function DetailsFunc(data) {
alert("User Id:" + data + " Details!");
}
function EditFunc(data) {
alert("User Id:" + data + " will be Edited!");
}
function DeleteFunc(data) {
alert("User Id:" + data + " will be deleted!");
}
//On Load
$(document).ready(function () {
$.ajax({
type: "GET",
url: 'http://localhost:5094/Home/ConAction',
dataType: "json",
contentType: "application/json",
success: function (response) {
console.log(response);
var id = 0;
$.each(response, function (index, value) {
id++;
console.log(id);
var tr = "<tr>";
tr += "<td>" + value.action + "</td>";
tr += "<td>" + value.controller + "</td>";
tr += "<td>" + value.returnType + "</td>";
tr += "<td>" + "<input type='button' id='" + id + "' class='btn btn-info' onclick='DetailsFunc(" + value.id + ")' value='Details'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-warning' onclick='EditFunc(" + value.id + ")' value='Edit'>" + " " + "<input type='button' id='" + value.id + "' class='btn btn-danger' onclick='DeleteFunc(" + value.id + ")' value='Delete'>" + "</td>" + "</tr>";
$("#tBody").append(tr);
});
$("#userTable_info").DataTable();
}
});
});
</script>
}
Output:
You could refer to official document for more details.

ASP.NET Json doesn't appear

Please refer to this link
http://aspsolution.net/Code/5/5215/How-to-loop-through-ViewBag-List-in-Jquery/#
I followed what is written in the website. However the Json.Result doesn't appear. I tried to include this one (#using Newtonsoft.Json) in the html but it's still not appearing. Why is that? Is there any solution for this?
This is my script:
fillDatatable();
function fillDatatable() {
var cart = #Html.Raw(Json.Result(#ViewBag.cart));
alert(cart.Items.ItemID);
}
Edited:
if (PurchaseOrder != "") {
var tableHTML = '';
$.each(PurchaseOrder, function (index, value) {
tableHTML += "<tr>";
tableHTML += "<td>" + value.items.itemID + "</td>";
tableHTML += "<td>" + value.items.itemModelDescription + "</td>";
tableHTML += "<td>";
tableHTML += "<input id='UnitPrice" + value.items.ItemID + "' class='form-control b-r-xl text-right' value='" + value.items.itemUnitPrice + "' oninput='return change_unitprice('" + value.items.itemID + "')' />";
tableHTML += "</td>";
tableHTML += "<td>";
tableHTML += " </tr>";
});
$("#TableRecords").html(tableHTML);
}
See my HTML inside the loop where you can see change_unitprice function. I'm trying to pass the value of an id there, but according to the result of console it is undefined? Why is that?
The example you are referencing does not contain the code you included to the question. It describes how to use Json.Encode() to obtain data from the ViewBag field. Possible problems why your code doesn't work are:
Using not defined the cart field.
Using the Items property that does not defined.
Trying to work with HTML document that does not loaded yet.
Therefore, use function from this example as is:
<script>
$(document).ready(function(){
var StockList =#Html.Raw(Json.Encode(#ViewBag.StockList));
if (StockList != '') {
var tableHtml;
$.each(StockList, function( index, value ) {
tableHtml +="<tr><td>" + value.stockId + "</td><td>" + value.StockName + "</td><td>" + value.StockPrice + "</td></tr>";
});
$("#output").html(tableHtml);
}
})
</script>
If it does not work (probably because of the jquery disable by Layout = null; line in the Index.cshtml ) add the following line after the <head> tag:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
For additional information see the following post: https://stackoverflow.com/a/10779161/6630084
I think the simplest method that works for complex object would be like this:
#Html.Raw(Json.Encode(ViewBag.cart))

HTML Table data will disappear after page refresh

I am using a web service to get data from MySQL database and show them in a HTML Table. And it is working data will appear in the table. But when I reload the page Table data will disappear. How can I fix that? How can I keep data even page reloaded?
HTML
<body>
<button id="btnSearch">Search</button>
<table id="tab">
</table>
</body>
And the following JS.
<script type="text/javascript">
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>
<script type="text/javascript">
$( document ).ready(function() {
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
$("#btnSearch").click(function()
{
$.getJSON("http://localhost:8080/Service/Rest/cart/get/cart",function(data)
{
var tb = $("#tab");
$.each(data,function(i,value)
{
tb.append("<tr><td>Product Name: " + value.name + "</td><td>Price: " + value.price + " </td><td>Description: " + value.description + "</td></tr>");
});
});
});
</script>
I have another solution for this, create a dummy table data with null value, and store your value in browser session and then replace all the null value on runtime through jquery/javascript.
Hope this helps.

remove span by class from $(this).html()

Basically my search returns search results in spans, then when one is clicked, a new span is added to another div with a select input and hidden input so all the selected features can be posted as an array.
My question is, $(this).html() now includes a span of class alias_span. Which I don't want to appear in the new span. How do I remove it before inserting the contents of the clicked span into the new span
$(".minisearch_res").live('click', function() {
// when a search result is clicked we disable the submit button,
// append a span to the left column with an id,
// a select input to select standard/optional and
// a hidden field with the required information to save and something to
// show the user
var id = $(this).attr('id');
var html = "<span class= \"added_result_cont\" id=\"" + id + "_cont\">";
html += "<select name='" + id + "_sel'>";
html += "<option value=\"none\" selected=\"selected\"></option>";
html += "<option value=\"std\">Standard</option>";
html += "<option value=\"opt\" >Optional</option>";
html += "</select>";
html += "<span id= \"" + id + "\" class=\"added_result\">";
html += "<input type=\"hidden\" name=\"selectedfeat[]\" value=\"" + id + "\">";
html += $(this).html() + "</span></span>";
$('#div_apply_to').append(html);
$(this).remove();
$('#search_input').trigger('keyup');
$("input[type=submit]").attr("disabled", "disabled");
});
Update: here's the html of the span
<span class="minisearch_res" id="opt_1">Anti-Lock Brakes<br><span style="padding-left:20px" class="alias_span"><i>abs</i></span><br></span>
<div></div>
Add it to the dom, then remove it.
var htm = (
'<span class="foo">foo</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>' +
'<span>bar</span>'
);
var $el = $("div").append(htm);
console.log($el.html());
$el.find('.foo').remove();
console.log($el.html());
http://jsfiddle.net/chovy/w2HdE/
Got a tidy cross browser solution, which I'm very proud of :)
var temp = $(this);
temp.children('.alias_span').remove();
$('#div_apply_to').append("...html..." + temp.html() + "...html...");
inspiration came from here:
Remove element from Ajax Response

Auto select the check box in rows

I am displaying table rows in the form. Each row has 5 columns, one of the columns is an (editable) textbox field.
ajaxLoading(true);
$.post('<%=request.getContextPath()%>'+"/processServlet", postData,
function(data) {
var ctxPath='<%=request.getContextPath()%>';
currentPosition = data.currentPosition;
var items = $("#itemsTable");
items.empty();
if (data.items.length == 0) {
items.append($('<tr><td colspan=5 style="color:red;">No items<td></tr>'));
}
;
for (var i = 0; i < data.items.length; i++) {
editText = "";
items.append($("<tr " + zebra + "><td><a href=\"javascript: deviceView('" + data.items[i].id + "')\">" + data.items[i].num +
"</a></td><td>" + data.items[i].itemType +
"</td><td><input type = 'checkbox' id = 'CheckBoxRow_' />" + data.items[i] +
"</td><td><input type = 'textbox' id = 'TextBoxRow_' value = '" + data.items[i].itemName +"' "/>" +
"</td><td>" + data.items[i].status +
"</td><td>" + data.items[i].date + "</td>" +
"<td>" + data.items[i].firmware + "<td>" +
"Delete" +
"</tr>"));
;
ajaxLoading(false);
}, "json");
How do I auto select the check box when the data is entered or modified in the textbox and save the data in the database?
bind to textbox onchange event and have it set the checkbox to checked=true once returned with a value (and not already checked).
$('#itemsTable input[type="checkbox"]').change(function(e){
var $cb = $(this);
if ($cb.is(':checked')){
$cb.closest('tr').find('input[type="checkbox"][id^=CheckBoxRow_]').prop('checked','true');
}
});
basically. though you really should not use HTML in an append, and should be building the objects with jQuery.