How to find text-box in GridView using Javascript - c#

I am trying to get access and find text-box in GridView using javascript but i am getting an error: 'The name txt_UID' does not exist in the current context'. Everything worked fine when my text-box was outside of the GridView. Here is my text-box in the gridview and my gridview is called GridView1:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Assigned">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
Here is my JavaScript:
<script type ="text/javascript">
function setAutoComplete() {
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++) {
addAutoComplete(textBoxes[i].id);
}
}
</script>
<script type="text/javascript">
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
<script type ="text/javascript">
$(document).ready(function () { setAutoComplete(); });
</script>

The problem is your GridView creates a TextBox on each row. There is no "txt_UID" control outside of the GridView. That is what your error message is telling you.
Your JavaScript function is designed to work with one TextBox. I imagine you want the AutoComplete to work on ALL TextBox controls in the GridView.
My suggestion would be to change the JavaScript function to take a parameter with the TextBox ID and then add a CSS class to each TextBox, and finally make a wrapper JavaScript function that will enumerate the TextBox controls using getElementsByClassName, and call that wrapper function on DOM ready.
Here's what it will look like:
Add CSS class to the TextBoxes:
<asp:TemplateField ItemStyle-Width="150px" HeaderText="User Name">
<ItemTemplate>
<asp:TextBox ID="txt_UID" runat="server" Text='<%# Eval("UID")%>'
CssClass="AutoCompleteTextBox" Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="150px" />
</asp:TemplateField>
New JavaScript function:
function setAutoComplete()
{
var textBoxes = document.getElementsByClassName("AutoCompleteTextBox");
for (var i = 0; i < textBoxes.length; i++)
{
addAutoComplete(textBoxes[i].id);
}
}
Next, make your other JavaScript into a function that takes a parameter (the id):
function addAutoComplete(textBoxId) {
$("#" + textBoxId).autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetUserNames") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
select: function (e, i) {
$("#<%=hfUserId.ClientID %>").val(i.item.val);
},
minLength: 1
});
};
Finally, your on ready code changes to just call the wrapper function you created:
$(document).ready(function () { setAutoComplete(); });
Bonus: Here's a way to do it with jQuery only:
(just requires the CSS class on the TextBoxes)
$(document).ready(function () {
$.each($(".AutoCompleteTextBox"), function (i, textBox) {
textBox.autocomplete( /* your code */);
})
});

Your Gridview will be rendered as Table and your control will be contained in cell of table. You can give a try to following.
<script type=”text/javascript”>
$(document).ready(function(){
tblTable=document.getElementById(‘<<Client ID of the GridView>>’);
Cell=tblTable.rows[i].cells[j];//i and j are locations of that cell.
FirstControl = Cell.childNodes[0];
});
</script>
replace <<Client ID of the GridView>> with id of your GridView

you can use name attribute and the grid id to find it:
<asp:TextBox ID="txt_UID" name="mytextbox" runat="server" Text='<%# Eval("UID")%>'
Width="130px" BackColor="LightGoldenrodYellow"></asp:TextBox>
the javascript part:
$("#<%=MyGrid.ClientID %>[name=mytextbox]").autocomplete({});

Related

How To get Selected Tex from asp.net Dropdown codeBehind After Bind through JQuery Ajax Calling

I have Bind asp.net dropDwon by Jquery ajax Call .now i want selected text from code behind.
How?
<asp:DropDownList runat="server" ID="DropdownCounty" DataValueField="id" DataTextField="name" AppendDataBoundItems="True" onchange="populateState();">
</asp:DropDownList>
$.ajax({
type: "POST",
url: "webservice/WebService1.asmx/getCountry",
contentType: "application/json; charset=utf-8",
dataType: 'JSON',
success: function (response) {
$("#DropdownCounty").empty();
$("#DropdownCounty").append('<option value="0">Please select</option>');
$.each(response.d, function (key, value) {
$("#DropdownCounty").append($("<option></option>").val(value.id).text(value.name));
})
},
failure: function (response) {
alert(response.d);
}
});
Code behind
var dasd = DropdownCounty.SelectedValue;
Show us your code for a better reply but I think you you can try
var value =yourDropDownList.SelectedValue

