Hi I would like to turn label red in .aspx when user enters wrong answer into textbox.
but not know how, hw I can do this?
You can do this using javascript (call this code from onchange of the textbox):
<label for="myTextBox" id="myLabel">For my textbox</label>
<input id="myTextBox" onchange="ValidateAnswer();">
function ValidateAnswer() {
var txtBox = document.getElementById('myTextBox');
if(txtBox.value != "answer") {
document.getElementById('myLabel').style.color = 'red';
}
}
You can also use the Validator controls if you're using ASP.Net:
<asp:CustomValidator runat="server" ID="cvAnswer"
ControlToValidate="myTextBox"
ErrorMessage="required"
ClientValidationFunction="ValidateAnswer"
ValidateEmptyText="true"
Display="Dynamic"
ValidationGroup="First"
ForeColor="red" >
</asp:CustomValidator>
function ValidateAnswer(sender, args) {
args.IsValid = args.Value != "" && args.Value == "answer here";
if(!args.IsValid) {
document.getElementById('myLabel').style.color = 'red';
}
return;
}
From the server side code:
if(this.txtBox.Text.Length == 0)
{
//no value entered
lblMyLabel.BackColor = Color.Red;
lblMyLabel.Text = "Invalid entry";
}
Client side you can do this:
Markup:
<asp:TextBox onchange="Validate();" runat="server" id="myTextBox"/>
JS:
function Validate()
{
var t = document.getElementByID("myTextBox");
var l = document.getElementByID("myLabel");
if (t.Length == 0)
{
l.style.backgroundColor='red';
}
}
There are multiple options, some server side, and some client side, but in both cases it involves validation. Essentially you are looking to change a css class or other style property on the label.
C# code behind:
if(yourConditionText != "YourExpectedValue")
{
youTextBox.BackColor = System.Drawing.Color.Red;
}
In the Server side button click event (which will be automatically generated when you double click on the button in Design view of the aspx page):
protected void Button_Click(...)
{
if(txtYourTextBox.Text != "YourDesiredValue")
{
lblYourLabel.ForeColor = Color.Red;
}
}
Better still, you could use String.Compare (recommended) as below:
if(string.Compare(txtYourTextBox.Text, "YourDesiredValue") != 0) //0 = Match
{
lblYourLabel.ForeColor = Color.Red; //For backColor set BackColor property
}
Hope it helps!
Related
I have function that hides or displays divs, depending on radio button list value. My problem is that, it won't work without javascript enabled in browser. How could I get it work on server side, because SelectedIndexChanged can't get postback in this case.
I tried to add some click events to buttons, also tried prerender radio button list but no luck.
HTML:
<script>
function HideOrDisplayDisvsWithRadioButton(radioButtonList) {
var rblValue = $('#RblParticipantsType input:checked').val();
var divInsertPerson = $('div#DivInsertPerson');
var divInsertCompany = $('div#DivInsertCompany');
if (rblValue === '1') {
divInsertPerson.css('display', 'inherit');
divInsertCompany.css('display', 'none');
}
if (rblValue === '2') {
divInsertPerson.css('display', 'none');
divInsertCompany.css('display', 'inherit');
}
return false;
}
<script>
<asp:RadioButtonList ID="RadioButtonList" OnSelectedIndexChanged="RadioButtonList_SelectedIndexChanged"
onchange="javscript: HideOrDisplayDisvsWithRadioButton(this)"
AutoPostBack="true"
ClientIDMode="Static"
RepeatColumns="2"
runat="server"
<asp:ListItem Value="1" Selected="True">Eraisik</asp:ListItem>
<asp:ListItem Value="2">Ettevõte</asp:ListItem>
</asp:RadioButtonList>
And code behind:
protected void RadioButtonList_SelectedIndexChanged(object sender, EventArgs e)
{
if (RadioButtonList.SelectedValue == "1")
{
DivInsertPerson.Visible = true;
DivInsertCompany.Visible = false;
}
if (RadioButtonList.SelectedValue == "2")
{
DivInsertCompany.Visible = true;
DivInsertPerson.Visible = false;
}
}
I got it work with using CSS, I do not know is it wrong or right, but it works. I did something like here. link . These hidden buttons helped me out. Some configurations for CSS, HTML and C#.
I am trying to change the text for the link-button dynamically based on if the user is logged in or not. The text should be Log-out if user is logged in and vice versa. It is always showing Login. I am not sure what I am doing wrong here.
<p><asp:LinkButton ID="MyLnkButton" runat="server" EnableViewState = "False" onClick="MyLnkButton_Click" Text="" ForeColor="Red"/></p>
code behind
if (!Page.IsPostBack)
{
if (Session["USRID"] != null)
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}
else
MyLnkButton.Text = "Login";
}
I would reverse the logic question is do you need to call Bind_GV regardless of post back.. if so I will depict in my code below
if (Page.IsPostBack && !string.IsNullOrEmpty((string)Session["USRID"]))
{
MyLnkButton.Text = "Login";
}
else
{
lblWLC.Text = (string)Session["USRID"];
MyLnkButton.Text = "Logout";
Bind_GV();
}
I have one textbox..
i want to validate it's value based on dropdownlist value..
So i am displaying message from code behind using RegularExpressionValidator..
But it is not working plz,give me suggestion..
<asp:TextBox ID="tbnooflecture" runat="server" Width="119px" Height="33px"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" ForeColor="#6600FF"
runat="server" ValidationGroup="upper"
ControlToValidate="tbnooflecture"></asp:RegularExpressionValidator>
<asp:Button ID="bfillattendence" runat="server" Text="To Fill Attendence Click Here"
onclick="FillAttendence_Click" Width="218px" Height="33px" CausesValidation="true" ValidationGroup="upper"/>
i am writing below code in Button click event
string batchname = dpbatchname.SelectedItem.Text.ToString();
int lengthofbatch=batchname.Length;
if(lengthofbatch==2)
{
RegularExpressionValidator1.ValidationExpression = "[1-9][02468]|[02468]";
RegularExpressionValidator1.ErrorMessage = "Only Even No. of Attendence is Valid for Lab.";
}
else if (lengthofbatch == 1)
{
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
}
else
{
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
}
Are you validating Textbox value?
If you use regular expression on server side, then you need to validate input (your textbox) like
below, and display message.
if (Regex.IsMatch(text, reg))
{
}
Add this line
RequiredFieldValidator1.IsValid = false;
after
RegularExpressionValidator1.ValidationExpression = "[0-9][0-9]|[0-9]";
RegularExpressionValidator1.ErrorMessage = "Attendence Shold be Like 9,50";
I am using a WebForms GridView control. When a user clicks "Update" on a row, I want to check the values they entered against some other records.
From that, if I return true, I'd like to display a confirm dialog asking the user if they'd like to continue with their update.
A javascript confirm dialog probably won't work because I don't always want to show this dialog, only when the values entered meet a certain condition.
Any suggestions?
I would suggest using the RowDataBound event to check for those conditions and add the confirmation dialog where needed.
EDIT : Compare dates and show a confirmation if they're different
See this jsFiddle for a demonstration.
<script type="text/javascript">
validateInput = function(inputDate, compareDate, confirmButtonID) {
var confirmButton = document.getElementById(confirmButtonID);
if (confirmButton) {
$(confirmButton).one("click", function() {
var result = dates.compare(inputDate, compareDate);
if (result != 0){ //change to suit your needs
return confirm("Are you sure you want to save these changes?");
}
return true;
});
}
}
</script>
And here's the code for the dates class used for the comparison (link):
<script type="text/javascript">
var dates = {
convert:function(d) {
return (
d.constructor === Date ? d :
d.constructor === Array ? new Date(d[0],d[1],d[2]) :
d.constructor === Number ? new Date(d) :
d.constructor === String ? new Date(d) :
typeof d === "object" ? new Date(d.year,d.month,d.date) :
NaN
);
},
compare:function(a,b) {
return (
isFinite(a=this.convert(a).valueOf()) &&
isFinite(b=this.convert(b).valueOf()) ?
(a>b)-(a<b) :
NaN
);
},
inRange:function(d,start,end) {
return (
isFinite(d=this.convert(d).valueOf()) &&
isFinite(start=this.convert(start).valueOf()) &&
isFinite(end=this.convert(end).valueOf()) ?
start <= d && d <= end :
NaN
);
}
}
</script>
In the RowDataBound event of the GridView, assign the onchange function for each row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
var inputCtrl = e.Row.FindControl("txtEnteredDate") as TextBox;
if (inputCtrl != null)
{
var updateButtonCtrl = e.Row.FindControl("btnUpdate") as Button;
if (updateButtonCtrl != null)
{
inputCtrl.Attributes["onchange"] = string.Format("return validateInput(this.value, '{0}', '{1}');", DataBinder.Eval("DateToCompare"), updateButtonCtrl.ClientID);
}
}
}
jQuery Confirmation Dialog
If you need something more flexible than a regular JavaScript confirm dialog, you can change the above to use the jQuery UI Dialog as a confirmation instead.
If you are using WebForms (?), you need to add some validation controls to the GridView template.
Here is an example from MSDN using a CompareValidator:
<EditItemTemplate>
<asp:TextBox ID="EditUnitPrice" runat="server"
Text='<%# Bind("UnitPrice", "{0:c}") %>'
Columns="6"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server"
ControlToValidate="EditUnitPrice"
ErrorMessage="The price must be greater than or equal to zero and
cannot include the currency symbol"
Operator="GreaterThanEqual" Type="Currency"
ValueToCompare="0">*</asp:CompareValidator>
</EditItemTemplate>
The label is initialized with the value of the textbox. Upon clicking the label, the textbox is shown. The user can then edit the contents of the textbox. Upon blurring focus, the textbox is hidden and the label shown. Should the user delete the contents of the textbox or only enter whitespace into the textbox, the textbox is not hidden, thus avoiding showing a label with no text. Is there a way to do this ?
Untested, but the general idea should help you out.
HTML:
<asp:TextBox ID="txtA" onblur="txtBlur();" style="display:none;" runat="server"/>
<asp:Label ID="txtA" onclick="txtFocus();" runat="server"/>
Client-side JS:
<script>
var txtA = document.getElementById("<%# txtA.ClientID %>");
var lblA = document.getElementById("<%# lblA.ClientID %>");
function txtBlur()
{
if (txtA.value.trim() != '')
{
lblA.innerText = txtA.value;
lblA.style.display = 'inline';
txtA.style.display = 'none';
}
}
function txtFocus()
{
txtA.value = lblA.innerText;
lblA.style.display = 'none';
txtA.style.display = 'inline';
}
</script>
Check for js validation that textbox is not empty
function Validate()
{
if(document.getElementById("txta").value=="")
{
alert('Please enter the value');
document.getElementById("txta").focus();
return false;
}
}
or you can server side
if (txa.text ="")
{
Response.Write('Text box cannot be empty');
}