Javascript enable/disable button not working as expected - javascript

This is my logon view:
#model SuburbanCustPortal.Models.LogOnModel
#{
ViewBag.Title = "Log On";
}
<h2>Log On</h2>
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
<p>
If only you wish to make a payment on your account and do not want to create a website login, #Html.ActionLink("click here", "RedirectToPaymentPage", "Account").
</p>
#Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.")
#using (Html.BeginForm()) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(m => m.UserName)
</div>
<div class="editor-field focus">
#Html.TextBoxFor(m => m.UserName, new { #class = "GenericTextBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.UserName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButton()" })
#Html.ValidationMessageFor(m => m.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
#Html.LabelFor(m => m.RememberMe)
</div>
<p>
<button name="btn" value="Log On" onclick="disableButton()" disabled="disabled">Log On</button>
</p>
<p>
If you need to retrieve your username #Html.ActionLink("click here.", "ForgotUsername", "Account")<br/>
If you need to reset your password #Html.ActionLink("click here.", "ForgotPassword", "Account")
</p>
</fieldset>
</div>
}
This is my widget.js:
function enableLogonButton() {
if ($('#UserName').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
$('#btn').attr('disabled', 'disabled');
return;
}
$('#btn').removeAttr('disabled');
}
function logonDisableSubmitButtons(clickedButton) {
$("input[type='button']").each(function() {
if (this.name != clickedButton)
$(this).attr("disabled", "disabled");
else {
//hiding the actually clicked button
$(this).hide();
//Creating dummy button to same like clicked button
$(this).after('<input type="button" disabled="disabled" value="' + $(this).val() + '" class="' + $(this).attr('class') + '" />');
}
});
}
function disableButton() {
$('#btn').click(function (e) {
$(this).attr('disabled', 'disabled');
});
}
I'm not having the button enabled no matter what I do.
What I am wanting is two things:
When the user has something in the logon and username, enable the submit button.
When they click submit, the button is disabled so they cannot click it twice.
I'm not having luck with either.
I have made the changes suggested below but the button is still not being enabled once I have entered something in the fields
** FURTHER TESTING**
I added the alerts() as suggested as such:
function enableLogonButton() {
alert("start");
if ($('#UserName').val() == "") {
alert("username");
$('#btn').attr('disabled', 'disabled');
return;
}
if ($('#Password').val() == "") {
alert("password");
$('#btn').attr('disabled', 'disabled');
return;
}
alert("enabled");
$('#btn').removeAttr('disabled');
}
Not one of them are firing off. At least, I'm getting no prompt.
So, then I changed the call to this to make sure it was even seeing the JScript:
#Html.PasswordFor(m => m.Password, new { #class = "GenericPasswordBox", onkeyup = "enableLogonButtonX()" })
And I get this message:
Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
So, I believe it is seeing the JScript.
I then added this:
<script>
function myFunction() {
alert("hit!");
}
</script>
And changed this:
<button name="btn" value="Log On" onclick="myFunction()" disabled="disabled">Log On</button>
And my "hit" worked. So, I believe the onclick is working also.

disabled is a boolean property, not an attribute.
To set:
$('#btn').attr('disabled', 'disabled');
To clear:
$('#btn').removeAttr('disabled')

Unless I'm not reading your question close enough (which, admittedly, could be the case since it is after 5 here...time for beer) or you have a typo in your question, I think your error message gives you everything you need to debug this.
Here is your message: Microsoft JScript runtime error: 'enableLogonButtonX' is undefined
Here is your function name: enableLogonButton
So, according to the error message, you are calling the function enableLogonButtonX() but your function is named enableLogonButton. Change to this:
#Html.PasswordFor(m => m.Password, new {
#class = "GenericPasswordBox",
onkeyup = "enableLogonButton()" })

Instead of changing the value of disable attribute remove it completely from element.
i.e. Replace this
$('#btn').attr('disabled', false);
With
$('#btn').removeAttr('disabled');