How to perform searching in autofill on textbox with single enter press

<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" ></asp:TextBox>
</div>
<br>
<script type="text/javascript">
$(function fnc() {
$(".search_hot_txtbox").autocomplete({
source: function(request, response) {
$.ajax({
url: "hotel-result.aspx/BindDatatoDropdown",
data: "{ 'cn': '" + request.term + "' }",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
dataFilter: function(data) { return data; },
success: function(data) {
response($.map(data.d, function(item) {
return {
value: item.HotelName
}
}))
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
// alert(textStatus);
}
});
},
minLength: 2
});
});
</script>
protected void chk3_CheckedChanged(object sender, EventArgs e)
{
if (Session["List"] != null)
UCPager1.GetItemsControl(1, 5, 0, chk3star.Checked, chk2star.Checked, chk1star.Checked, chk4star.Checked, chk5star.Checked, chkP1.Checked, chkP2.Checked, chkP3.Checked, chkP4.Checked, chkP5.Checked, txtHotel.Text, spP1.InnerText, spP2.InnerText, spP3.InnerText, spP4.InnerText, spP5.InnerText, new Repeater(), chkP6.Checked, chkP7.Checked, chkP8.Checked, spP6.InnerText, spP7.InnerText, spP8.InnerText);
else
UCPager1.GetItems();
}
You need here to make a post back, when you press "enter" on the textbox the browser make the postback, but if you wish to make it with javascript you need to fire up a button control.
So I place a button control, and I can even have it hidden with css as:
<div style="position: absolute; top: 841px; left: 12%;">
<asp:TextBox ID="txtHotel" runat="server" CssClass="search_hot_txtbox" onkeydown="return SendKeyEnterTo(event, 'btnGo');" />
<asp:Button runat="server" ID="btnGo" Text="search" onclick="btnSearch_Click" style="display:none;" ClientIDMode="Static" />
</div>
and then using this simple javascript I read the "enter" key from the textbox and trigger that post back of the input control.
function SendKeyEnterTo(e, IdToClick)
{
// look for window.event in case event isn't passed in
if (window.event)
{
e = window.event;
}
if (e.keyCode == 13)
{
document.getElementById(IdToClick).click();
return false;
}
else
{
return true;
}
}
This onkeydown="return SendKeyEnterTo(event, 'btnGo');" is important to read the text box input, and the ClientIDMode="Static" on the button is important to keep the same id when its rendered.
Also, please note, this code is run together with the autocomplete, and I have tested and use it.

Jquery Auto complete extender not working after postback

