Storing and accessing data of a div inside a table cell - jquery-ui

http://fiddle.jshell.net/kBFU7/2/
In the code, I have created a dynamic table through jQuery.
I also have a div for each table cell.
I wish to store and access data of this div, eg, the row and column for each of it.
I would hence like to ask for some recommendations on how I should go about storing this data.
I have tried creating a span for each div to store info in it following the suggestions from this link http://time2hack.blogspot.sg/2012/11/jquery-store-access-relative-info-within-HTML-element.html#axzz2Ee3iLxCt but it did not seem appropriate and I have failed at accessing back the info.
I would appreciate it if someone could just give me some recommendations which I could try out.

So basically you want to create a dynamic table and access each of the TDs and its data.
In order to do that, you don't need any div or span to place inside those TDs to access their content (if that is all that you want). The simplest way to do so is to assign an id to each of these TDs according to their Row and Column position. That way you can access each of them in a loop or directly or what not.
below I've written a super simple way to achieve it. Of course you can customize or enhance it according to your need. but then you should get the idea right?
(I am using ur code to do that)
$(document).ready(function() {
createTable($("#tb1"));
function createTable(tbody){
if (tbody == null || tbody.length < 1) return;
for(var r=0;r<5;r++){
var trow=$("<tr>");
for(var c=0; c<5;c++){
var tcol=$("<td>")
tcol.attr("id","row"+r+"col"+c); /// assign id to each td
var cellText = "row " +r + " col " +c
$("<div>")
.text(cellText)
.appendTo(tcol)
tcol
.appendTo(trow)
}
trow.appendTo(tbody);
}
}
});
so basically you did this:
<td id="row1col1"></td>
<td id="row1col2" ></td>
now whenever you want to access any of the cells do this
$('#row1col1').text();
or
$('#row1col1').html();
​
you can access the cells in a loop like
for(var r=0;r<5;r++){
for(var c=0;c<5;c++){
var cellValue= $('#row'+r+"col"+c).text() // or .html()
makeAjaxRequest(cellValue); /// send to server or whatever
}
}

when create a div add an unique id:
.attr("id","cell-" + r+ "-" + c)
try this code on a button with input:
$("#btn").bind("click", function(){
var r = $('#row').val();
var c = $('#column').val();
var data = $('#data').val();
$('#cell-' + r + '-' + c).text(data);
});
Try it on my fiddle:
http://jsfiddle.net/kBFU7/4/

you'll have to pass this value as array and have to receive it on back-end
go on this link
http://www.aspdotnet-suresh.com/2012/07/aspnet-save-dynamically-created-control.html

To access the data attributes in the elements; there can be two ways. the jQuery access that data by
$('#table_cell_div').data('info');
But this function only works if the DOM is created before
$(document).ready();
i.e the document elements created by JS are not accessible in data() function of jQuery
But to access those elements and attributes after the DOM has become ready; you can access that data by following code
$('#table_cell_div').attr('data-info');

Related

How to perform actions on tables row in JQuery mobile

I have a table which displays results like the image posted below. Now I need to do some actions on each row by selecting it. There are two options I can think of,
1) We can provide a radio button for each row & a drop down on the right side to perform an action. But here i need to generate this code dynamically from a javascript file like below
function getMessage(result){
for (var j = 0; j < result.invocationResult.resultSet.length; j++) {
var tmp = "<tr>";
var resSet = result.invocationResult.resultSet[j];
for(res in resSet){
tmp += "<td>" + resSet[res] + "</td>";
}
$("#mytable > tbody").append(tmp+"</tr>");
$('#AppBody').hide();
$('#AuthBody').hide();
$('#ResTable').show();
}
}
2) Provide a link to a particular item in the row like Dispute Number & when clicked it should take me to another page where I can perform those action with a drop down. But here the links should be applied dynamically to the items in the rows. As per my knowledge we should not navigate using href as i am using worklight.
Please help me with approach and also examples.
Thanks.
So I'm not sure what is the issue you are facing with option 1...
As for option 2,
There is no problem navigating to another "page" using Worklight and jQuery Mobile, as long as you're doing it responsibly (definitely not use href). That is, not lose the Worklight context, at which point stuff will stop working.
The idea is this:
In the app's index.html you (will/should) have a <div data-role="page"> and in the case of Worklight, you will need to switch its contents with another from some other HTML file.
Here's a simplified Worklight 6.2 sample project: https://github.com/IdanAdar/Multipage-Navigation-Using-jQM
In the HTML:
load page1
In the JavaScript:
function changeToSomePage() {
$(':mobile-pagecontainer').pagecontainer('change','somepage.html');
}

Is it possible to post a link that targets a specific choice in an accordeon so to open automatically?

