I have this code
var users = result.users; // array
$("#dialog:ui-dialog").dialog("destroy");
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
open: function() {
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
},
buttons: {
"Okay": function() {
$(this).dialog("close");
},
Cancel: function() {
is_okay = 0;
$(this).dialog("close");
}
}
});
where the array contain data in the form of
{"ss":"Sandra Schlichting","fn":"Full name"}
What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)
<table>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
<tr> <td>ss </td> <td>Sandra Schlichting</td> </tr>
<tr> <td>fn </td> <td>Full name </td> </tr>
</table>
and have that replaced with <b>New text goes here</b> in
$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
From what I can tell $.each() should be used for this.
But still I can't quite figure out how to get started.
Can anyone help me out?
You can use a JS for-in to loop through it.
<table id='nameTable'>
<tr> <td>Initials</td> <td>Full Name </td> </tr>
</table>
var names = {
"ss": "Sandra Schlichting",
"fn": "Full name"
};
var $table = $('#nameTable');
var row = '';
for (name in names) {
row += '<tr><td>' + name + '</td><td>' + names[name] + '</td></tr>';
}
$table.append(row)
Here's a fiddle : http://jsfiddle.net/exP2b/4/
function makeTable(users) {
var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
$.each(users, function(index, value) {
result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
});
result += '</table>';
return (result);
}
alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));
Working here
$.each documentation
Related
I'm having this issue with my datetimepicker that stops working after appending an html table.
I have a button that opens a dialog. This contains fields to enter and when clicking Save it adds the values as a record to an html table.
That works fine, however, when opening the dialog again, the datetimepicker buttons don't work anymore.
The dialog form has multiple datetimepickers, however, I simplified an example of the issue.
Please see my jsfiddle below for an example.
$(".datepicker").datepicker({
dateFormat: "yy-mm-dd", timeFormat: "HH:mm", hourMin: 0, hourMax: 24, stepMinute: 10
});
var dialog;
dialog = $("#addnewDialog").dialog({
autoOpen: false,
height: 250,
width: 350,
modal: true,
buttons: {
"Save": addnewrec,
Cancel: function () {
dialog.dialog("close");
}
},
open : function() {
},
close: function () {
}
});
$("#AddNew").button().on("click", function () {
dialog.dialog("open");
});
function addnewrec() {
var valid = true;
var dealerref = $('#tblInput').find('#DealerRef').val();
var dtCreated = $('#tblInput').find('#DTCreated').val();
if (valid) {
var td1 = '<td id=DealerRef>' + dealerref + '</td>';
var td2 = '<td id=DTCreated>' + dtCreated + '</td>';
$("#tblStyle tbody").append("<tr><td></td>" +
td1 + td2 + "</tr>");
dialog.dialog("close");
}
return valid;
}
JSFiddle
This is beacause you're genrating in the table td's with the same id as your datepicker id , so it works first time then after appending td into the table , the select on timepicker will throw an error due to duplicate id items
Also know that in an HTML page you should always use ID for one and only one element otherwise use classes .
You can fix this last by generating changine timepicker id or genrate other id's for td's by incrementation for example :
See this Fiddle
Snippet :
$(function () {
$(".datepicker").datepicker({
dateFormat: "yy-mm-dd", timeFormat: "HH:mm", hourMin: 0, hourMax: 24, stepMinute: 10
});
var increment = 0;
var dialog;
dialog = $("#addnewDialog").dialog({
autoOpen: false,
height: 250,
width: 350,
modal: true,
buttons: {
"Save": addnewrec,
Cancel: function () {
dialog.dialog("close");
}
},
open : function() {
},
close: function () {
}
});
$("#AddNew").button().on("click", function () {
dialog.dialog("open");
});
function addnewrec() {
var valid = true;
var dealerref = $('#tblInput').find('#DealerRef').val();
var dtCreated = $('#tblInput').find('#DTCreated').val();
if (valid) {
increment++;
var td1 = '<td id=DealerRef'+increment+'>' + dealerref + '</td>';
var td2 = '<td id=DTCreated'+increment+'>' + dtCreated + '</td>';
$("#tblStyle tbody").append("<tr><td></td>" +
td1 + td2 + "</tr>");
dialog.dialog("close");
}
return valid;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<input id="AddNew" type="button" value="Add New Activity" class="btn btn-default" />
<br /><br />
<div id="addnewDialog" title="Add New Activity">
<table id="tblInput">
<tbody>
<tr>
<td>
DealerRef
</td>
<td>
<input id="DealerRef" name="DealerRef" type="text" value="">
</td>
</tr>
<tr>
<td>
DTCreated
</td>
<td>
<input class="datepicker" id="DTCreated" name="DTCreated" type="text" value="">
</td>
</tr>
</tbody>
</table>
</div>
<table id="tblStyle">
<thead>
<tr>
<th>DealerRef</th>
<th>DTCreated</th>
</tr>
</thead>
<tbody></tbody>
</table>
I have a html table with 4 columns and multiple rows
column1 : simple text
column2 : simple text
column3 : select list with 2 values
column4 : Button that performs some operation
At run time, I want to get the selected / entered values for all the columns of that row against which column4 button is clicked. I know a little of JavaScript/jQuery.
Here is the static table code
<table id="invoiceTbl" border="1">
<thead>
<tr>
<th>Broker info</th>
<th>Receivable Amount</th>
<<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody></tbody>
</table>
And I am populating table i.e. inserting data on AJAX call like this:
$.ajax({
type: "POST",
data: $('#searchDetails').serialize(),
async: false,
cache: false,
url: "/opsadmin/search.json",
dataType: 'json',
success: function (result) {
var i = 1;
$.each(result, function (index, value) {
alert(index + ": " + value.brokerInfo);
$('table#invoiceTbl TBODY').append('<tr> <td>' + i + '</td><td>' + value.brokerInfo + '</td><td>' + value.receivableAmount + '</td><td><select name="act" id="s"><option>PENDING</option><option>CLEARED</option></select></td><td><input type="button" value="Process" onclick="updateStatus(\'' + index + '\')"</input></td></tr>');
i++;
});
}
});
return false;
First set the unique ID to each of your "select" with help of index like:
'<select name="act" id="s'+ index +'">'
and pass the index with "updateStatus(index)" function call.
function updateStatus(index) {
$('#s'+index).val(); // value of selected box.
}
$("#invoiceTbl input[type=button]").click(function(e){
$(e.target).closest("tr").find("td").slice(0,2).each(function(){
console.log($(this).text());
});
});
On #button click you will get an array (arr) that holds the values of the clicked row cells:
$('#button').on('click', function() {
var arr = [];
$(this).closest('tr').find('td').each(function() {
var that = $(this);
if (that.find('input[type="text"]').length > 0) {
arr.push(that.find('input[type="text"]').val());
} else if (that.find('select').length > 0) {
arr.push(that.find('select').val());
} else {
arr.push(that.text());
}
});
alert(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>text</td>
<td>text2</td>
<td>
<select>
<option value="opt1">opt1</option>
<option value="opt2">opt2</option>
<option value="opt3">opt3</option>
</select>
</td>
<td><button id="button">Click</button></td>
</tr>
</tbody>
</table>
There's already a few good answers, but my solution is a bit different:
$("#invoiceTbl tr").each(function(){
var select = $(this).find("select");
var button = $(this).find("button");
button.click(function(){
alert(select.val());
});
});
If you also want the content of the other columns, that's a bit more difficult:
$("#invoiceTbl tr").each(function(){
var tr = $(this);
var button = $(this).find("button");
button.click(function(){
tr.find("td").each(function(){
var select = $(this).find("select");
var td_button = $(this).find("button");
if(!td_button.length)
{
if(select.length)
console.log(select.val());
else
console.log($(this).text());
}
});
});
});
Check out https://jsfiddle.net/cgfjewoe/ to see it run.
I am creating a table at run time using Jquery and binding the unique id to the checkbox.
$.getJSON('/api/Test/SelectionList' + '/' + ID)
.done(function (data) {
$.each(data, function (key, val) {
var myRow = $("<tr/>");
//$("<td> <input type='checkbox' ></input> </td>").text(val.IsActive).appendTo($(myRow));
var items = "";
items += '<input type="checkbox" id=' + val.FacilityID + ' ';
if (val.IsSelected) {
items += 'checked/>';
}
else {
items += '/>';
}
//$("<td/>").text(val.IsActive).appendTo($(myRow));
$("<td> " + items + "</td>").appendTo($(myRow));
$("<td/>").text(val.Facilityname).appendTo($(myRow));
$("<td/>").text(val.RegionName).appendTo($(myRow));
$("<td/>").appendTo($(myRow));
myRow.appendTo($("#Table"));
});
})
User can check and uncheck the checkboxex, On click of save i want to store the value of (table) all check boxex with checked/unchecked state with the ID.
I want to loop through the full table, and store the data as id#1 for checked box and id#0 for unchecked box in a same array.
I am bit new to jquery, So not getting the syntax. Please suggest.
Updated, here is the fiddle http://jsfiddle.net/MQQSv/1/
<table>
<tr>
<td>one</td>
<td>
<input type="checkbox" id='1' checked/></td>
</tr>
<tr>
<td>two</td>
<td>
<input type="checkbox" id='2' /></td>
</tr>
</table>
$('#save-btn').on('click', function() {
var output = []
$("table td input[type=checkbox]").each(function(){
id = $(this).attr("id");
output.push( id + "#" + ($(this).is(":checked") ? "1" : "0"))
})
console.log(JSON.stringify(output));
})
you can try this :
push id into two different array
$(document).ready(function() {
// bind click event to save-btn
$('#save-btn').on('click', function() {
// init two array
// (if you want to use var out of on's callback function, you need to do declaration outside)
var checkedList = [],
uncheckedList = [];
// push ckecked id into checkedList
$('input:checked').each(function() {
checkedList.push($(this).attr('id'));
});
// push unckecked id into uncheckedList
$('input').not(':checked').each(function() {
uncheckedList.push($(this).attr('id'));
});
});
});
I am trying to following the example here and create a popover table row. When I just copy the code it works like a charm. But in the table where I want the popup to work it fails.
I have the following JavaScript code (same as Fiddle):
// Popover
var options = { placement: 'bottom', trigger: 'manual', html: true, title: 'This row' };
function createPopover(element, args) {
var href = $(element).data('popover-url'), txt = $(element).data('popover-content');
var html = '<p>Challenge: Can you click the link in a popover?</p><p><a href="' + href
+ '">' + txt + '</a></p>';
$(element).data('content', html).popover(args);
}
function popoverPlacementBottom() {
createPopover($(this), options);
}
$('.row').each(popoverPlacementBottom);
var insidePopover = false;
function attachEvents(tr) {
$('.popover').on('mouseenter', function () {
insidePopover = true;
});
$('.popover').on('mouseleave', function () {
insidePopover = false;
$(tr).popover('hide');
});
}
$('table').on('mouseenter', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) {
$(tr).popover('show');
attachEvents(tr);
}
}, 200);
});
$('table').on('mouseleave', 'tr', function () {
var tr = $(this);
setTimeout(function () {
if (!insidePopover) $(tr).popover('hide');
}, 200);
});
and try to have popovers on this table:
<table class="table table-condensed scrollable popup">
<thead>
<tbody id="logEvents">
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-
original-title="" title="">
<td class="col-md-1">18:27</td>
<td class="col-md-5">InfoService</td>
<td>Blabla...</td>
</tr>
</tbody>
</table>
This however, does not work. While it does work at the table underneath which looks like this:
<table class="popup">
<tbody>
<tr class="row" data-popover-url="#url_for_row_1" data-popover-content="line 1" data-original- title="" title="">
<td>the first line</td>
</tr>
</tbody>
</table>
Why does it not work at the table where it should work? I hope someone can help me out.
/EDIT Okay I made my own Fiddle HERE.
Strangely enough the code works in the Fiddle. But on my webpage it does not. The only difference with the Fiddle is that the tr rows are dynamically generated everytime an event happens by the function:
return "<tr " + trClass + " data-popover-content='line 1' data-popover-url='#url_for_row_1'>"
+ "<td class='col-md-1'>" + time + "</td>"
+ "<td class='col-md-5'>" + item.Source + "</td>"
+ "<td>" + item.DescriptionShort + "</td>"
// + "<td class='col-md-6'>" + "<a id='pop' data-content='test' data-
toggle='popover'>" + item.DescriptionShort + "</a></td>"
+ "</tr>";
Could this have anything to do with it? (e.g., that the id's and classes come after the document-ready? And that I need to reassign the classes every time a new event happens? And if so, how?
Okay the problem was in the generated code! The <tr>'s were generated everytime an event happened and so I should not assign the popover event only at document ready, but also everytime a new row was created.
I put the popover() function in his own pop namespace, and added the pop.popOver() after the new event made a new row. Looked as follows:
this.addData = function (item) {
var container = $(this.cId);
container.append(this.getEventHtml(item));
pop.popOver();
}
Now the popups show! YEAH! Thanks to Suman Bogati for his help.
I have a JSON value that has multiple values separated by a comma. Is there a way to have that rendered in the dom as a selection dropdown input?
Here is a more detailed view of my markup.
HTML
<h1>JSON Grid Edit</h1>
<table cellpadding="0" cellspacing="0" border="0" class="dt display" id="json-table-edit" contenteditable="true" onKeyUp="editValue(this.id);">
<thead>
<tr>
<th width="25%">Setting</th>
<th width="75%">Value</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
<tr>
<th>Setting</th>
<th>Value</th>
</tr>
</tfoot>
</table>
JSON
{
"allconfig": {
"card.inserted": {
"value": "Inserted, Not Inserted",
},
"card.cisproc": {
"value": "Processed",
}
}
}
JQUERY
$.getJSON('json/ione-edit.json', function (data) {
var newJson = [];
var myJson = data;
$.each(myJson.allconfig, function (key, value) {
var rowArray = [];
rowArray.push(key);
$.each(myJson.allconfig[key], function (key1, value1) {
rowArray.push(value1);
});
newJson.push(rowArray);
});
$('#json-table-edit').dataTable({
"bJQueryUI": true,
"bStateSave": true,
"sPaginationType": "full_numbers",
"bProcessing": true,
"oLanguage": {
"sLengthMenu": ' <select>' + '<option value="10" selected="selected">Filter</option>' + '<option value="10">10</option>' + '<option value="20">20</option>' + '<option value="30">30</option>' + '<option value="40">40</option>' + '<option value="50">50</option>' + '<option value="-1">All</option>' + '</select>'
},
"aaData": newJson
});
This is possible using the split() method. split(",") will give you an array of separate strings for each coma separated entity. You can then use the jQuery .each() method to iterate over the array and append each string to the DOM wrapped in <option> tags.
something like this:
var data = {
"allconfig": {
"card.inserted": {
"value": "Inserted, Not Inserted",
},
"card.cisproc": {
"value": "Processed",
}
}
}
var options = (data.allconfig["card.inserted"]["value"]).split(",");
$("body").append("<select id='select'></select>");
//I am appending this to the body, but you can change body to
// whatever element/class/id you want
$(options).each(function() {
$("#select").append("<option>"+this+"</option>");
});
//I have also given the select an id so this code can be used on pages that have multiple select elements
here is a fiddle
One way would be to use the plain Javascript method .split().
You'll need to split the value string, which will then turn the comma-seperated string into an array. Then you'll need to run over the array to make your select dropdown.
Something like this inside of your JSON return function (not exactly these variable names, just an example to show you the idea):
$('#SelectContainer').html('<select name="mySelect">');
var options = value.split(',');
for (counter=0; counter < options.length; counter++)
{
$('#SelectContainer').append('<option value="' + options[counter] + '">' + options[counter] + '</option>');
}
$('#SelectContainer').append('</select>');