Im using jQuery Autocomplete using Web Service in ASP.Net.I've used the autocomplete to filter employeecode.When the page loads autocomplete works fine,but after when i click the search button autocomplete is not working properly.
I think the problem lies in document.ready function,so when the page loads it works fine,But i've to use autocomplete after the buttonclick event also.
How can i do this ???
Heres my jQuery Autocomplete
<link href="../AutoComplete/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../AutoComplete/jquery.min.js" type="text/javascript"></script>
<script src="../AutoComplete/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
});
</script>
Markup
<td align="right">
<asp:Label ID="lblEmpCodeSrch" runat="server" Text="EmpCode" CssClass="label"> </asp:Label>
</td>
<td>
<asp:TextBox ID="txtEmpCodeSrch" runat="server" Width="250px" ToolTip="Enter Employeecode"></asp:TextBox>
<asp:Button ID="bttnSearch" runat="server" CssClass="submit" Height="23px" Text="Search" onclick="bttnSearch_Click" />
</td>
ButtonSearch Codebehind
protected void bttnSearch_Click(object sender, EventArgs e)
{
clsEmp.EMPLOYEEID =txtEmpCodeSrch.Text.Trim()==""? 0:Convert.ToInt32(hFieldEmpId.Value);
DataTable dtEmp = clsEmp.GetDetails();
if (dtEmp.Rows.Count > 0)
{
hFieldEmpId.Value = "";
// txtEmpCodeSrch.Text = "";
if (ViewState["Sort"] != null)
{
DataView dView = new DataView(dtEmp);
dView.Sort = ViewState["Sort"].ToString();
gdView.DataSource = dView;
gdView.DataBind();
}
else
{
gdView.DataSource = dtEmp;
gdView.DataBind();
}
}
}
When you have an UpdatePanel, after the update of the data, you also need to re-initialize the javascript, because the old one is not longer working, because the struct of your html page have change, the dom have change.
The UpdatePanel is giving some function to do that on client side, and your code will be as:
<script type="text/javascript">
// if you use jQuery, you can load them when dom is read.
$(document).ready(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
// Place here the first init of the autocomplete
InitAutoCompl();
});
function InitializeRequest(sender, args) {
}
function EndRequest(sender, args) {
// after update occur on UpdatePanel re-init the Autocomplete
InitAutoCompl();
}
function InitAutoCompl() {
$("#<%=txtEmpcode.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/MyWebService.asmx/FetchEmpCode") %>',
data: "{ 'Empcode': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[1],
//val: item
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
minLength: 1
});
}
</script>
I tell you that I could solve the problem by adding a Triggers within the UpdatePanel tag, thus achieves the desired behavior in my case. I hope you can serve you as me helped me.
<ajax:UpdatePanel>
<ContentTemplate>
//My label fire autocomplete
<asp:TextBox id="MyLabelForAutoComplete" runat="server"/>
// Other Html Tags...
<Triggers>
<ajax:PostBackTrigger ControlID="MyLabelForAutoComplete">
</Triggers>
</ajax:UpdatePanel>

AutoPopulate DropDownList Using Ajax

I have 2 dropdownlist which is already binded on pageload , i want to rebind these two dropdownlist after firing a ajax function.Here i have written a sql server stored procedure to get the data which is needed to dropdownlists.But how i will get the value to dropdownlist,so that it can bind the new data using ajax function.The screen is developed by using Asp.net C# coding.
Here is the drop down list of the asp.net
<asp:DropDownList id="ddlCourse" runat="server" AutoPostBack="false"
Height="28px" title="Select Course" Width="290px"
></asp:DropDownList>
and here is the jquery method that is calling the web service method
function BindCourse() {
$.ajax({
type: "POST",
url: "/WebService/CollegeWebService.asmx/GetCourseDetails",
data: "{}",
async: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnCoursePopulated,
error: function (xml, textStatus, errorThrown) {
alert('error');
alert(xml.status + "||" + xml.responseText);
}
});
}
This is the method to That is used in the ajex call method and call the PopulateControl method to bind the Drop down List
function OnCoursePopulated(response) {
PopulateControl(response.d, $('#<%=ddlCourse.ClientID %>'));
}
Here is the description of the PopulateControl Method
function PopulateControl(list, control) {
if (list.length > 0) {
control.removeAttr("disabled");
control.empty().append('<option selected="selected" value="0">Please select</option>');
$.each(list, function () {
control.append($("<option></option>").val(this['Value']).html(this['Text']));
});
}
else {
control.empty().append('<option selected="selected" value="0">Not available<option>');
}
}
Thus you finally bind the drop down list
You can try the following as a demo. Server side DropDownLists are replaced with HTML select elements so that exception "Invalid postback or callback argument" doesn't happen.
Drawback in this demo is that the values are not restored on form after postback. You can put this inside a form in Default.aspx:
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
function populate(populateInitial) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '/Default.aspx/populate',
data: "{'populateInitial': '" + populateInitial + "'}",
dataType: "json",
async: false,
success: function(result) {
var ddlItems = document.getElementById('ddlItems');
ddlItems.options.length = 0;
$.each(result.d, function(key, item)
{ ddlItems.options[key] = new Option(item); });
}
});
}
</script>
<form id="form1" runat="server">
<div>
<select id="ddlItems" name="ddlItems">
</select>
<br />
<input type="button" onclick="populate('0');" value="Change values" />
<br />
Selected item:
<asp:Label ID="lblSelectedItem" runat="server" Text=""> </asp:Label>
<br />
<asp:Button ID="Button1" runat="server"
Text="Write out selected item text" />
</div>
<script type="text/javascript">
populate('1');
</script>
And you put these methods inside Default.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
lblSelectedItem.Text = Request["ddlItems"].ToString();
}
}
[System.Web.Services.WebMethod()]
[System.Web.Script.Services.ScriptMethod()]
public static List<string> populate(string populateInitial)
{
if (populateInitial == "1")
return (new string[] { "a", "b" }).ToList();
else
return (new string[] { "c", "d", "e", "f" }).ToList();
}
You should make Ajax call to some sort of page (I advice you to add Generic Hanlder) which responses xml or json or even html, of drop down values and textfield values, than read it in javascript jquery and generate html for your drop down which is the following
<select id="ddl">
<option value="value">text</option>
</select>
you should read "value" & text and generate this> <option value="value">text</option>
and append to ddl

