Get value from jQuery Datarow - javascript

I have an asp.net page - I am using jQuery datatables on it.
Part of the code is below:
<% foreach (SubmissionSearchResult result in SearchResults)
{%>
<tr data-name='<%=result.ID %>'>
So each time a row is drew on screen I am adding a data-name of result ID to it. What I want then is on clicking the row retrieve this ID.
I had something like the below to start :
$('#searchResultsTbl').on("click", "tbody tr", function () {
var nTds = $('td', this);
var id = $(nTds[0]).text().trim();
This worked when the id was in the first td in the row but now the columns can be dynammic and it may not be in the first column. So I wanted to add the id to each row and then get it from the row so I added it as a data-name but not sure on how to get the value back from it?

$('#searchResultsTbl').on("click", "tbody tr", function () {
var id = $(this).data('name');
});

try this
$('#searchResultsTbl tr:gt(0)').click(function () {
var this_row = $(this);
var data_name = this_row.attr('data-name');//row attribute
var first_td = $.trim(this_row.find('td:eq(0)').html());
var second_td = $.trim(this_row.find('td:eq(1)').html());
var third_td = $.trim(this_row.find('td:eq(2)').html());//and so on
});

add the javascript function on click event of row
like
<tr data-name='<%=result.ID %>' onclick='showid("<%=result.ID %>")'>
Now in javascript define this showid function
function showid(rowvalue)
{
alert(rowvalue);
}

Related

issue with adding datetimepicker in dynamically added table rows

I am working on a project where I am finding difficulty in adding datetimepicker to dynamically added table rows. I have added datetimepicker to static table rows and it is working fine for them but not working for dynamically added table rows.
The tutorial I am following for datetimepicker
https://eonasdan.github.io/bootstrap-datetimepicker/
My Code I tried: I am cloning hidden rows.
Row Clone function:
// Table Add Function
$('.table-add').click(function () {
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
//always assign new id to new table row, will be easy to recognize rows
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.find("[name='datepicker']").datetimepicker();
//$("[name='datepicker']").datetimepicker();
$hiddentr = $('table').find('tr.hide');
//add dynamic word picker to cloned rows dynamically
$clone.find('td:nth-last-child(4)').after('{% if obj.word_picker == "Y" %} <td><input id="wordpicker" style="border:none"; data-role="tagsinput" class="myinput" name="unique_tag"/></td>{% endif %}');
$clone.appendTo( $('#'+hid).parent());
//submitting form after row clone
submitForm();
});
HTML of hidden td:
<td>
<div style="position: relative">
<input class = "form-control" type= "text" name = "datepicker" id= "datetime">
</div>
</td>
Messy but just init datetimepisker each time after you add a row...
$('#datetimepicker1').datetimepicker();
$('#datetimepicker2').datetimepicker();
etc
I was able to initialize the datetimepicker once the element was completely generated into the dom. working codepen
function addTableRow() {
var tbodyElement = document.getElementById("tbody");
var trElement = document.createElement("tr");
trElement.id = "generatedTr";
for (var x=0; x<3; x++) {
var tdElement = document.createElement("td");
var textNode = document.createTextNode("Generated td: " + x);
tdElement.appendChild(textNode);
trElement.appendChild(tdElement);
}
var finalTdElement = document.createElement("td");
var inputElement = document.createElement("input");
inputElement.setAttribute("type", "text");
inputElement.id = "generatedInput";
finalTdElement.appendChild(inputElement);
trElement.appendChild(finalTdElement);
tbodyElement.appendChild(trElement);
$('#generatedInput').datetimepicker();
}
If you have multiple elements that are being generated that needs the datetime picker, then I would suggest creating a class on all of them, then simply instantiate the plugin against that class like so.
$('.dateTimePickers').datetimepicker();
I would suggest don't initialize the datetimepicker every time after each element. better use following code. It will work like a charm.
I have been doing lot of research for this. Thus, Recommending to use Following code.
$('body').on('focus',".datetimepicker", function(){
$(this).datetimepicker();
});

Selecting custom attributes within a <div> with jQuery

I have a table that has the following td:
<td>
<div id="spcheck">
<div id="check"
data-1='<%# Eval("sth1") %>'
data-2='<%# Eval("sth2") %>'
data-3='<%# Eval("sth3") %>'>
<asp:CheckBox ID="chk1" runat="server"/>
</div>
</div>
</td>
This is the last one. It has custom attributes as you can see. I need to get the values data-1, data-2 and data-3 if have the checkbox cheked. I have the folowing code that gets each tr but I need to go inside the td and get the attribute values:
$('#ListView2_itemPlaceholderContainer tbody tr').each(function () {
// I GET THE <TR>
$(this).find('input:checkbox:checked').each(function () {
// I NEED THIS CODE
});
});
});
Thanks in advance.
Because the attributes are on the div , you need to find the div first and get the attributes of the div.. You can use the .attr() on the div to get them
$(this).find('input:checkbox:checked').each(function () {
var $closestDiv = $(this).closest('div'); // Find the div
var $data1 = $closestDiv.attr('data-1'); // data-1
var $data2 = $closestDiv.attr('data-2'); // data-2
var $data3 = $closestDiv.attr('data-3'); // data-3
});
$('#ListView2_itemPlaceholderContainer tbody tr').each(function () {
$(this).find('input:checkbox:checked').each(function () {
var dataElement = $(this).closest('[data-1]');
var data1 = dataElement.data('1');
var data2 = dataElement.data('2');
var data3 = dataElement.data('3');
});
});
});
$(this).attr('data-1');
should do the trick
see jQuery manual entry for attr