I have a page that contains multiple topics in accordion.
How can I post a link (on social media or other places) so when the user clicks it can view the topic I want without making him choose the desired one to view it?
The website is built in Joomla 2.5 using its native (mootools) accordions.
A temporary solution came to my mind is to make single pages containing only the content I want, but it won't help them view the other topics contained in the same page, unless the user clicks the same category.
MooAccordion has a display option. You could use like:
window.addEvent('domready', function () {
var index = window.location.search; // get query string
index = index.replace("?", ''); // remove the ?
index = index.length ? index : 0; // in case there in no query, display first
var myAccordion = new Fx.Accordion($('accordion'), '#accordion h2', '#accordion .content', {
display: index // the actual behavior you are looking for
});
});
Read more at Mootools docs
So you could try these links as demo:
http://jsfiddle.net/brM2v/show/?0
http://jsfiddle.net/brM2v/show/?1
http://jsfiddle.net/brM2v/show/?2

Drag and drop of rows primefaces datatable/datagrid?

I trying to drag and drop of rows using primefaces datatable/datagrid.But this is issue in primefaces.What is best way to integrate drag and drop of primefaces datatable/datagrid with jquery or other third party api plugin.Please suggesst to me.
You need to add some JavaScript (JQuery) in your JSF page to make Datatable sortable and to disable selection mode. Listed below doReorder() method gets the new order of the rows and save to order_q variable:
<script type="text/javascript">
$(document).ready(function () {
$('.ui-datatable tbody').sortable();
$('.ui-datatable tbody').disableSelection();
});
function doReorder() {
var order = '';
var len = $('.row').length;
$('.row').each(function (index) {
order += ($(this).text() + ((index == (len - 1)) ? '' : ';'));
});
$('#order_q').val(order);
return true;
}
</script>
Add some code to your Datatable component. You see a new column with number of the row as value with attribute styleClass set to „row” . There is a hidden variable order_q updated during execution JavaScript method doReorder() :
<p:dataTable rowIndexVar="rowIndex"
var="entry" value="#{myBean.list}" >
<p:column headerText="#">
<h:outputText styleClass="row" value="#{rowIndex}"/>
</p:column>
... (other colums as you wish)
</p:dataTable>
<h:inputHidden id="order_q" value="#{myBean.order}"/>
<p:commandButton value="Submit order" ajax="false" onclick="return doReorder()" action="#{myBean.reorder}"/>
Your bean class should contain a String field order (with getters and setters of course). The variable wil store a value from the JavaScript – the new order of our list (source data of the Datatable widget). We need to implement also a method mentioned in the xhtml - reorder() to handle action from button „Submit order”
public String reorder() {
Map < String, String > tmp = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String order = tmp.get("order_q");
if (order != null && !order.isEmpty()) {
ArrayList < YourData > reordered = new ArrayList < > ();
for (String s: order.split(";")) {
try {
Integer i = Integer.parseInt(s);
YourData data = list.get(i);
reordered.add(data);
} catch (NumberFormatException nfe) {}
}
list = reordered;
}
return null;
}
That’s all! Now you can reorder your Datatable using drag&drop feature and save the new order by clicking a button. I leave a reference to my blog where all of this is described:
http://michalu.eu/wordpress/drag-and-drop-rows-to-reorder-your-datatable-in-primefaces/
Just use
<p:dataTable draggableRows="true"
On Primefaces 5.0 DataTable documentation you can see the parameter draggableRows, like this :
draggableRows | false | Boolean | When enabled, rows can be reordered using dragdrop.
http://www.primefaces.org/documentation
As far as i know from datatables (primefaces) in my applications, they have 2 main states/modes. It may be not the correct word but i stay with it. The 1st is display only, and 2nd editing.
(In display i dont see events triggering so DnD wont work.) in editing they have a serious issue with selectivity. u have to press at the edge of the table and not in inline components reach to get the focus on the row. So The drop must be done in that area and only propably for events to trigger. If u see the examples...all drops are made on an outer component(panel etc) and the table is just updated because the ondrop event in ajax has run and changed the data the drop table will contain. That may be magic for incrementing data...but not for rearranging and updating cell or row data.
SO the answer for that up to primefaces 3.5.x is i dont think you can achieve it...I dont think you can doit with jquery either because they run client side? i havent used them before so i cant tell for sure.
A bit of rework of your forms may be needed.

jquery-mobile create dynamic controlgroup and apply jquery-ui css [duplicate]

