I am wondering how to gray out a button until all text boxes have text in ASP.NET and or C#. In the image below I want to gray out the commit button. Cheers, Chris!
You can try similar like this
Check for every input element that it has the value or not and make a global variable which would be true when all the inputs value.
Now enable a button when this variable is true.
$('input').keyup(function() {
var isEntryPresent = false;
$('input').each(function() {
if ($(this).val() == '') {
isEntryPresent = true;
}
});
if (isEntryPresent) {
$('#commitInventory').attr('disabled', 'disabled');
} else {
$('#commitInventory').removeAttr('disabled');
}
});
Js Fiddle Demo
You may need to use the more specific input selector if there are any other input elements are present on the page. So you should use the specific selector as per your condition.
You can do this with the "change" event rather than on every single keyup/keydown. Also, you can use a filter to simplify the code for checking for any empty inputs.
View Demo
$(document).ready(function(){
$("input").on("change", function(){
$("#inp-submit").prop("disabled", anyEmptyInputs());
});
});
function anyEmptyInputs(){
var empty = $("input").filter(function() { return this.value === ""; });
return empty.length > 0;
}
Since you have JavaScript tagged here as well as ASP.NET I'm assuming you are doing this on the Client Side also, or can do it on the Client Side, Below you can run the code Live from JSFiddle
Click Here For A Live JsFiddle Demo.
If you run the code on JsFiddle, it basically attaches all the TextBoxes to the "KeyUp" Event and then checks how many TextBoxes are Not Empty comparing it to the count of the Number of Total TextBoxes, if the count of Not Empty matches the count of number of Total TextBoxes then the Commit button is enabled, otherwise its disabled.
The HTML used there are 5 TextBoxes and 1 Button named Commit. If you are running the code below in your own web page. Remember to include JQuery 2.0
<span>TextBox #1</span><input type="text" /><br /><br />
<span>TextBox #2</span><input type="text" /><br /><br />
<span>TextBox #3</span><input type="text" /><br /><br />
<span>TextBox #4</span><input type="text" /><br /><br />
<span>TextBox #5</span><input type="text" /><br /><br />
<input id="btnSubmit" type="button" value="Commit" />
The JQuery/JavaScript that enables and disables the Commit button based on text in the TextBoxes
$(document).ready(function () {
$("input[type=button]").attr("disabled", "disabled");
//This routine attaches the "KEYUP" event to every TextBox
//When the user types each TextBox will be checked every time
//and count which ones are Not Empty, if the count of the Not Empty
//TextBoxes equals that of the count of all TextBoxes then the
//Commit button is Enabled.
$('input:text').keyup(function () {
var isValid = true;
$('input:text').each(function () {
if ($(this).val().length === 0) {
$("input[type=button]").attr("disabled", "disabled");
isValid = false;
return false;
}
if (isValid) {
$("input[type=button]").removeAttr("disabled");
}
});
});
Related
I have two text boxes. One textbox for input and other for output. when number entered in first textbox by button click then i want to find square of that number in second textbox by clicking Square button. But i am not able to get the desired result. Nothing is displayed in second textbox when Square button is clicked.
Here is Code snippet:
#Html.TextBoxFor(model => model.textBox, new { #readonly = "readonly" })
<br/>
#Html.TextBoxFor(model => model.textBox1, new { #readonly = "readonly" })
<input name="button" type="submit" id="btntwo" value="2" />
<input name="button" type="submit" id="btnthree" value="3" />
<input name="button" type="submit" id="btnfour" value="4" />
<input name="button" type="submit" id="btnSqr" value="Sqr" />
Here is code snippet for controller:
if (button == "Sqr")
{
model.value1 = model.textBox;
model.textBox1 = (float.Parse(model.value1) * float.Parse(model.value1)).ToString();
}
Note: I have only provided the code which is required to solve the issue.
Here is my assumptions of what you are doing "IF You Use Server Side Solution"
public ActionResult FindSquare()
{
SquareModel model = new SquareModel(); // model contains textbox, textbox1
return View(model);
}
And when you submit form on button click
public ActionResult FindSquare(SquareModel model, FormCollection collection)
{
if(!string.IsNullOrEmpty(collection["button"]) && collection["button"].ToString() == "Sqr")
{
double value = Convert.ToDouble(model.textBox);
var result = value * value;
model.textBox1 = Convert.ToString(result);
return View(model);
}
}
Edit:
Remove removeonly from your view page.
Use Client Side Script to do it easily
$('#btntwo').click(function (e) {
var num = parseInt($('#textBox').val());
$('#textBox1').val(num*num);
return false;
});
If you want to continue in server side, you have to remove #readonly =
"readonly".
I suspect the issue you're having is related to the fact you've got two textboxes (textBox and textBox1), and both are read-only. Nothing can be changed, so perhaps the controller is not firing at all?
I'd also be worried your controller implementation is not wired up properly. You've provided too little code to validate the mainstay failure points for postback processing are not the cause.
I am having a user control file without its codebehind file in dotnentnuke.
In which i have put a form in which i have one textbox and one Linkbutton.
I want to pass that textbox's value when i press the button as querystring to access it in another page.
For that i have written following code but it does not work.
<asp:TextBox ID="txtemail" runat="server" class="txtbox" placeholder="Enter Email Here"></asp:TextBox>
<asp:LinkButton ID="LinkButton1" class="lbsubscrb" runat="server"
PostBackUrl="~/Portals/_default/Skins/Gravity/Dummy.aspx?add=<% txtemail.Text %>"
ForeColor="White">SUBSCRIBE</asp:LinkButton>
All answers are appreciated...
It sounds like you really just need your own custom module, instead of trying to take an existing module, without the source code, and make it do something completely different?
That being said, if you really want to take that existing module and make it do that, jQuery is likely going to be your method of choice.
Basically you wan to hijack the click event for the button and send it elsewhere, something along the lines of the following code. I actually wrote most of this last night for another module I was working on (newsletter subscriptions, by the way) but have removed some of my logic to make it simpler for what you are trying to do
EDIT: replaced the txtbox class below to match your textbox's class
<script language="javascript" type="text/javascript">
/*globals jQuery, window, Sys */
(function ($, Sys) {
$(document).ready(function () {
var originalHref = $('.lbsubscrb a').attr('href');
$('.lbsubscrb a').removeAttr("href");
$('.txtbox').focus(function () {
if($('.txtbox').val().indexOf('#')<1)
$('.txtbox').val('');
});
$('.txtbox').bind("keypress", function (e) {
if (e.keyCode == 13) {
$('.lbsubscrb a').click();
}
});
$('.lbsubscrb a').click(function () {
//check if they hit enter in the textbox and submit the form
if (validateEmail($('.txtbox').val())) {
//
//TODO: Add your jquery for the redirect call here.
//
//uncomment this line to actually use the original submit functionality
//eval(originalHref.replace('javascript:', ''));
//if postback is wanted uncomment next line
//$('.lbsubscrb a').removeAttr("href");
} else {
alert('something wrong with your email');
}
});
});
}(jQuery, window.Sys));
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
</script>
Alright my basic question is how do I simulate a button click in javascript.
I know I have to use document.getElementById("btnSubmit").click(); but this doesn't seem to call the onClientClick javascript function as well.
Enviorment:
I am using ASP.NET with C# and javascript.
What happened:
I have an input text area and I want to make sure that users must enter a character before the submit button is enabled. I was able to do this with onkeypress="validateTxt();" which then called this function
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
The only problem though is doesn't register backspace.
To solve this I found this online
<script type="text/javascript">
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
Now whenever the user presses the backspace my javascript function is called. This worked great up until I found out that when I press enter from the text area it wouldn't call my javascript function.
Here is all of the relevant code...
<script type="text/javascript">
function InformUser()
{
window.document.getElementById("loadingMessageDIV").style.display = "block";
<%=Page.GetPostBackEventReference(btnSubmit as Control)%>
document.getElementById("btnSubmit").disabled = true;
}
function validateTxt() {
var input = document.getElementById("<%=txtUserName.ClientID %>").value;
//Need a min of 3 characters
if(input.length > 1)
{
document.getElementById("btnSubmit").disabled = false;
}
else
{
document.getElementById("btnSubmit").disabled = true;
}
}
</script>
Here is the text area + javascript bounding function
<asp:TextBox ID="txtUserName" runat="server" Font-Size="11pt" onkeypress="validateTxt();"></asp:TextBox>
<script type="text/javascript">
//We bind the textbox to this function and whenever the backspace key is pressed it will validateTxt
document.getElementsByName('txtUserName')[0].onkeydown = function (event) {
if (event === undefined) event = window.event; // fix IE
if (event.keyCode === 8)
validateTxt();
if (event.keyCode === 13) {
document.getElementById("btnSubmit").click();
}
};
</script>
Here is the submit button
<asp:Button ID="btnSubmit" runat="server" OnClientClick="InformUser();" OnClick="btnSubmit_Click"
Text="Login" Font-Bold="True" Enabled="True" />
<script type="text/javascript">
//Disable the button until we have some actual input
document.getElementById("btnSubmit").disabled = true;
</script>
So to recap it does press the button, but it fails to disable it as well. I even tried to call the InformUser directly when the user presses enter and then press the button, but that didn't work either.
I know it has something to do with how I bound the javascript function to the text area because when I take it out it works.
Thanks for the help
If what you're really trying to do is enable/disable the submit button based on the amount of text in the text area, then it would be simplest just to check the length every time it's changed.
Would you be able to use jQuery? If you can, it's a trivial problem, as jQuery normalises keyboard events so you don't have to worry about different browsers raising different events.
As a simple experiment, I created a jsFiddle with this HTML:
<textarea id="txt"></textarea>
<label id="count" />
and this JavaScript:
$('#txt').keyup(function () {
$('#count').text($('#txt').val().length);
});
On every keyup (I used keyup rather than keydown or keypress as keyup fires after the text has been modified) the length is updated. This registers normal keys, backspace, delete, enter, etc, and works in FF and IE8.
In your case, you'd obviously change the function to enable/disable the submit button.
I am creating some text boxes at runtime and I would like to change the color of the text box if the text box has been left blank
and the user submits the form.
I am using the code behind approach, this is the code I wrote in the .aspx.cs file
textBoxObj is the text box object that I create at runtime and it is the object on which I want the empty validation.
CustomValidator customValidatorObj = new CustomValidator();
customValidatorObj.ControlToValidate = textBoxObj.ID;
customValidatorObj.ClientValidationFunction = "changeColorofTextBox";
and I wrote a small Javascript snippet within the .aspx file which goes as follows (I haven't yet written the logic to change the color,
just making it not valid for now)
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
args.IsValid = false;
}
}
</script>
In the submit button click function of the form, I have this check if(Page.IsValid), then submit the form. However, even when the text box is empty,
the form gets submitted. It seems like the function is not even being hit. Do you have any pointers on what I am doing wrong?
I am fine with either client side or server side validation, whichever works.
EDIT
I got the error, I just had to do this
customValidatorObj.ValidateEmptyText = true;
and it started working.. Thank you, I didn't realize that the customValidator class does not try validating if the control is blank.
But I am stuck again :(
In the form, I have many text boxes. Suppose, the user entered text for 3 of the text boxes and left 2 of them blank, how do I find the text box ids so that I can change the color of only the blank ones. or, how can I write code in the javascript to find out the control ID at runtime?
I know we have to do this
document.getElementById(CONTROLIDGOESHERE).style.backgroundColor = "red";
but how I get the CONTROLIDGOESHERE value to pass to the getElementById function?
Any pointers, thanks.
Try setting customValidatorObj.EnableClientScipt = True
Assuming you are running .NET Framework version 4.0 then you could declare your textboxes using ClientIDMode="Static". That way they'll have the same ID client-side and server-side e.g.
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
Then you could trigger client-side validation on a button click by declaring a button like this:
<input type="submit" id="btnSubmit" onclick="ClientSideValidation(); return false;" value="Save"/>
The JavaScript function could look something like this:
<script type="text/javascript">
function ClientSideValidation() {
var txtName = document.getElementById("txtName");
if (txtName.value.length == 0) {
txtName.style.background = "#DE0000";
}
// Check other text boxes...
}
</script>
Thank you guys, I figured it out. This code does the job for me
.aspx.cs
CustomValidator customValidator = new CustomValidator();
customValidator.ControlToValidate = textBox.ID;
customValidator.ClientValidationFunction = "changeColorofTextBox";
customValidator.ValidateEmptyText = true;
customValidator.EnableClientScript = true;
e.Item.Controls.Add(customValidator);
.aspx
<script type="text/javascript">
function changeColorofTextBox(oSrc, args) {
if (args.Value.length > 0) {
args.IsValid = true;
}
else {
var ctrlid = oSrc.id;
var validatorid = document.getElementById(ctrlid);
ctrlid = validatorid.controltovalidate;
document.getElementById(ctrlid).style.backgroundColor = "Tomato";
args.IsValid = false;
}
}
</script>
I'm creating a program where, in each GridView row, there is a checkbox and a textbox, which are unchecked and disabled by default respectively. When the checkbox is ticked, I need to fire a bit of JavaScript to enable that textbox, and vice versa for when is unticked. So far I am doing this:
JS:
<script type="text/javascript">
function onholdev(index) {
var chk = document.getElementById('<%=grdCons.Rows[index].FindControl("chkHold").ClientID %>');
var txt = document.getElementById('<%=grdCons.Rows[index].FindControl("txtReason").ClientID %>');
if (chk.checked == true) {
txt.disabled = false;
}
else {
txt.disabled = true;
txt.value = "";
}
}
</script>
C# (RowDataBound event)
CheckBox chkHold = ((CheckBox)e.Row.FindControl("chkHold"));
chkHold.Attributes.Add("onchange", "onholdev(" + e.Row.RowIndex + ")");
But in the JS, it's saying the 'index' variable does not exist, in the first line of the function (that begins with var chk). Am I doing this right?
the problem is that index is inside the string while it should be a parameter, this fixes it :
var chk = document.getElementById('<%=grdCons.Rows[' + index + '].FindControl("chkHold").ClientID %>');
the same goes for the other line
Since the check box will render as input we can able to find it by using the $('.check input') and since it is added dynamically we need to use jquery bind to add the click function to the check box.So in this I am getting the checked control by chk = $('.check input');.Each time when user checks a check box the function calls .I am here setting the visibility to none of all text box and when the user click it will find the next control and removing the class .hde using $(this).parent().next().removeClass('hide');.So the textbox will be visible next to the checkbox.
In your case I think by default you will make textbox disabled=false
.hide is used to set visiblity false.you can do disabling by adding attribute disabled to the textbox
css
.hide
{
display: none;
}
Designer Code
<ItemTemplate>
<asp:CheckBox ID="cbEnergyItems" runat="server" CssClass="check" />
<input type="text" id="txtQty" style="width: 25px" class="hide"
value="0" runat="server" />
<%# Eval("something") %>
</ItemTemplate>
Jquery
$('.check input').bind("click", function() {
var chk = $('.check input');
if ($(this).attr('checked')) {
//$(this).parent().next().removeClass('hide'); //removing the class to visible. you can do removing the attribute
$(this).parent().next().removeAttr("disabled");
if ($(this).parent().next().val() == ""0"")
showStatus(true, "Please enter the quantity");
}
else {
$(this).parent().next("disabled","disabled").
// $(this).parent().next().addClass('hide');
}
});
I think this will solve your problem.
Thanks all for your help, I sort of 'solved' it by not doing it serverside instead. Bit lazy but saves a lot of JS headaches.