.clone doesn't not appear to be incrementing

this script is suppose to clone a new row of a HTML table. It does not seem to be incrementing the name, id, attributes. What am I doing wrong? The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_* although I think that is because it does seem to be incrementing as it clones a row.
<script type="text/javascript">
function MaskTime(){
var index = $("#TimeCard tbody>tr").length-1;
$('#endtime_'+index).mask("99:99 aa");
$('#starttime_'+index).mask("99:99 aa");
}
function update_rows(){
$("#TimeCard tbody>tr:odd").css("background-color", "#FFF");
$("#TimeCard tbody>tr:even").css("background-color", "#999");
}
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
$("td:eq(0) select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
$("td:eq(1)").html(" ")
$("td:eq(2) select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
$("td:eq(3)").html(" ")
$("td:eq(4) input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
$("td:eq(5) input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
$("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
</script>
For the first part of your question:
It does not seem to be incrementing the name, id, attributes.
Your script isn't giving the proper context for where the tds are for which you want to modify the attribues, etc.
Here's a modification that corrects that, adding a new variable "newrow" (to reduce DOM calls) and modifying the lines of code related to td:eq(#)...
$(document).ready(function() {
$("#addrow").click(function() {
var row = $('#TimeCard tbody>tr:last').clone(true).insertAfter('#TimeCard tbody>tr:last');
var index = $("#TimeCard tbody>tr").length-1;
var endvalue = $('#endtime_'+index-1).val();
var newrow = $("#TimeCard tbody>tr:last");
newrow.children("td:eq(0)").children("select").attr("name", 'type_'+index).attr("id", 'type_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(1)").html(" ")
newrow.children("td:eq(2)").children("select").attr("name", 'propid_'+index).attr("id", 'propid_'+index).addClass("validate[required]").val('')
newrow.children("td:eq(3)").html(" ")
newrow.children("td:eq(4)").children("input").attr("name", 'starttime_'+index).attr("id", 'starttime_'+index).addClass("validate[required,custom[timeclock]]").val(endvalue)
newrow.children("td:eq(5)").children("input").attr("name", 'endtime_'+index).attr("id", 'endtime_'+index).addClass("validate[required,custom[timeclock]]").val('')
newrow.children("td:eq(6)").html(" ")
update_rows();
MaskTime();
return false;
});
});
Also, I'd made a jsfiddle with the above: http://jsfiddle.net/m78UN/2/
I'm not following what you're wanting when you describe your second problem:
The only other thing that is not working is get the value from the previous input id of #endtime_* and putting it in the cloned input id of #starttime_*
...so I've not attempted to address that.
I think you can do everything you're doing in a way simpler way. I don't have your original HTML, but check this out as a possible alternative. It mainly does 3 things:
Removed IDs used for finding things
Caches selectors
Adds classes to time inputs to make them easier to reference
Removed MaskTime() function
Here's the code:
$(document).ready(function() {
var $timecard = $("#TimeCard");
var $tbody = $timecard.find("tbody");
var $rows = $tbody.children("tr");
$("#addrow").click(function(e) {
e.preventDefault(); // clearer than return false
var $lastRow = $tbody.find("tr:last-of-type");
var lastEnd = $lastRow.find(".endTime").val();
var $newRow = $lastRow.clone(true).appendTo($tbody);
var $cols = $newRow.find("td");
var index = $rows.length - 1;
$cols.eq(0).find("select").attr("name", 'type_' + index).addClass("validate[required]").val('');
$cols.eq(1).empty();
$cols.eq(2).find("select").attr("name", 'propid_' + index).addClass("validate[required]").val('');
$cols.eq(3).empty();
$cols.eq(4).find("input").attr("name", 'starttime_' + index).addClass("time startTime validate[required,custom[timeclock]]").val(lastEnd);
$cols.eq(5).find("input").attr("name", 'endtime_' + index).addClass("time endTime validate[required,custom[timeclock]]").val('');
$cols.eq(6).empty();
update_rows(); // no idea what this is
$newRow.find(".time").mask("99:99 aa"); // MaskTime() just did this
});
});

if ID is missing fill the rows in another hiddenfield with jquery

I have one Table that is named CustomPickedTable, this Table have rows with attribute such as <td Data-question-id="5">Example</td> and some of the rows do not have any attribute at all. just <td>example</td>.
I want to do be able to sort em into different hiddenfields, these are my hiddenfields:
#Html.HiddenFor(model => model.SelectedCustomQuestions, new { #id = "SelectedQuestionsWithAttr" })
#Html.HiddenFor(model => model.SelectedQuestions, new { #id = "SelectedQuestionsWithNoAttr" })
the code that I have right now is that all rows with attribute "data-question-id" gets filled to SelectedQuestionsWithAttr that is my hiddenfield for rows with attributes.
But I want that my Jquery code also fills those rows with no attributes gets filled to my SelectedQuestiosnWithNoAttr hiddenfield.
This is the code for Just filling SelectedQuestionsWithAttr hiddenfield:
var selectedQuestionsWithAttr = $("#SelectedQuestionsWithAttr");
var currentIds = new Array();
$("#CustomPickedTable").find("td").each(function () {
var clickedId = $(this).attr("data-question-id");
currentIds.push(clickedId);
});
selectedQuestionsWithAttr.val(currentIds.join(","));
$("form").submit();
}
Is there any solutions that can I add to my jquery code for this?
Thanks in Advance
You would need to add something onto the <td> tags to be able to identify them:
<td id="noAttr#(Model.SelectedQuestions.IndexOf(variable))">
Then the jQuery would be:
var $qWithAttr = $("#SelectedQuestionsWithAttr");
var $qWithoutAttr = $("#SelectedQuestionsWithNoAttr");
var currentIds = new Array();
var missingIds = new Array();
$("#CustomPickedTable td[data-question-id]").each(function () {
currentIds.push($(this).attr("data-question-id"));
});
$("#CustomPickedTable td:not([data-question-id])").each(function () {
missingIds.push($(this).attr("id"));
});
$qWithAttr.val(currentIds.join(","));
$qWithoutAttr.val(missingIds.join(","));
$("form").submit();

Loop through gridview rows on client-side javascript

I have a gridview with a template field of check boxes.
I have my rows color coded in BLUE color in the gridview based on a database value on page load.
Now I want a button on the page to loop through the gridview and select the the checkbox for the rows that are in BLUE Color without a post back.
any help would be appreciated.
thanks.
Loop through gridview rows on client-side javascript
var GridviewRows = $("#<%=gvbooksdetails.ClientID%> tr").length;
var rowlenght = GridviewRows - 1;
for (var i = 0; i < rowlenght; i++)
{
var Aname = document.getElementById("MainContent_gvbooksdetails_lblgvauthorname_" +[i]+"").innerHTML;
var Bname = document.getElementById("MainContent_gvbooksdetails_lblgvbookname_" +[i]+ "").innerHTML;
var BType = document.getElementById("MainContent_gvbooksdetails_lblgvbooktype_" +[i]+ "").innerHTML;
var Pubilication = document.getElementById("MainContent_gvbooksdetails_lblgvPublisher_" + [i] + "").innerHTML;
var Bid = document.getElementById("MainContent_gvbooksdetails_hiddenid_"+[i]+"").value;
}
Instead of foreach we can use this method.
$('#mygrid tr.blueClass input[type="checkbox"]').each(
function() {
this.checked = true;
});
Assuming mygrid is the name of your gridview, and each blue row has a class called blueClass

Categories

Resources