How to tell how many datalists in page with JavaScript - javascript

This is an ascx page and the code is in aspx. It will show more than one datalist. How can I get the number of datalists in the page through JavaScript?
<asp:DataList ID="TF_DataList" runat="server" RepeatDirection="Vertical" OnItemCreated="TF_Datalist_ItemCreated">
<ItemTemplate>
<table style="text-align:left;">
<tr>
<td valign="top" align="left" nowrap="nowrap">
<asp:RadioButton ID="lbTrue" runat="server" GroupName="ans" Text="T" onclick="Radcheck();"
/>
<asp:RadioButton ID="lbFalse" runat="server" GroupName="ans" Text="F" onclick="Radcheck();"
/>
</td>
<td>
</td>
<td runat="server" id="AnswerContentTD" style="text-align: left">
<asp:Label ID="lblAnswerText" runat="server" Text='<%# Eval("AnswerText")%>'>
</asp:Label>
</td>
</tr>
</table>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left">
</ItemStyle>
</asp:DataList>

The best you can do is this work around. Give a CssClass="mydatalist" to every datalist in your page. Please rememeber these things.
All your asp:DataList must have this CssClass
Only the asp:DataList must have this CssClass
Javascript implementation.
function FindDataLists(){
var datalists = document.getElementsByClassName("mydatalist");
return datalists ? datalists.length : 0;
}
// fallback for LTE IE8
if (!document.getElementsByClassName) {
document.getElementsByClassName = function (className, parentElement) {
if (Prototype.BrowserFeatures.XPath) {
var q = ".//*[contains(concat(' ', #class, ' '), ' " + className + " ')]";
return document._getElementsByXPath(q, parentElement);
} else {
var children = ($(parentElement) || document.body).getElementsByTagName('*');
var elements = [],
child;
for (var i = 0, length = children.length; i < length; i++) {
child = children[i];
if (Element.hasClassName(child, className)) elements.push(Element.extend(child));
}
return elements;
}
};
}
If you are using jQuery
function FindDataLists(){
var datalists = document.getElementsByClassName("mydatalist");
return $(".").length;
}

<asp:DataList> does not generate any html tags for itself. So you can only define the number of <table style="text-align:left;"> elements on your page. Add an name attribute to them and count elements with such name.

Related

How to get value of selected label from repeater using javascript