Related

How to get viewbag data in jquery?

Hi I am developing web application in mvc5. I have login form with username and password fields as below.
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid",
#class = "form-control validate[requiredInLogin] text-input "})
#Html.Password("txtPassword", null, new { #maxlength = "15", id =
"txtPassword", #class = "form-control validate[requiredOutLogin] text-input" })
<input type="submit" class="btn btn-primary btnLogin red"
value="SIGN IN" name="submit" />
}
I have below action method,
[HttpPost]
public ActionResult ClickAction()
{
//Some logic
//When 3 unsuccessful attempts made to login then i set
//ViewBag.captcha = true;
return View();
}
I will make 3 unsuccessful attempts to login then i will set ViewBag.captcha to true. Once i set ViewBag.captcha to true i want to access the ViewBag.captcha value in View and i want to display captcha. May i know how can i access Viewbag value in view? any help would be appreciated. Thanks,
Meanwhile i tried below options,
#{
var message = ViewBag.captcha;
}
Then in JS
var message = '#message';
if (message)
{
alert(message);
}
Below is my login view.
<html>
<head></head>
<body>
<div id="formID">
#*<form id="formID">*#
<div class="loginContainer">
<div class="loginContentArea">
<div class="loginLogo"><img src="~/images/c3card.png" alt="C3 Card" align="middle" /></div>
#using (Html.BeginForm("ClickAction", "Login", FormMethod.Post))
{
<div class="loginUsernamePassword">
<i class="fa fa-user"></i>
#Html.TextBox("txtUid", null, new { #maxlength = "15", id = "txtUid", #class = "form-control validate[requiredInLogin] text-input ", placeholder = "Username", autocomplete = "off" })
</div>
<div class="loginUsernamePassword">
<i class="fa fa-lock"></i>
#Html.Password("txtPassword", null, new { #maxlength = "15", id = "txtPassword", #class = "form-control validate[requiredOutLogin] text-input", placeholder = "Password", autocomplete = "off", Style = "background:#FFFFFF;" })
</div>
<div class="errormessage">#TempData["Message"]</div>
<div class="captcha" id="captcha">
<div class="g-recaptcha" data-badge="inline" data-sitekey=#System.Configuration.ConfigurationManager.AppSettings["recaptchaPublicKey"]></div>
<br />
</div>
<div class="loginButton">
<input type="submit" class="btn btn-primary btnLogin red" value="SIGN IN" name="submit" />
</div>
<div class="loginLink">#Html.ActionLink("Forgot Your Password?", "Index", "ForgotPassword")#**#</div>
}
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('input[type=password]').each(function () {
$(this).attr('data-background-color', $(this).css('background-color'));
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
$(this).focus(function () {
$(this).attr('type', 'password');
$(this).css('background-color', $(this).attr('data-background-color'));
});
$(this).blur(function () {
$(this).css('background-color', $(this).css('color'));
$(this).attr('type', 'text');
});
});
});
jQuery(document).ready(function () {
#{ var message = ViewBag.captcha; }
alert(message);
if (message) { alert(message); }
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});
$("#myinput").rules("add", {
minlength: 2
});
</script>
</body>
</html>
This does not work for me.
May i know proper way to access viewbag value in the above scenario? Any help greatly appreciated. Thank you so much.
Since you are using Razor you could do this:
1. Get your ViewBag value to a variable
<script type="text/javascript">
var message = "#ViewBag.captcha";
</script>
You don't have to set it inside your document ready.
2.The variable is of type string however. In order to use it in a function you will have to do something like that:
If(message.toLowerCase() == "true")
in order to get the desired effect.
To convert it to boolean you could use something like that
message = message.toLowerCase() === "true"
Hope it helps
You can initialize a ViewBag value like this:
ViewBag.captcha = "true";
Then you can access it like this in a view:
var message = #ViewBag.captcha;
From here on you will be able to use message. What you essentially did was the following:
you initialize ViewBag.captcha (note that this part is commented out)
you put that into a variable called message
you try to get #message as a string, but you are not using the Javascript value calculated
Can you change the message variable like below in JS and then try
jQuery(document).ready(function () {
var message = '#ViewBag.captcha'; //change it here
if (message)
{
alert(message);
}
$("[id=captcha]").hide();
// binds form submission and fields to the validation engine
jQuery("#formID").validationEngine();
$("formID").attr('autocomplete', 'off');
$('#txtUid').attr('autocomplete', 'off');
$('#txtPassword').attr('autocomplete', 'off');
});

