How do you check if the two dates are in a same month and year? And which validation control should I use to have this? I'm thinking of using client-side validation (if it's possible)
Thanks!
You could use a CustomValidator
aspx:
<asp:CustomValidator runat="server"
ID="valMonth"
onservervalidate="ServerValidation"
onclientvalidate="ClientValidate"
ErrorMessage="From and To must be in the same month" />
servervalidate:
protected void ServerValidation (object source, ServerValidateEventArgs args)
{
DateTime dtFrom;
DateTime dtTo;
if(DateTime.TryParse(TxtFrom.Text, out dtFrom) && DateTime.TryParse(TxtTo.Text, out dtTo))
{
args.IsValid = dtFrom.Year == dtTo.Year && dtFrom.Month == dtTo.Month;
}
else
{
args.IsValid = false;
}
}
You should also add two CompareValidators which check if both are valid dates.
To provide a ClientValidationFunction you can have a look at the getMonth and getFullYear functions.
For example(not tested):
<script language="javascript">
<!--
function ClientValidate(source, arguments)
{
var txtFrom = document.getElementById('<%= TxtFrom.ClientID %>');
var txtTo = document.getElementById('<%= txtTo.ClientID %>');
var dtFrom = new Date(txtFrom.value);
var dtTo = new Date(txtTo.value);
var monthFrom = dtFrom.getMonth();
var monthTo = dtTo.getMonth();
var yearFrom = dtFrom.getFullYear();
var yearTo = dtTo.getFullYear();
arguments.IsValid = yearFrom == yearTo && monthFrom == monthTo;
}
// -->
</script>
Assuming the date is in "dd/MM/yyyy" format, you could use this javascript function with a custom validator.
aspx
<asp:CustomValidator ID="CustomValidator1" runat="server"
EnableClientScript="true"
ErrorMessage="ERROR MESSAGE HERE"
ClientValidationFunction="checkDate">
</asp:CustomValidator>
javascript
function checkDate() {
var date1=document.getElementById('<%=txtDate1.ClientID%>').value;
var date2=document.getElementById('<%=txtDate1.ClientID%>').value;
var date1Values=date1.split("/");
var date2Values=date2.split("/");
if (date1Values[2] == date2Values[2] && date1Values[1] ==date2Values[1]) {
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}
You should have server validate code too if javascript is disabled. See Tim's answer.
Here's a short and simple example using a CustomValidator control
Date 1<asp:TextBox ID="txtDate1" runat="server" />
<br />
Date 2<asp:TextBox ID="txtDate2" runat="server" />
<br />
<asp:Button ID="btnCompare" runat="server" Text="Compare" />
<asp:CustomValidator ID="dateValidator" runat="server" ErrorMessage="The two dates must be in the same month and year"
OnServerValidate="ValidateDate" />
<script runat="server">
protected void ValidateDate(object source, ServerValidateEventArgs args)
{
DateTime date1 = DateTime.Parse(txtDate1.Text);
DateTime date2 = DateTime.Parse(txtDate2.Text);
if (date1.Month != date2.Month || date1.Year != date2.Year)
args.IsValid = false;
}
</script>
Related
I am using a customValidator to validate whether a date is within a valid range or not within a textbox. It works great if you manually enter in a date and calls my custom ClientValidationFunction. Unfortunately if i use a popup calendar to select a date my customValidator is not triggered.
I was hoping to get a better understanding on how asp:CustomValidators are triggered.
I've tried to force input validation to re-validate when the calendar is closed but have had no luck.
<asp:CustomValidator ID="ValidDateCheck" runat="server" ControlToValidate="txtDate" ErrorMessage="Please enter a valid date." ClientValidationFunction="clientValidate"
EnableClientScript="True" Display="Dynamic" CssClass="dateboxRJS-validator text-danger" ValidateEmptyText="true"></asp:CustomValidator>
Javascript
clientValidate = function (source, args) {
console.log("validating...");
var s = document.getElementById(source.controltovalidate);
var minDate = moment("1900-01-01");
var maxDate = moment().add(200, 'y');
var inputDate;
if (moment(s.value, "MM/DD/YYYY", true).isValid()) {
inputDate = moment(s.value, "MM/DD/YYYY");
console.log(s.value);
console.log("break");
if (!inputDate.isBetween(minDate, maxDate)) {
args.IsValid = false;
s.classList.add("is-invalid");
Page_BlockSubmit = true;
return false;
} else {
s.classList.remove("is-invalid");
args.IsValid = true;
Page_BlockSubmit = false;
return true;
}
}
}
});
I want to change the header text of the gridview using Design..
<asp:BoundField HeaderText="">
i created a variable in javascript and initialize variable defending on the condition and then i tried to call that variable over here as below:
<asp:BoundField HeaderText="Text Here" DataField="slno" >
here I use "text here" string stored in one variavble name . and i want to use that variable
My code :
<script type="text/javascript" language="javascript">
/// <summary>
/// TO ACCESS COOKIE VARIABLE
/// </summary>
var flag;
var ca = document.cookie.split('=');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ',') c = c.substring(1);
}
if (c != '' && c != null) {
flag = c;
}
else {
flag = 1;
}
//*********************************************
if (flag == 1) {
var name_lbl = "Hai";
}
else if (flag == 2) {
var name_lbl = "How are you?";
}
</script>
//------------------------------------------------
</asp:Content>
<form id="form1" runat="server">
</table>
<div style="overflow: auto; height: 99%;" id="divTable">
<table><tr><td>
<label for='field ID'> <b><input type="text" id="kilist_lbl" size="20" style="border: none; height:20px" readonly/></b> </label> <br />
</td></tr></table>
<asp:GridView ID="gvareadetails" runat="server"
CssClass="mGrid" AutoGenerateColumns="False">
<Columns>
<%-- here is the problem when assigning ID to headerText label --%>
<asp:BoundField HeaderText='sss' DataField="slno" >
<ItemStyle Width="5%" />
</asp:BoundField>
</Columns>
</asp:GridView>
</div>
</form>
<script type="text/javascript" language="javascript">
document.getElementById('sss').value = name_lbl;
</script>
</asp:Content>
Any one have any suggestions how this could be achieved..
Instead of js, just try the C# code to get values from the grid view.
ex:
int name_lbl = gvareadetails.Columns[0][0];
Here Columns[0][0] gives you the first row first column value.
C# code to get values from the grid view:
string name_lbl;
protected void Page_Load(object sender, EventArgs e)
{
//---------------------------------------------
/// </summary>
/// /// <summary>
/// TO ACCESS COOKIE VARIABLE
/// </summary>
string b;
HttpCookie a = Request.Cookies["LangaugaeObj"];
if (a != null) b = a.Value; else b = "1";
if (b == "1")
{
name_lbl = "Hai";
}
else
{
name_lbl = "How are you";
}
//---------------------------------------------------
protected void Button1_Click(object sender, EventArgs e)
{
// here I set the variable name to the grid Header
gvareadetails.Columns[0].HeaderText = name_lbl;
Report report = new Report();
report.areaid = hidStatus.Value.ToString();
DataSet ds = report.getareawisedetails();
gvareadetails.DataSource = ds;
gvareadetails.DataBind();
ds.Dispose();
ds = null;
report = null;
}
Thank You for Shaji SS for his suggestion.. I hope this answer will help to someone who looking for- set the header text dynamically in asp.net using asp:BoundField.
I am having trouble with my GridView RowDataBound event after I click on Save to save the data to the database.
I have a grid with 5 columns: Tag Name, Current Timestamp, Current Value, New Date, New Value.
The idea is the user will enter into the New Date/New Value to update the data in the database. The Current Timestamp and Current Value are what is already stored in the database.
I use a JQuery editor to enter the date.
When I click on Save, I have server side validation in place to check the entered values. If the data is valid, a message under the text in the New Value column is displayed to indicate this. If the validation fails, then a message in the New Value column is displayed.
New Date and New Value columns are TemplateField's. The New Value TemplateField contains a panel with two labels - one for OK status and the other for error.
The error occurs in MyDataGrid_RowDataBound when I call any e.Row.FindControl(...) which is triggered from the Save button click when I rebind.
It works ok if a valid value has been entered but if an invalid value is entered then it errors. In order to simplify the scenario, enter 100 for a valid value and anything else for an invalid.
This WebForm has been the trouble of my life. Maybe I shouldn't have used a GridView.
Anyway, I would appreciate any help here to identify the issue. And maybe a better approach to the form code.
I've took the code from my solution and moved it into a standalone solution to reproduce the issue. I've removed the database access and populated a datastructure. This is only ever done (once) in the Page Load when the page is initially loaded.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="Styles/jquery-ui-timepicker-addon.css" />
<link rel="stylesheet" href="Styles/jquery-ui-1.10.1.custom.css" />
<link rel="stylesheet" href="Styles/jquery-ui-1.10.1.custom.min.css" />
<script src="Scripts/jquery-1.9.1.js"></script>
<script src="Scripts/jquery-ui-1.10.1.custom.js"></script>
<script src="Scripts/jquery-ui-1.10.1.custom.min.js"></script>
<script src="Scripts/jquery-ui-timepicker-addon.js"></script>
</head>
<body>
<script type="text/javascript">
/** Disable backkey */
$(document).unbind('keydown').bind('keydown', function (event) {
var doPrevent = false;
if (event.keyCode === 8) {
var d = event.srcElement || event.target;
if ((d.tagName.toUpperCase() === 'INPUT' && (d.type.toUpperCase() === 'TEXT' || d.type.toUpperCase() === 'PASSWORD' || d.type.toUpperCase() === 'FILE'))
|| d.tagName.toUpperCase() === 'TEXTAREA') {
doPrevent = d.readOnly || d.disabled;
} else {
doPrevent = true;
}
}
if (doPrevent) {
event.preventDefault();
}
});
$(function () {
$(".datetimepicker").datetimepicker({
changeMonth: true,
changeYear: true
});
});
$(function () {
$(".datepicker").datepicker({
changeMonth: true,
changeYear: true
});
});
$(function () {
$(".timepicker").timepicker({ showTimezone: false });
});
</script>
<form id="form1" runat="server">
<div>
<asp:GridView ID="MyDataGrid" runat="server"
EnableModelValidation="True"
DataKeyNames="Id"
AutoGenerateColumns="False"
AutoGenerateSelectButton="False"
EmptyDataText="There is no plant data configured."
OnRowDataBound="MyDataGrid_RowDataBound">
<Columns>
<asp:BoundField DataField="Name" SortExpression="Name" HeaderText="Tag Name"></asp:BoundField>
<asp:BoundField DataField="Date" SortExpression="Date" HeaderText="Current Timestamp"></asp:BoundField>
<asp:BoundField DataField="Value" SortExpression="Value" HeaderText="Current Value"></asp:BoundField>
<asp:TemplateField HeaderText="New Date<BR/>MM/DD/YYYY HH:MM">
<ItemTemplate>
<asp:TextBox ID="txtNewDate" runat="server" CssClass="datetimepicker"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="New Value">
<ItemTemplate>
<asp:TextBox ID="txtNewValue" runat="server"></asp:TextBox>
<asp:Panel ID="ErrorPanel" runat="server">
<br />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
<asp:Label ID="lblStatus" runat="server" ForeColor="#66cc00"></asp:Label>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="SaveButton" runat="server"
Text="Save Values"
ToolTip="Save the current changes."
OnClick="SaveButton_Click" />
</div>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
private const int COL_NEW_DATE = 3;
private const int COL_NEW_VALUE = 4;
bool canEdit = true;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
PopulateDataGrid();
}
}
private void PopulateDataGrid()
{
// this is where i load from the database
List<RowData> data = new List<RowData>() {
new RowData() { Date = new DateTime(2000,1,1), Editable = true, Name = "Data Item 1", Value = 100.0 },
new RowData() { Date = new DateTime(2000,1,1), Editable = false, Name = "Data Item 2", Value = 120.0 },
new RowData() { Date = new DateTime(2000,1,1), Editable = true, Name = "Data Item 3", Value = 19.0 }
};
this.MyDataGrid.DataSource = data;
this.MyDataGrid.DataBind();
ViewState["GridData"] = this.MyDataGrid.DataSource;
}
private void SaveData()
{
for (int i = Page.Validators.Count - 1; i >= 0; i--)
Page.Validators.Remove(Page.Validators[i]);
ValidateData();
List<RowData> rowDataList = (List<RowData>)ViewState["GridData"];
if (this.IsValid)
{
foreach (GridViewRow row in this.MyDataGrid.Rows)
{
if (row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow && row.Enabled)
{
RowData dataItem = rowDataList[row.DataItemIndex];
var txtNewValue = row.Cells[COL_NEW_VALUE].FindControl("txtNewValue") as TextBox;
var txtNewDate = row.Cells[COL_NEW_DATE].FindControl("txtNewDate") as TextBox;
if (dataItem != null && txtNewDate != null && txtNewValue != null && !string.IsNullOrEmpty(txtNewValue.Text) && !string.IsNullOrEmpty(txtNewDate.Text))
{
var newValue = double.Parse(txtNewValue.Text);
var newDate = DateTime.Parse(txtNewDate.Text);
dataItem.InfoText = "Value written successfully for " + txtNewDate.Text;
dataItem.ErrorText = string.Empty;
dataItem.EnteredDateCache = string.Empty;
dataItem.EnteredValueCache = string.Empty;
if ((dataItem.Date.HasValue && DateTime.Compare(newDate, dataItem.Date.Value) >= 0) || !dataItem.Date.HasValue)
{
dataItem.Date = newDate;
dataItem.Value = newValue;
}
}
}
}
// save any outstanding changes if valid removed from demo
}
ViewState["GridData"] = rowDataList;
}
private void ValidateData()
{
List<RowData> rowDataList = (List<RowData>)ViewState["GridData"];
foreach (GridViewRow row in this.MyDataGrid.Rows)
{
if (row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow && row.Enabled)
ValidateDataRow(rowDataList, row);
}
}
private void ValidateDataRow(List<RowData> rowDataList, GridViewRow gridViewRow)
{
RowData rowData = rowDataList[gridViewRow.DataItemIndex];
bool valueOK = false;
var txtNewValue = gridViewRow.Cells[COL_NEW_VALUE].FindControl("txtNewValue") as TextBox;
var txtNewDate = gridViewRow.Cells[COL_NEW_DATE].FindControl("txtNewDate") as TextBox;
var labelError = gridViewRow.Cells[COL_NEW_VALUE].FindControl("lblError") as Label;
var labelInfo = gridViewRow.Cells[COL_NEW_VALUE].FindControl("lblStatus") as Label;
labelInfo.Text = string.Empty;
labelError.Text = string.Empty;
rowData.InfoText = string.Empty;
rowData.ErrorText = string.Empty;
rowData.EnteredDateCache = txtNewDate.Text;
rowData.EnteredValueCache = txtNewValue.Text;
if (rowData != null && (!string.IsNullOrEmpty(txtNewValue.Text) || !string.IsNullOrEmpty(txtNewDate.Text)))
{
if (!txtNewValue.Text.IsNumber())
{
rowData.ErrorText = rowData.Name + " must be a number.";
AddCustomValidatorForCell(rowData.ErrorText, gridViewRow, 4);
}
else
{
if (txtNewValue.Text != "100")
{
rowData.ErrorText = rowData.Name + " is invalid.";
AddCustomValidatorForCell(rowData.ErrorText, gridViewRow, 4);
}
else
{
valueOK = true;
}
}
}
}
private void AddCustomValidatorForCell(string errorMessage, GridViewRow gridViewRow, int cellIndex)
{
var labelError = gridViewRow.Cells[cellIndex].FindControl("lblError") as Label;
var divInfoError = gridViewRow.Cells[cellIndex].FindControl("ErrorPanel") as Panel;
labelError.Text = errorMessage;
labelError.ToolTip = errorMessage;
labelError.Attributes.Add("style", "color: red;");
CustomValidator validatePower = new CustomValidator()
{
IsValid = false,
ErrorMessage = errorMessage,
EnableViewState = false,
};
Page.Validators.Add(validatePower);
}
protected void SaveButton_Click(object sender, EventArgs e)
{
SaveData();
this.MyDataGrid.DataSource = ViewState["GridData"];
this.MyDataGrid.DataBind();
}
protected void MyDataGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
var rowData = e.Row.DataItem as RowData;
if (rowData != null)
{
DataControlFieldCell txtNewDate = (DataControlFieldCell)e.Row.Cells[COL_NEW_DATE];
DataControlFieldCell txtNewValue = (DataControlFieldCell)e.Row.Cells[COL_NEW_VALUE];
e.Row.Cells[1].Text = rowData.Date.HasValue ? rowData.Date.ToString() : string.Empty;
e.Row.Cells[2].Text = rowData.Value.HasValue ? rowData.Value.Value.ToString() : string.Empty;
txtNewValue.Enabled = txtNewDate.Enabled = (canEdit & rowData.Editable);
if (!string.IsNullOrEmpty(rowData.EnteredDateCache))
txtNewDate.Text = rowData.EnteredDateCache;
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
txtNewValue.Text = rowData.EnteredValueCache;
(e.Row.FindControl("lblStatus") as Label).Text = rowData.InfoText;
(e.Row.FindControl("lblError") as Label).Text = rowData.ErrorText;
//(e.Row.FindControl("ErrorPanel") as Panel).Visible = (!string.IsNullOrEmpty(rowData.InfoText) || !string.IsNullOrEmpty(rowData.ErrorText));
}
}
}
[Serializable()]
private class RowData
{
public int Id { get; set; }
public string Name { get; set; }
public DateTime? Date { get; set; }
public double? Value { get; set; }
public string ValidationRule { get; set; }
public string ErrorText { get; set; }
public string InfoText { get; set; }
public string EnteredDateCache { get; set; }
public string EnteredValueCache { get; set; }
public bool Editable { get; set; }
}
}
public static class StringExtensionMethods
{
public static bool IsNumber(this String str)
{
double Number;
if (double.TryParse(str, out Number)) return true;
return false;
}
}
Looks like I was incorrectly setting the controls incorrectly in the RowDataBound event. This should be:
if (e.Row.RowType == System.Web.UI.WebControls.DataControlRowType.DataRow)
{
var rowData = e.Row.DataItem as RowData;
if (rowData != null)
{
DataControlFieldCell txtNewDate = (DataControlFieldCell)e.Row.Cells[COL_NEW_DATE];
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
{
var txtNewValue = (e.Row.FindControl("txtNewValue") as TextBox);
txtNewValue.Enabled = txtNewDate.Enabled = (canEdit & rowData.Editable);
txtNewValue.Text = rowData.EnteredValueCache;
}
(e.Row.FindControl("lblStatus") as Label).Text = rowData.InfoText;
(e.Row.FindControl("lblError") as Label).Text = rowData.ErrorText;
}
}
Remove the following lines from SaveData:
(row.FindControl("lblStatus") as Label).Text = dataItem.InfoText;
(row.FindControl("lblError") as Label).Text = dataItem.ErrorText;
Remove the following from ValidateDataRow:
labelInfo.Text = string.Empty;
labelError.Text = string.Empty;
I am assuming that calling the following:
DataControlFieldCell txtNewValue = (DataControlFieldCell)e.Row.Cells[COL_NEW_VALUE];
if (!string.IsNullOrEmpty(rowData.EnteredValueCache))
txtNewValue.Text = rowData.EnteredValueCache;
Will remove the controls from the template column when the data is set (which would be on the invalid value as it is not cleared in the cache) which is why I saw the error when an invalid value was entered.
I am trying to add a required field validator to my page at runtime.
Nothing fancy there:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:ValidationSummary ID="ValidationSummary1"
runat="server" ShowMessageBox="True" ShowSummary="False" />
</form>
and # codebehind
protected void Page_Init(object sender, EventArgs e)
{
RequiredFieldValidator theValid = new RequiredFieldValidator();
theValid.ID = "0000" + "RFV";
theValid.ControlToValidate = TextBox1.ID;
theValid.ErrorMessage = "Message here"
theValid.Text = "*";
theValid.Display = ValidatorDisplay.Dynamic;
theValid.EnableClientScript = true;
theValid.EnableViewState = true;
theValid.SetFocusOnError = true;
theValid.Enabled = true;
theValid.Visible = true;
Page.Validators.Add(theValid);
form1.Controls.Add(theValid);
}
When I click the button it only validates server-side, but not client-side. What am I missing?
TIA.
You can to check your code with jquery.
function TextBoxValidate() {
$('input:[type="text"]:[id*="TextBox1"]').each(function () { var txtId = this.id; $('span').each(function () { if (this.controltovalidate == txtId) ValidatorValidate(this); }); });
}
function InitValidationOnClick()
{
$('input:[id*="Button1"]').each(function(){$(this).on('click', function(){TextBoxValidate(); return Page_IsValid;});});
// or other case
//$('form:[id*="form1"]').each(function(){$(this).on('submit', function(){TextBoxValidate(); return Page_IsValid;});});
}
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitValidationOnClick);
If validator exists in page it will validate on click (submit) event client-side.
Hello All Try This one For Radio Buttons Along With RequiredField Validator
Code
TableRow trow4 = new TableRow();
trow4.Style.Add("width", "100px");
TableCell tcel4 = new TableCell();
Label lb4 = new Label();
lb4.Text = Resources.QcLabelName.Gender;
tcel4.Controls.Add(lb4);
CSSCell(tcel4);
table.Rows.Add(trow4);
RadioButtonList rblist = new RadioButtonList();
rblist.ID = "rbtnmalendfemale";
rblist.Items.Add("Male");
rblist.Items.Add("Female");
tcel4.Controls.Add(rblist);
trow4.Cells.Add(tcel4);
table.Rows.Add(trow4);
rblist.Visible = true;
RequiredFieldValidator rFV5 = new RequiredFieldValidator();
TableCell tcl46 = new TableCell();
rFV5.ControlToValidate = "rbtnmalendfemale";
rFV5.ErrorMessage = "Gendor Selection Is Mandatory";
rFV5.Style.Add("color", "Red");
rFV5.ID = "Reqfield9";
tcl46.Controls.Add(rFV5);
trow4.Cells.Add(tcl46);
table.Rows.Add(trow4);
rFV5.Visible = true;******
I'm using jQuery's AutoComplete on an ASP.NET DropDownList, the user can select a value and submit for entry into the DB. But they must also be able to type in a value, and I can't seem to be able to access that value in the code behind.
Heres the jQuery:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue'>")
.insertAfter(select)
.val(value)
.autocomplete({
delay: 0,
minLength: 0,
source: function (request, response) {
var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
response(select.children("option").map(function () {
var text = $(this).text();
if (this.value && (!request.term || matcher.test(text)))
return {
label: text.replace(
new RegExp(
"(?![^&;]+;)(?!<[^<>]*)(" +
$.ui.autocomplete.escapeRegex(request.term) +
")(?![^<>]*>)(?![^&;]+;)", "gi"
), "<strong>$1</strong>"),
value: text,
option: this
};
}));
},
select: function (event, ui) {
ui.item.option.selected = true;
self._trigger("selected", event, {
item: ui.item.option
});
},
change: function (event, ui) {
if (!ui.item) {
var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex($(this).val()) + "$", "i"),
valid = false;
select.children("option").each(function () {
if ($(this).text().match(matcher)) {
this.selected = valid = true;
return false;
}
});
if (!valid) {
// remove invalid value, as it didn't match anything
//$(this).val("");
// select.val("");
// input.data("autocomplete").term = "";
return false;
}
}
}
})
.addClass("ui-widget ui-widget-content ui-corner-left");
input.data("autocomplete")._renderItem = function (ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
};
this.button = $("<button type='button'> </button>")
.attr("tabIndex", -1)
.attr("title", "Show All Items")
.insertAfter(input)
.button({
icons: {
primary: "ui-icon-triangle-1-s"
},
text: false
})
.removeClass("ui-corner-all")
.addClass("ui-corner-right ui-button-icon")
.click(function () {
// close if already visible
if (input.autocomplete("widget").is(":visible")) {
input.autocomplete("close");
return;
}
// work around a bug (likely same cause as #5265)
$(this).blur();
// pass empty string as value to search for, displaying all results
input.autocomplete("search", "");
input.focus();
});
},
destroy: function () {
this.input.remove();
this.button.remove();
this.element.show();
$.Widget.prototype.destroy.call(this);
}
});
})(jQuery);
So this takes my DropDownList, hides it, creates an input field acting as my select and also enables me to type in values.. This is my DropDownList:
<asp:FormView ID="frmCreateOptionValue" runat="server" DataKeyNames="OptionValueID"
DataSourceID="OptionSetValues_DS" DefaultMode="Insert"
oniteminserting="frmCreateOptionValue_ItemInserting">
<InsertItemTemplate>
<table border="0" cellpadding="0" cellspacing="0" id="id-form">
<tr>
<th>
Add Option Set Value:
</th>
<td>
<div class="ui-widget" runat="server" id="addOptValue">
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList>
<asp:ObjectDataSource ID="OptionValues_DS" runat="server" OldValuesParameterFormatString="original_{0}"
SelectMethod="GetDataBy1" TypeName="PurekbbDataSetTableAdapters.tblOptionValueTableAdapter">
<SelectParameters>
<asp:QueryStringParameter Name="oID" QueryStringField="optionSetID" Type="Int32" />
</SelectParameters>
</asp:ObjectDataSource>
</div>
</td>
<td>
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True" CommandName="Insert"
CssClass="form-submit" />
</td>
</tr>
</table>
</InsertItemTemplate>
</asp:FormView>
And when the user inserts an item:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((TextBox)frmCreateOptionValue.FindControl("txtOptValue")).Text;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Is where I am stuck, how can I get the value from that HTML input field generated in jQuery?
How can this be achieved, it's killing me ;)
you can get the value of this text box using javascript and save it in a hidden field then read the hidden field value from code behind
put this inside javascript
$('#HiddenFieldID').val($('#txtOptValue').val());
then code behind will look like this
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! CANNOT FIND THE HTML INPUT AND SAVE THE VALUE
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("HiddenFieldID")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Heres the solution to this one, using a HiddenField:
Add onblur to the dynamically created input:
(function ($) {
$.widget("ui.combobox", {
_create: function () {
var self = this,
select = this.element.hide(),
selected = select.children(":selected"),
value = selected.val() ? selected.text() : "";
var input = this.input = $("<input id='txtOptValue' onblur='JavaScript:copyValue()'>") ....
Add HiddenField and jQuery to the page:
<asp:HiddenField runat="server" ID="hfoValue" EnableViewState="true" ClientIDMode="Static" />
<div class="ui-widget" runat="server" id="addOptValue">
<script type="text/javascript" language="javascript">
function copyValue() {
var theVal = $('#txtOptValue').val();
//alert('Copyng ' + theVal);
$('#hfoValue').val(theVal);
//alert('copied');
}
</script>
<asp:DropDownList ID="ddlAddOptionValue" runat="server" ClientIDMode="Static" DataSourceID="OptionValues_DS"
DataTextField="Name" DataValueField="OptionValueID" AppendDataBoundItems="true"
SelectedValue='<%# Bind("OptionValueID") %>'>
<asp:ListItem Value="" Text="Select One..." />
</asp:DropDownList> ...
Finally access the value from the HiddenField:
protected void OptionSetValues_DS_Inserting(object sender, ObjectDataSourceMethodEventArgs e)
{
// if the value doesn't already exist, create it
if (e.InputParameters["OptionValueID"] == null)
{
// !!!! FOUND THE VALUE :)
string ovName = ((HiddenField)frmCreateOptionValue.FindControl("hfoValue")).Value;
int ovOptionID = Convert.ToInt32(Request.QueryString["OptionSetID"]);
tblOptionValueTableAdapter t = new tblOptionValueTableAdapter();
int ovID = Convert.ToInt32(t.InsertQuery(ovOptionID, ovName, 0, ""));
e.InputParameters["OptionValueID"] = ovID;
}
}
Thanks to #Miroprocessor for helping to solve this one