i have bind the the repeater and i want to get the value of label while check on particular check box:
$(function() {
$('.toggleCheck').change(function() {
console.log('Toggle: ' + $(this).prop('checked'))
RepeaterData();
})
})
function RepeaterData() {
var size = $('.nameLabel').length;
console.log('size' + size);
for (i = 0; i < size; i++) {
var name = $('.nameLabel').eq(i).text();
var id = $('.IdLabel').eq(i).text();
//var result = document.getElementById('result');
alert(name);
// result.innerText += name + " \t " + id + "\n";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<asp:Repeater ID="rptCust" runat="server">
<HeaderTemplate>
<div class="table-responsive">
<table class="table table-striped table-bordered table-hover table-highlight" data-provide="datatable" data-display-rows="10" data-info="true" data-search="true" data-length-change="true" data-paginate="true">
<thead>
<tr>
<th data-filterable="true">No</th>
<th>name</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblId" CssClass="IdLabel" runat="server" Text='<%#Eval("id")%>' Style="display: none"></asp:Label>
<asp:Label ID="lblno" CssClass="nameLabel" runat="server" Text='<%#Eval("no")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblname" runat="server" Text='<%#Eval("name")%>'></asp:Label>
</td>
<td>
<input id="Checkbox1" commandname="Edit" data-toggle="toggle" type="checkbox" checked='<%# (Eval("status")).ToString() == "1" ? true : false %>' runat="server" class="toggleCheck">
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</tbody>
</table>
</div>
</FooterTemplate>
</asp:Repeater>
i have written above code .
Now when i click on check box then i need to get id of that checkbox using javascript.
I have tried to get the value but it gives me all the value instead of particular id on checkbox checked/unchecked.
How can i get value of particular id when i am checked/unchecked the checkbox ?
you can do this...
$('.toggleCheck').click(function(){
console.log($(this).attr('id'));
})
or if you want to identify if cheched...
$('.toggleCheck').click(function(){
if($(this).is(':checked')){
console.log($(this).attr('id'));
}
})
i have solved it . Below is the code.
i have added var id = $(this).closest('tr').find('td:first-child').text();
with the above line i am able to get particular id on checkbox checked/unchecked
$(function() {
$('.toggleCheck').change(function() {
console.log('Toggle: ' + $(this).prop('checked'))
var id = $(this).closest('tr').find('td:first-child').text();
})
})

Search for matches in DataList using JavaScript

First, I'm working in C#, in ASP.NET, I have a DataList with employees, and the names are in Labels, into a ItemTemplate.
Then I need a JavaSript funtion that catch the text typed by the user and compare it with the Label's text. If exits a coincidence show the Row, else hide it.
<asp:DataList ID="dt_usuario" runat="server" CellPadding="4" OnItemCommand="dt_usuario_ItemCommand"
ForeColor="#333333" BorderColor="Black" BorderStyle="Dashed" BorderWidth="1px" ItemStyle-BorderColor="Gray" ItemStyle-BorderStyle="Dashed" ItemStyle-BorderWidth="1px">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#EFF3FB" />
<ItemTemplate>
<table>
<tr>
<td>
<asp:Label ID="lblid" runat="server" Visible="false" Text='<%# DataBinder.Eval(Container.DataItem, "id_usuario" )%>'></asp:Label>
</td>
<td style="width:450px;" title="emploee">
<asp:Label ID="lbl" runat="server" Text='<%# DataBinder.Eval(Container.DataItem, "nom_institucion") %>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="lkreport" runat="server" Text="Reporte" CommandName="Reporte" class="btn btn-7 btn-7ba icon-reporte"><span><center>Imprimir</center></span></asp:LinkButton>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
<asp:TextBox ID="txtSeach" Width="400px" onkeyup="javascript:Seach(this)" runat="server"></asp:TextBox>
I'm tried to create my own funtion, but didn't work
function Seach(phrase)
{
var palabra = phrase.value.toLowerCase().split(" ");
var datalist = document.getElementById('<%=dt_usuario.ClientID%>');
for (var i = 0; i < datalist.length; i++)
{
var usuario = datalist.rows[i].getElementById("lblUsuario").value;
var institucion = datalist.rows[i].getElementById("lblInstitucion").value;
if (usuario.match(/palabra.*/) || institucion.match(/palabra.*/))
{
datalist.rows[i].visible = false;
}
}
}
</script>
I hope somebody could help me
Here are a few adjustements that you can make to your code:
Since the table rows don't support the getElementById method, the getElementsByClassName method can be used instead. A common class name can be given to the Labels targeted by the search, so that they can be retrieved with a single call.
The Labels being rendered as span elements, their content is given by the innerHTML property instead of value.
The display style can be used to show/hide the rows, instead of the visible property (which does not exist).
You refer to Labels with IDs lblUsuario and lblInstitucion in your function but I don't see them in your markup. I assume that they were lost when you copied/pasted your code in the question.
Typical markup for the Labels in the DataList:
<asp:Label ID="lblUsuario" runat="server" CssClass="fieldValue" Text='<%# DataBinder.Eval(Container.DataItem, "nom_usuario") %>' />
<asp:Label ID="lblInstitucion" runat="server" CssClass="fieldValue" Text='<%# DataBinder.Eval(Container.DataItem, "nom_institucion") %>' />
The Search function:
function Search(phrase) {
var i, j, k;
var fields, foundMatch;
var palabra = phrase.value.toLowerCase().split(' ');
var datalist = document.getElementById('<%= dt_usuario.ClientID %>');
for (i = 0; i < datalist.rows.length; i++) {
foundMatch = false;
fields = datalist.rows[i].getElementsByClassName('fieldValue');
for (j = 0; j < palabra.length; j++) {
for (k = 0; k < fields.length; k++) {
if (fields[k].innerHTML.toLowerCase().indexOf(palabra[j]) >= 0) {
foundMatch = true;
break;
}
}
}
datalist.rows[i].style.display = foundMatch ? '' : 'none';
}
}
I assume this is what you are after. You can use RegEx.IsMatch(input, pattern)
First, add using System.Text.RegularExpressions;
Then:
function Seach(phrase)
{
var word = phrase.value.toLowerCase().split(" ");
var datalist = document.getElementById('<%=dt_employee.ClientID%>');
for (var i = 0; i < datalist.length; i++)
{
var empl = datalist.rows[i].getElementById("lblemployee").value;
if (RegEx.IsMatch(empl, word))
{
datalist.rows[i].visible = false;
}
}
}

querySelectorAll returns empty nodelist

I have an ASP.Net page with 3 textboxes and 1 radiobuttonlist. Each of the 4 controls has
class="tabbable"
in its definition. Here's the complete markup:
<%# Control Language="c#" AutoEventWireup="false" Codebehind="approvalacctprocess.ascx.cs" Inherits="cmc.workflow.ui.ApprovalAcctProcess" TargetSchema="http://schemas.microsoft.com/intellisense/ie5" %>
<%# Register tagprefix="CMC" Tagname="ApprovalComments" src="~/workflow\ui\ApprovalComments.ascx" %>
<script src="../../Scripts/jquery-1.4.1.js"></script>
<asp:Panel ID="pnlApprovalAC" CssClass="STDPANEL" HorizontalAlign="Center" Runat="server" Width="550">
<TABLE cols="2" width="520">
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Client Number</TD>
<TD>
<asp:TextBox id=txtclnum style="VERTICAL-ALIGN: top" Width="300" Runat="server" CssClass="FLDVALUE" TabIndex="0" onchange="MoveNext(this);" Text='<%# Property["clnum"] %>' MaxLength="14" AutoPostBack="True" class="tabbable"></asp:TextBox>
<asp:RegularExpressionValidator id="rxClNum" ValidationExpression="^[0-9]+[ ]*$|Clt Number TBD" ErrorMessage="Client Number consists of up to 14 numbers"
ControlToValidate="txtclnum" runat="Server"></asp:RegularExpressionValidator></TD>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Matter Number (5-6 digit)</TD>
<TD>
<asp:Label id=lbclnum style="TEXT-ALIGN: right" Width="140" Runat="server" Text='<%# Property["clnum"] %>' Font-Name="verdana" Font-Size="x-small">
</asp:Label>-
<asp:TextBox id=txtmmatter Width="150" Runat="server" CssClass="FLDVALUE" TabIndex="1" Text='<%# Property["mmatter"] %>' MaxLength="6" AutoPostBack="True" class="tabbable"></asp:TextBox>
</TD>
<TR>
<TD colSpan="2">
<HR style="COLOR: gray; TEXT-ALIGN: left" SIZE="1">
</TD>
</TR>
<tr>
<td class="FLDLABEL" style="VERTICAL-ALIGN: top" width="500" colspan="2"><asp:Label runat="server" ID="lbExistingClientQuestion" Text="Is there an Engagement Letter on file for this client?" Visible="false" />
<asp:Label runat="server" ID="lbUDFRetainerLetter" Text='<%# Property["RetainerLetter"] %>' Visible="false" /></td>
</tr>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top" width="500" colSpan="2">Has a
retainer/engagement letter been submitted and approved by Charlotte Fischman?</TD>
</TR>
<TR>
<TD colSpan="2">
<asp:RadioButtonList id="rblRetLtrReturned" TabIndex="2" Runat="server" CssClass="RADIOBUTTONLIST" RepeatDirection="Horizontal" class="tabbable"
RepeatLayout="Table" RepeatColumns="1" width="300" AutoPostBack="True">
<asp:ListItem Value="0">No</asp:ListItem>
<asp:ListItem Value="1">Yes</asp:ListItem>
</asp:RadioButtonList>
<asp:Label id="lblnoretainerltrneeded" Runat="server" CssClass="SMALLNOTE" Text="(This is an existing client and the matter is in an existing area of law.
A retainer letter may not be needed.)"
Font-Size="xx-small" Visible="False" ForeColor="red"></asp:Label></TD>
</TR>
<TR>
<TD colSpan="2">
</TD>
</TR>
<TR>
<td class="FLDLABEL" style="VERTICAL-ALIGN: top" colSpan="2" width="500">Reason for Not Submitting an Retainer/Engagement Letter for Approval<SPAN style="FONT-WEIGHT: bold; COLOR: red">
*</SPAN>
<asp:Label runat="server" CssClass="SMALLNOTE" Text="(Required if no retainer letter submitted and not an existing client)" Font-Size="XX-Small" ForeColor="Red" /></td>
</TR>
<TR>
<td colspan="2">
<asp:TextBox Width="500" runat="server" TextMode="MultiLine" TabIndex="3" CssClass="FLDVALUE" ID="txtReason" MaxLength="500" Text='<%# Property["Reason"] %>' AutoPostBack="True" class="tabbable" />
</td>
</TR>
<TR>
<TD colSpan="2">
<HR style="COLOR: gray; TEXT-ALIGN: left" SIZE="1">
</TD>
</TR>
<TR>
<TD class="FLDLABEL" style="VERTICAL-ALIGN: top">Comments</TD>
<TD>
<asp:TextBox id="txtComments" style="VERTICAL-ALIGN: top" Width="300" TabIndex="4" Runat="server" CssClass="FLDVALUE"
MaxLength="450" Rows="5" TextMode="MultiLine" Text='<%# Property["AcctgComment"] %>' AutoPostBack="True" class="tabbable"></asp:TextBox></TD>
</TR>
</TABLE>
<TABLE class="STDPANEL" style="VERTICAL-ALIGN: middle" height="50" width="550">
<TR>
<td align="center">
<input id="btnSaveACProperty" runat="server" name="btnSaveACProperty"
onserverclick="OnSave_Click" type="submit" value="Save Status and Comment">
<input id="btnResetACProperty" runat="server" name="btnResetACProperty"
type="reset" value="Cancel">
</input>
</input>
</td>
<tr>
<td align="left">
<asp:ValidationSummary ID="valsum" runat="server" BorderColor=""
BorderStyle="Solid" BorderWidth="2" CssClass="VALIDATORSUM" DisplayMode="List"
Font-Bold="True" ForeColor="red"
HeaderText=" Some errors occurred in your input. Please correct them:<br> "
ShowMessageBox="True" ShowSummary="True" Width="500" />
</td>
</tr>
</TABLE>
</asp:Panel>
<script type="text/vbscript">
</script>
<script type="text/javascript" lang="javascript">
function MoveNext(ele) {
$(document).ready(function () {
var lastTabIndex = 4;
var currentElementID = ele.id; // ID set by OnFocusIn
var currentElement = document.getElementById(currentElementID);
var curIndex = currentElement.tabIndex; //get current elements tab index
if (curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
curIndex = 0;
}
var tabbables = document.querySelectorAll("tabbable"); //get all tabbable elements
alert(tabbables.length);
for (var i = 0; i < tabbables.length; i++) { //loop through each element
if (tabbables[i].tabIndex == (curIndex + 1)) { //check the tabindex to see if it's the element we want
tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
break;
}
}
});
}
</script>
The textbox txtclnum calls the javascript function MoveNext at the bottom of the page (just to make sure everything loads in the right order)(this is taken from the first answer to this question). MoveNext has an alert in it to tell me what tabbables.length is. The alert returns 0 because the CssClass in the .Net controls overwrites the class="tabbable" in the HTML. I've tried
var tabbables = document.getElementsByTagName("*");
which gets me to the correct control, but the focus doesn't stay on that control. How can I keep the focus on the control?
That function takes as its argument a CSS selector, so if you're looking for elements with class "tabbable" you would use document.querySelectorAll(".tabbable")
Since tabbable is a class, you need to put a period in front of it in your queryselector, so it should be:
document.querySelectorAll(".tabbable")
Edit: Just further clarification, the queryselector without the "." would be looking for html tags like <tabbable>. Since that does not exist, the length returned is 0.
The way you're using it, document.querySelectorAll("tabbable") is looking for an element of the tag <tabbable>. Since it looks like you're trying to query by a class, add the period to denote it is such.
document.querySelectorAll(".tabbable")
When you use document.getElementsByClassName("tabbable") it could work, so I could see where you could get confused if you've used that method in the past.
OK, I feel like an idiot. Just for others' future reference, the problem was that 1) there's a Cssclass assigned to those controls, which overrides my tabbable class in the HTML markup; and 2) once I took care of that (see below code), it still wasn't working because (duh) each control had an AutoPostBack=true on it (they used to have server-side code attached to them). Now that AutoPostBack is false, my code works fine. Here it is:
<script type="text/javascript" lang="javascript">
function MoveNext(currentElement, btnID) {
$(document).ready(function () {
var saveButton = document.getElementById(btnID);
saveButton.disabled = false;
var lastTabIndex = 4;
var curIndex = currentElement.tabIndex; //get current elements tab index
if (curIndex == lastTabIndex) { //if we are on the last tabindex, go back to the beginning
curIndex = 0;
}
var tabbables = document.getElementsByTagName("*"); //get all tabbable elements
for (var i = 0; i < tabbables.length; i++) { //loop through each element
if (tabbables[i].tabIndex != null & tabbables[i].tabIndex == (curIndex + 1)) { //check the tabindex to see if it's the element we want
tabbables[i].focus(); //if it's the one we want, focus it and exit the loop
break;
}
}
});
}
Thanks to everyone for their help.