Calling WebMethod via jQuery from JavaScript on ASCX, needing value of Control

I understand how to use jQuery to make an AJAX call to a WebMethod from a normal page, but I'm running into problems doing it from a UserControl (ASCX). Right now the biggest Issue I'm having is that the JavaScript for getting access to the groupDropDown control is not working. It seems that since this is a UserControl hosted within DotNetNuke, the ususal method of getting the CLientID is not working since it is nested down x number of levels. Here is what I have:
Javascript:
function validateEnrolledDate(src, args) {
var isValid;
var groupDropDown = document.getElementById('<%= ddlDealer.ClientID %>');
$.ajax({
type: "POST",
url: "ajaxservice.asmx/ValidateEnrolledDate",
data: "{orderDate: '" + args.Value + "', groupId: '" + groupId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function (msg) {
alert(msg);
isValid = msg.d;
},
failure: function () {
alert("FAIL");
}
});
args.IsValid = isValid;
Validator User Control that calls this JavaScript:
<asp:CustomValidator id="CustomValidator1" runat="server" ControlToValidate="rdiDate" ErrorMessage="Fail" OnServerValidate="CustomValidator1_ServerValidate" ValidationGroup="vgce" CssClass="validation" Display="Dynamic" Text="*" ClientValidationFunction="validateEnrolledDate" />
groupDropDown I'm trying to get a value from:
<asp:DropDownList ID="ddlDealer" runat="server" CssClass="dropdownlist theDealer" TabIndex="3" AutoPostBack="true" OnSelectedIndexChanged="ddlDealers_Changed" />
WebMethod:
[WebMethod()]
private bool ValidateEnrolledDate(string orderDate, string groupId)
{
DateTime enrolledDate = new Service().GetEnrollmentDate(int.Parse(groupId));
if (DateTime.Parse(orderDate) >= enrolledDate)
{
return true;
}
else
{
return false;
}
}
TIME TO SIMPLIFY:
Here is testing JS Code:
function validateEnrolledDate(src, args) {
var isValid;
var selectedGroup = $("theDealer").val();
alert(selectedGroup);
}
I'm now just referencing a TextBox:
<asp:TextBox ID="dealerId" runat="server" CssClass="theDealer" />
The Text in the Textbox is being set in Server Side code, and it is visible on screen.
The alert message is "undefined", so something is still happening so that it is not getting the value of that textbox...
If you are having trouble getting the value of the drop down list the easist approach would be to assign a class to the control.
<asp:DropDownList ID="ddlUsers" runat="server" CssClass="dropdownlist theUsers" TabIndex="5" AutoPostBack="true" OnSelectedIndexChanged="ddlUsers_SelectedIndexChanged" Enabled="false" />
and than in your method.
var selectedUser = $("theUsers option:selected").val();

Categories

Resources