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;
}
}
}
Related
In the below code there is a radiobuttonlist control and Multiline textbox. On button click I would need to check whether textbox query should contain any WHERE clause. If yes then will get executed directly, but if not then should get confirmation box. If clicked on "Ok" then should get proceed but if clicked on "Cancel" then process get terminated there itself.
In my case confirmation box is not popping up and how to get it's value at code behind?
For this I would have followed an article as
https://www.aspsnippets.com/Articles/Server-Side-Code-Behind-Yes-No-Confirmation-Message-Box-in-ASPNet.aspx
below is my code
HTML:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script>
function alertmsg(m) {
alert(m);
}
function alertmsgwithYesNo(m) {
var confirm_value = document.createElement("INPUT");
confirm_value.type = "hidden";
confirm_value.name = "confirm_value";
if (confirm(m)) {
confirm_value.value = "Yes";
} else {
confirm_value.value = "No";
}
document.forms[0].appendChild(confirm_value);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<table width="100%">
<tr>
<td align="center" valign="top">
<table cellspacing="5">
<tr>
<td align="left" valign="top"><strong>Options : </strong>
<asp:RadioButtonList ID="RadioButtonListoptions" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="1">Execute Directly</asp:ListItem>
<asp:ListItem Value="2">Display In Gridview</asp:ListItem>
<asp:ListItem Value="3">Display On Label</asp:ListItem>
</asp:RadioButtonList> <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Select option" ControlToValidate="RadioButtonListoptions" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator></td>
</tr>
<tr>
<td align="left" valign="top">
<asp:TextBox ID="TextBoxQuery" runat="server" TextMode="MultiLine" Height="400px" Width="800px" placeholder="Enter query..." Font-Size="Large" Text="" Style="padding: 5px;"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Enter your query" ControlToValidate="TextBoxQuery" Display="Dynamic" SetFocusOnError="true" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td align="center">
<asp:Button ID="ButtonSubmitQuery" runat="server" Text="Submit" Width="200px" Height="30px" OnClick="ButtonSubmitQuery_Click" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td align="center" valign="top">
<asp:Label ID="LabelShowData" runat="server" Text="Label Here"></asp:Label>
<asp:GridView ID="GridViewData" runat="server" AutoGenerateColumns="true" EmptyDataText="No record found."></asp:GridView>
<asp:SqlDataSource ID="SqlDataSourceData" runat="server"></asp:SqlDataSource>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
C#:
protected void ButtonSubmitQuery_Click(object sender, EventArgs e)
{
if (RadioButtonListoptions.SelectedIndex != -1)
{
if (Convert.ToInt32(RadioButtonListoptions.SelectedItem.Value.ToString()) == 1)
{
if (!TextBoxQuery.Text.ToString().Contains("Where"))
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsgwithYesNo('Entered query did not have WHERE condition.');", false);
//ClientScript.RegisterClientScriptBlock(this.GetType(), "UpdateTime", "alertmsgwithYesNo('Query did not have WHERE Condition. Do you want to run it without Where Con');", true);
string confirmValue = Request.Form["confirm_value"];
Label1.Text = confirmValue;
return;
}
using (SqlConnection conn = new SqlConnection(vali.constr))
{
try
{
using (SqlCommand cmdsql = new SqlCommand(TextBoxQuery.Text.Trim()))
{
conn.Open();
int count = cmdsql.ExecuteNonQuery();
if (count > 0)
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsg('Select Option');", false);
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
finally
{
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
}
}
}
}
else
{
ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "message", "alertmsg('Select Option');", false);
return;
}
}
I have an asp.net page that contain some textbox in ListView
I want to disable textbox that have some text by asp.net ItemDataBound ListView Event or Javascript code
How can i do that?
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ID" >
<ItemTemplate>
<tr class="xl68" height="29" style='mso-height-source: userset; height: 21.75pt'>
<td > <asp:Label ID="lblID" runat="server" Visible="false" Text='<%# Eval("ID") %>'></asp:Label></td>
<td class="xl66" style='border-top: none'><%# Container.DataItemIndex + 1 %> </td>
<td class="xl69" width="351" style='border-top: none; border-left: none; width: 263pt'> <%# Eval("Name") %></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C1") %>' ID="txb1" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C2") %>' ID="txb2" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C3") %>' ID="txb3" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C4") %>' ID="txb4" ></asp:TextBox></td>
<td><asp:TextBox runat="server" MaxLength="2" Text='<%# Bind("C5") %>' ID="txb5" ></asp:TextBox></td>
<td class="xl67"> </td>
</tr>
</ItemTemplate>
</asp:ListView>
add the CssClass property with every TextBox control like this
<asp:TextBox runat="server" MaxLength="2" ID="txb1" CssClass="myCss" ></asp:TextBox>
add the Js function in aspx
function DisableInput(){
var inputs = $('input.myCss[type="text"]');
inputs.each(function( index )
{
if( $( this ).text() !='')
{
$( this ).attr('disabled',true);
}
});
}
On you Page_Load event add this code
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:DisableInput(); ", true);
On you Page_Load event add this code
ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:disablewithText(); ", true);
In that javaScript function you can iterate through all the textboxes and check for having value and accordingly you can set disable attribute.
I Solved it in CodeBehind by this code in Page_Load Event
foreach (ListViewItem row in ListView1.Items)
{
foreach (Control txt in row.Controls)
{
if (txt is TextBox)
{
if (((TextBox)txt).Text != "")
((TextBox)txt).Enabled = false;
}
}
}
I am having trouble setting panel visibility
but on change JavaScript returning null reference exception.
JavaScript runtime error: Unable to get property 'setAttribute' of undefined or null reference
I want to make panel TrMarketingDetails visible based on a radio button (RbMarketing) change.
JavaScript
function trVisible(val) {
var selected = $("#" + val.id + " input:radio:checked").val();
if (selected == "1") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').setAttribute("style", "visibility: visible");
document.getElementById('<%= hfdMarket.ClientID %>').value = 'Y';
}
else if (selected == "2") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').setAttribute("style", "visibility: hidden");
}
}
AXPX Code
<tr>
<td style="font-weight: bold" align="left" class="style4">
Marketing facilities available
</td>
<td style="font-weight: bold" class="style23">
<asp:RadioButtonList ID="RbMarketing" runat="server" DataTextField="Yes" onchange="trVisible(this);"
RepeatDirection="Horizontal">
<asp:ListItem Text="Yes" Value="1"></asp:ListItem>
<asp:ListItem Text="No" Value="2"></asp:ListItem>
</asp:RadioButtonList>
<asp:HiddenField ID="hfdMarket" runat="server" />
<%--OnSelectedIndexChanged="RbMarketing_SelectedIndexChanged" AutoPostBack="True"--%>
</td>
</tr>
<asp:Panel ID="TrMarketingDetails" runat="server" Style="visibility: hidden" EnableViewState="true">
<tr>
<%--visible="false"--%>
<td runat="server" style="border: none;" class="style7" align="left">
Details :
</td>
<td runat="server" style="border: none;" class="style26" align="left">
<asp:TextBox ID="TextMarketingDetails" runat="server" CssClass="textboxCss" autocomplete="off"
MaxLength="100" Enabled="True" ondrop="return false;" Width="300px" TextMode="MultiLine"></asp:TextBox>
<asp:RequiredFieldValidator ID="Requiredfieldvalidator49" runat="server" Display="None"
ControlToValidate="TextMarketingDetails" ValidationGroup="grp1" ForeColor="#F00000"
SetFocusOnError="true" ErrorMessage="Please enter Marketing details" Enabled="false"></asp:RequiredFieldValidator>
<asp:ValidatorCalloutExtender ID="ValidatorCalloutExtender3" runat="server" PopupPosition="Right"
TargetControlID="Requiredfieldvalidator49">
</asp:ValidatorCalloutExtender>
</td>
</tr>
</asp:Panel>
W3C link for style.visibility
document.getElementById("controlid").style.visibility = "hidden"
you just change like
function trVisible(val) {
var selected = $("#" + val.id + " input:radio:checked").val();
if (selected == "1") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').style.visibility = "visible";
document.getElementById('<%= hfdMarket.ClientID %>').value = 'Y';
}
else if (selected == "2") {
document.getElementById('<%=TrMarketingDetails.ClientID %>').style.visibility = "hidden";
}
}
You are already use jquery syntax in your code, then good to do this via jquery syntax like
$('#<%=TrMarketingDetails.ClientID %>').show();
$('#<%=TrMarketingDetails.ClientID %>').hide();
Check this link with same question
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>
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.