Adding DropDown-Selectedvalue to ContextKey of Autocomplete control Using Javascript

I'm having a Drop-down-list and a Text-box with auto-completed extender on my web form.
Now i need to set ContextKey property of auto-completed extender from java-script.
I'm trying to set ContextKey property using java-script on onkeyup event of text-box. But it's not working
.aspx code
<table>
<tr>
<td style="width:100px;">
<asp:Label ID="Label1" CssClass="lbl" runat="server" Text="Server:"></asp:Label>
</td>
<td colspan="4">
<asp:DropDownList ID="DropDownList1" CssClass="Comb" runat="server"
OnSelectedIndexChanged="ddlServer_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" CssClass="lbl" runat="server" Text="Originating:"></asp:Label>
</td>
<td colspan="4">
<asp:TextBox runat="server" ID="TextBox1" CssClass="tb10" autocomplete="off" onkeyup="SetContextKey()"/>
<ajaxToolkit:AutoCompleteExtender TargetControlID="TextBox1" UseContextKey="true"
runat="server" BehaviorID="AutoCompleteEx" ID="AutoCompleteExtender1"
ServicePath="AutoComplete.asmx" ServiceMethod="GetResellerList"
MinimumPrefixLength="1" CompletionInterval="1000" EnableCaching="true" FirstRowSelected="true"
CompletionSetCount="20" CompletionListCssClass="cssList" DelimiterCharacters=";, :"
ShowOnlyCurrentWordInCompletionListItem="true" OnClientHiding="OnClientCompleted"
OnClientPopulated="OnClientCompleted" OnClientPopulating="OnClientPopulating">
</ajaxToolkit:AutoCompleteExtender>
</td>
</tr>
</table>
.cs code (Service Code)
[WebMethod]
public string[] GetResellerList(string prefixText, int count, string contextKey)
{
DataSet ds = new DataSet();
ds = clsTransaction.Select("SELECT nm AS Name FROM tblReseller WHERE nm LIKE '" + prefixText + "%' AND wsid = '" + contextKey + "'",
DataSendBSSWEB.ServerDbEnum.MainSqlServer,
false);
//Then return List of string(txtItems) as result
List<string> txtItems = new List<string>();
String dbValues;
foreach (DataRow row in ds.Tables[0].Rows)
{
dbValues = row["Name"].ToString();
txtItems.Add(dbValues);
}
return txtItems.ToArray();
}
javascript Code
<script type="text/javascript">
function SetContextKey() {
$find('<%=autoComplete2.ClientID%>').set_contextKey($get("<%=ddlServer.ClientID %>").value);
}
</script>
Can any one tell me how can i do this using java-script.
Target control id of the extender should be the TextBox's Id, Not the drop down's.