This question already has answers here:
Dynamic controlgroup and checkboxes unstyled
(6 answers)
Closed 8 years ago.
This is my code:
http://jsfiddle.net/YKvR3/34/
I would create a controlgroup with values that are in my array (name).
The problem is that when I click load button the values are added in a controlgroup but the jquery-ui styles are not loaded like in the image.
The controlgroup is not styled with jquery-ui mobile css.
$("#load").click(function(){
var name=["one","two"];
var html='<fieldset id="listPlayers" data-role="controlgroup"><legend><h1>Choose as many players as youd like to remove:</h1></legend>';
for ( var int = 0; int < 2; int++) {
html+='<input type="checkbox" name="checkbox-'+int+'a" id="checkbox-'+int+'a" class="custom" /><label for="checkbox-'+int+'a">'+name[int]+'</label>';
}
alert('<legend><h3>Choose as many players as you would like to remove:</h3></legend>'+html+'</fieldset');
$("#list").html(html+'</fieldset');
//$("#list").page();});​
What I am doing wrong?
Thanks.
$("#list").trigger('create');
From: jqm docs
if you generate new markup client-side or load in content via Ajax and inject it into a page, you can trigger the create event to handle the auto-initialization for all the plugins contained within the new markup. This can be triggered on any element (even the page div itself), saving you the task of manually initializing each plugin (listview button, select, etc.).
I do applogies if this post is too old and if my post isn't by the correct standard since it's the first time ever posting so please correct me if it's horribly bad :-]
But in case someone else comes across it, I had similar problems with how the dynamic data is displayed and I used the jsfiddles and comments above as a help, and this is what got mine to work, well somewhat near my solution, I don't have a button to load the data it's loaded automatically when the page is loaded.
Updated In my .html-file:
<div id="members"></div>
<input type="button" id="load" value="test"/>
Updated In my .js-file:
$("#load").click(function(){
var name = ["NameOne","NameTwo", "NameThree"];
var fset = '<fieldset data-role="controlgroup" id="members-ctrlgroup"><legend>This is a legend:</legend>';
var labels='';
for ( var i = 0; i < name.length; i++) {
labels += '<input type="checkbox" class="checkbox" id="c'
+ i
+ '"><label for="c'
+ i
+ '" data-iconpos="right">'
+ name[i]
+'</label>';
}
$("#members").html(fset+labels+'</fieldset>');
$("#members").trigger("create");
});
I know the "field" looks a bit weird how I divided it but I find it somewhat easier when it comes to getting the whole html-string correct in these cases.
Updated In order to have the rounded corners and have it as one controlgroup you'll have to have this approach instead. Just like the former posters showed.
Do note that the id with the checkbox and the label for= can tend to screw the output if they're not the same :-]
fiddle
In order to replace the content you should use .html(); instead of .append(), which adds the new content after the existing one.
After adding content to a jQuery Mobile Page you need to enhance the content, using for instance $("input[type='radio']").checkboxradio();
I was using
for( var i=0 ; i < html.length ; i++ ){
var spline = html[i].split("|");
inHTML = inHTML + " <input type=\"checkbox\" name=\"checkbox-"+i+"a\" id=\"checkbox-"+i+"a\" class=\"custom\" /> <label for=\"checkbox-"+i+"a\">"+ spline[0] +" , "+ spline[2] +"</label> ";
}
jq("fieldset#myFieldSet").empty();
jq("fieldset#myFieldSet" )
// Append the new rows to the body
.append( inHTML )
// Call the refresh method
.closest( "fieldset#myFieldSet" )
// Trigger if the new injected markup contain links or buttons that need to be enhanced
.trigger( "create" );

JQM - Inject dynamic content at load time only

I'm trying to dynamically populate a select tag at load time (latest jQM version) using a custom template filling function.
If the fn is called in the "pagebeforechange" event, the select tag is properly initialized. Since this event is called on every page transition, I thought of moving the fn to the 'pageinit' event. This does not work, presumably because the DOM is not yet fully available. How can I coerce jQM to inject content in a page only once? Currently, I am using a kludge. There surely must be a smarter way. Thanks for any suggestions.
$(document).bind('pageinit', function () {
InitSelTagTest("#selActTag", "tplTag"); // Does not work.
});
$(document).bind("pagebeforechange", function (e, data) {
if ($("#selActTag").children().size() === 0) {
InitSelTagTest("#selActTag", "tplTag"); // Kludge, but it works
}
});
function InitSelTagTest(el,tpl) { // Append all tags to element el
var lstAllTags = JSON.parse($("#hidTag").val()); // Create tag array
// Retrieve html content from template.
var cbeg = "//<![" + "CDATA[", cend = "//]" + "]>";
var rslt = tmpl(tpl, { ddd: lstAllTags }).replace(cbeg, ").replace(cend,");
$(el).html(rslt).trigger("create"); // Add to DOM.
}
EDIT
In response to Shenaniganz' comment, it seems that the "pagebeforecreate" event could do the trick ie.
$("#pgAct").live("pagebeforecreate", function () {
// Populate tag select. Works. Traversed only once.
InitSelTag("#selActTag", "tplTag");
});
I'm not sure I fully understand your question but I'll throw a few things out there and you let me know if I can extend further.
To make something trigger only once on page load you can try to implement a regular JQuery $(document).ready(function(){}) aka $(function(){}) for the exact reason why JQuery Mobile users are told not to use it. It triggers only once on DOM load. Further pages don't trigger it because they're being switched via Ajax.
Other than that, on regular dynamic content loading you take a look at the following example I put together for someone else earlier:
http://jsbin.com/ozejif/1/edit

Resources