Verification in DropDownListFor ASP.NET

i have one element span where i can write name of courier, during the writing it's searching couriers from database. I have also one element dropDownListFor where i can chose one courier. My problem is that, when i wrote a name which not exist in my datadase i dont have any information about that. I wanted to hide submit button if the DropDownListFor is empty - the name from span is incorrect, but it doesn'twork. How can i do this?
I have partialview like this:
div class="col-md-12">
<div class="col-md-offset-4 text-center">
<input type="text" oninput="Finder(this, '#CourierId'), check()" class="form-control" value="#Model.CourierName" id="courier-finder" placeholder="Select courier"/>
#Html.DropDownListFor(model => model.CourierId, (List<SelectListItem>)ViewBag.Couriers, new { #class = "form-control", onchange = "RefreshInput(this, '#courier-finder')" })
#Html.HiddenFor(model => model.TaskId)
</div>
<script>
function check() {
if (document.getElementById("CourierId")== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
Try :
function check() {
if ($("#CourierId").val()== "-1") {
$("#buttonDeleteMODALAssign").hide();
}
}
OR
function check() {
if (document.getElementById("CourierId").value== "-1") {
document.getElementById("buttonDeleteMODALAssign").style.display = 'none';
}
}

show and hide based on drop down list asp mvc 5

I am learning asp.net mvc 5.
My dropdownlistfor is working perfect and shows right field based on its value.
But the problem is when the page loaded first time it shows all field..
Problem is: I want default is showing nothing when the page first time loaded.
my cshtml:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(m => m.PaymentMethod, ViewBag.PayTypeList as List<SelectListItem>, new { #class = "btn btn-primary btn-lg dropdown-toggle", #id = "PaymentId" })
<div id="PaypalButton">
<br/>
<script src="https://www.paypalobjects.com/api/button.js?"
data-merchant="braintree"
data-id="paypal-button"
data-button="checkout"
data-color="gold"
data-size="medium"
data-shape="pill"
data-button_disabled="true">
</script>
<!--data-button_type="paypal_submit"-->
</div>
<div id="EcheckForm">
<div class="form-group">
<div class="col-md-10">
#Html.TextBoxFor(m => m.VecInsNum, new { #class = "form-control input-lg", placeholder = "Vehicle Isurance Number", required = "required", tabindex = 18 })
#Html.ValidationMessageFor(m => m.VecInsNum, null, new { #class = "text-danger" })
</div>
</div>
</div>
</div>
And Js:
#section Scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
});
});
When the page first time loaded:
When I select Paypal:
when I select E-check:
When I go back to Default:
First, create a function which contains hide methods inside it:
// hide all div options
function hideOnLoad() {
$('#PaypalButton').hide();
$('#EcheckForm').hide();
}
Then, call function above to hide all option div elements when page has loaded at first time and when default value being selected as given below:
$(document).ready(function () {
hideOnLoad(); // add this line
$('#PaymentId').change(function () {
var value = $(this).val();
if (value == '1') {
$('#PaypalButton').show();
$('#EcheckForm').hide();
} else if (value == '2') {
$('#PaypalButton').hide();
$('#EcheckForm').show();
} else {
hideOnLoad();
}
});
});
Simplified example: JSFiddle Demonstration