Set Value Textbox Inside GridView Using Javascript

I want the stored value in "val" and assgined to the textbox in the gridview. I'm able to loop and find the rows but not the control. I'm getting a undefined error message. What I'm missing that I cannot find the control . Attached is the sample code:
<!--Javascript Code-->
<script type="text/javascript">
function SetPIN(val)
{
if (Searching == 'eID')
{
var num = val;
var grdvw = document.getElementById('gvEvents');
for (var rowId = 1; rowId < grdvw.rows.length -1; rowId++){
var txtbx = grdvw.getElementById('txtEvtTo').value;
txtbx = num;
}end for
}
}
</script>
<asp:GridView ID:gvEvents runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox ID="txtEvtTo" runat="server" Width="250px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I've tried different options that I've online but I haven't been able to get the value to textbox
Any suggestions would be greatly appreciate it.
DR
Don't look at the html markup in the IDE, but the rendered html as shown in "view page source" of your browser. asp control id's get mangled when rendered, so unless you set the control's ClientIDMode to Static, your call to getElementById won't work for finding the gridview or the cell controls.
Here are a couple of sample data rows from one of my gridviews:
<tr class="gvRowStyleContactList " valign="middle">
<td>
<span id="ctl00_ctl00_cphMain_IEHContent_gvEscalationContactListView_ctl02_lblEmailAddress">x#v.com</span>
</td>
</tr>
<tr class="gvRowStyleContactList " valign="middle">
<td>
<span id="ctl00_ctl00_cphMain_IEHContent_gvEscalationContactListView_ctl03_lblEmailAddress">xx#vv.com</span>
</td>
</tr>

Categories

Resources