ASP.NET when form onsubmit called DOM elements disappear

I have simple Html.BeginForm with some data, and i want to check some condition using onsubmit() javascript function when user clicked "submit" button, before form will be send. And when this condition is false, I want to stop reloading page, just don't send my form to POST method. This is working fine, bit I met a problem, because DOM elements which I create in onsubmit() method disappear:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form", **onsubmit=" return registerValidation()"**}))
{
#Html.AntiForgeryToken()
#Html.TextBoxFor(m => m.Email, new { #class = "form-control", #id = "emailVal"})
#Html.ValidationMessageFor(m => m.Email,"", new { #class = "validation-error-white", #id="emailValidation"})
<input type="submit" class="btn btn-warning btn-block add-item-button-text" value="Zarejestruj" />
}
<script type="text/javascript">
function registerValidation() {
var validForm = validateRegisterForm(email, login);
if (!validForm) {
$('#emailValidation').append('Those email already exists! Take another one');
return false;
}
return true;
}
</script>
So when I want to return false, and do not send form, text that I append to validation-div that says what's wrong disappear - it's not what I want to achieve, because it's very small period of time and user cannot even notice that!
You manually trigger the button click event. Make sure type is button.
You do not need **onsubmit=" return registerValidation()"**
<input id="btnSubmit" type="button" ... />
<script type="text/javascript">
$(function () {
// Trigger btnSubmit button's click event, when enter key is pressed.
// If you do not want that feature, you can ignore this.
$("form").keydown(function (event) {
if (event.keyCode === 13) {
$("#btnSubmit").click();
return false;
}
});
$("#btnSubmit").click(function () {
// Do something, then submit the form
$("form").submit();
});
});
</script>

Display only required DDL value in Edit screen in MVC

When I use the JS code below in create view in MVC it works perfect. However I've tried to alter it so that when in edit view it should still only display the textbox when "OtherSpecifyFormGroup" is selected from the create screen. Any help would be great!!
<script>
$(document).ready(function () {
//this line fires no matter what
$("#OtherSpecifyFormGroup").hide();
$("#SelectType").change(function () {
//alert("in function");
var value = document.getElementById("SelectType").value;
if (value == "4") {
$("#OtherSpecifyFormGroup").show("highlight", { color: "#7FAAFF" }, 1000);
}
else {
$("#OtherSpecifyFormGroup").hide();
}
});
})
</script>
HTML code
<div class="form-group">
#Html.LabelFor(model => model.SelectType, "Select Type", new { #class = "control-label col-md-5" })
<div class="col-md-1">
#Html.DropDownList("SelectType", String.Empty)
#Html.ValidationMessageFor(model => model.SelectType)
</div>
</div>
<div class="form-group" id="OtherSpecifyFormGroup">
#Html.LabelFor(model => model.OtherSpecify, new { #class = "control-label col-md-5" })
<div class="col-md-4 sbchanged">
#Html.TextBoxFor(model => model.OtherSpecify)
#Html.ValidationMessageFor(model => model.OtherSpecify)
</div>
</div>
Through working around with the the JS code I finally got it working!
<script>
$(document).ready(function () {
if (document.getElementById("SelectType").value != "4") {
$("#OtherSpecifyFormGroup").hide();
}
$("#SelectType").change(function () {
//alert("in function");
var value = document.getElementById("SelectType").value;
if (value != "4") {
$("#OtherSpecifyFormGroup").hide();
}
else {
$("#OtherSpecifyFormGroup").show("highlight", { color: "#7FAAFF" }, 1000);
}
});
})
</script>
By changing the inital if statement I was able to hide any value which wasn't "4", this meant that if a user selects any other value on the create screen and go into edit that "OtherSpecifyFormGroup" is hidden. The show and hide in the second part of the change was swapped around so that if any value other than "4" was selected while in edit view the textbox remained hidden but when "4" was selected then it appeared.

Categories