启用按钮,被javascript禁用

本文关键字:javascript 禁用 按钮 启用 | 更新日期: 2023-09-27 18:12:28

我禁用按钮在第一次点击,以防止交易被提交多次。如果屏幕上有一个错误,我把他们送回表单,按钮仍然被禁用,所以他们不能重新提交表单。

这是我的javascript表单:

@using SuburbanCustPortal.sessions
@model SuburbanCustPortal.Models.PaymentModel.WebPayment

@{
  ViewBag.Title = "Make a payment!";
}
@if (CurrentCustomerSession.Current.TokenShowHideSettings.ShowPaymentScreenMessage)
{
  <div class="CompanyMessage">
    @Html.Raw(@CurrentCustomerSession.Current.TokenSettings.PaymentScreenMessage)
  </div>
}
@using (Html.BeginForm("WebPaymentSubmit", "Payment", FormMethod.Post))
{
    <div>
    <fieldset>
      <legend>Please enter the amount of the payment below.</legend>
      <div class="paymentPageMargin">
        <div class="paymentBlock">
          <div class="block_container">
            <div class="serviceBox1 paymentBlockTextLeft payment-label-nomargin">
              Account Number:
            </div>
            <div class="serviceBox2 paymentBlockText payment-label-nomargin">
              @CurrentCustomerSession.Current.Branch-@CurrentCustomerSession.Current.AccountNumber
            </div>
          </div>
          @if (CurrentCustomerSession.Current.CurrentCustomer.BudgetRate > 0)
          {
            <div class="block_container">
              <div class="serviceBox1 paymentBlockTextLeft payment-label-nomargin">
                Budget Rate:
              </div>
              <div class="serviceBox2 paymentBlockText payment-label-nomargin">
                $@string.Format("{0:F2}", CurrentCustomerSession.Current.CurrentCustomer.BudgetRate)
              </div>
            </div>
            <div class="block_container">
              <div class="serviceBox1 paymentBlockTextLeft payment-label-nomargin">
                Budget Balance:
              </div>
              <div class="serviceBox2 paymentBlockText payment-label-nomargin">
                $@string.Format("{0:F2}", CurrentCustomerSession.Current.CurrentCustomer.BudgetBalance)
              </div>
            </div>
          }
          else
          {
            <div class="block_container">
              <div class="serviceBox1 paymentBlockTextLeft payment-label-nomargin">
                Account Balance:
              </div>
              <div class="serviceBox2 paymentBlockText payment-label-nomargin">
                @string.Format("{0:F2}", CurrentCustomerSession.Current.CurrentCustomer.TotalBalance)
              </div>
            </div>
          }
        </div>
        @Html.ValidationSummary(true, "Submit was unsuccessful. Please correct the following errors.")
        <div class="paymentCardTypesMargin">
          @if ((bool)CurrentCustomerSession.Current.TokenSettings.CreditCardAcceptsVisa)
          {
            <img src="../Content/images/visa.jpg" alt="Visa Card" height="27" width="42" />
          }
          @if ((bool)CurrentCustomerSession.Current.TokenSettings.CreditCardAcceptsAmex)
          {
            <img src="../Content/images/amex.png" alt="Mastercard" height="27" width="42" />
          }
          @if ((bool)CurrentCustomerSession.Current.TokenSettings.CreditCardAcceptsMasterCard)
          {
            <img src="../Content/images/mastercard.jpg" alt="Mastercard" height="27" width="42" />
          }
          @if ((bool)CurrentCustomerSession.Current.TokenSettings.CreditCardAcceptsDiscover)
          {
            <img src="../Content/images/discover.gif" alt="Mastercard" height="27" width="42" />
          }
        </div>
          <div class="payment-label width300">
          Card Holder's Name
        </div>
        <div class="editor-field width200">
          @Html.TextBoxFor(m => m.NameOnCard, new { @class = "makePaymentTextLeft width200" })          
        </div>
        <div class="block_container">
          <div class="payment-label-nomargin serviceBox1 width205">
            <p>Billing Street Address</p>
          </div>
          <div class="payment-label-nomargin serviceBox2 width75">
            <p>Billing Zip Code</p>
          </div>
        </div>

        <div class="block_container">
          <div class="serviceBox1 width200">
            @Html.TextBoxFor(m => m.StreetAddress, new { @class = "makePaymentTextLeft width200" })            
          </div>

          <div class="serviceBox2">
            @Html.TextBoxFor(m => m.Zip, new { @class = "makePaymentTextLeft width75" })            
          </div>
        </div>
        <div class="payment-label">
          Credit Card Number
        </div>
        <div class="editor-field">
          @Html.TextBoxFor(m => m.CreditCardNumber, new { @class = "makePaymentTextLeft width200", autocomplete = "off" })
        </div>

        <div class="block_container">
          <div class="serviceBox1 width120">
            <p>Expiration Date</p>
          </div>
          <div class="serviceBox2 width150">
            <p>Security Code</p>
          </div>
        </div>
        <div class="block_container">
          <div class="serviceBox1 width30">
            @Html.TextBoxFor(m => m.CreditCardExpMonth, new { @class = "makePaymentTextLeft width30", @placeholder = "MM", autocomplete = "off" })
          </div>
          <div class="serviceBox3 width30">
            @Html.TextBoxFor(m => m.CreditCardExpYear, new { @class = "makePaymentTextLeft width30", @placeholder = "YY", autocomplete = "off" })
          </div>
          <div class="serviceBox4 padLeftCvv">
            @Html.TextBoxFor(m => m.CreditCardCcv, new { @class = "makePaymentTextLeft width40", autocomplete = "off" })
          </div>
        </div>
        <div class="payment-label">
          Payment Amount
        </div>
        <div class="payment-label-nomargin focus">
          @Html.TextBoxFor(m => m.Amount, "{0:F2}", new {@class = "makePaymentTextRight width90", autocomplete = "off"})
        </div>
        <div class="paymentButton">
          <p>
            <input id="saveButton" class="typicalbutton" type="submit" value="Pay Now" />
          </p>
          <script>
            // Find ALL <form> tags on your page
            $('form').submit(function () {
              // On submit disable its submit button
              $('input[type=submit]', this).attr('disabled', 'disabled');
            });
          </script>
        </div>
      </div>
    </fieldset>
  </div>
}

当表单由于表单上的错误而无法提交时,如何重新启用该按钮?

EDIT1

这是我的控制器中的方法在提交时被调用:

[Authorize]
[SessionExpireFilter]
public ActionResult WebPaymentSubmit(PaymentModel.WebPayment model)
{
  Console.WriteLine("WebPaymentSubmit Clicked!!");
  var control = Logging.StartLog();
  control.ClassName = System.Reflection.MethodBase.GetCurrentMethod().Name;
  try
  {
    Logging.WriteLog(control, "Start WebPaymentSubmit");
    var hasErrors = false;
    if( model.Amount <= 0)
    {
      hasErrors = true;
      ModelState.AddModelError("Amount", "Invalid amount.");          
    }
    if (string.IsNullOrEmpty(model.CreditCardNumber) || LuhnsTest.IsValidCreditCardNumber(model.CreditCardNumber))
    {
      hasErrors = true;
      ModelState.AddModelError("CreditCardNumber", "Invalid credit card number.");                    
    }
    if (hasErrors)
    {
      return View("WebPayment");
    }

返回视图("WebPayment");是在值检查后返回的方式。

EDIT2

好了,我知道为什么不发布了。PaymentModel [Required]正在阻止表单继续,这就是为什么表单没有被重新加载。

如果是这种情况,如果在我的PaymentModel上所需的失败,如何启用按钮?

public class WebPayment
{
  [Required]
  [DataType(DataType.Text)]
  public string StreetAddress { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string Zip { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string NameOnCard { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string CreditCardNumber { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string CreditCardExpMonth { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string CreditCardExpYear { get; set; }
  [Required]
  [DataType(DataType.Text)]
  public string CreditCardCcv { get; set; }
  [Required]
  [DataType(DataType.Currency)]
  [DisplayFormat(DataFormatString = "{0:F2}", ApplyFormatInEditMode = true)]
  public decimal Amount { get; set; }
}

启用按钮,被javascript禁用

如果不想刷新页面,则需要在JavaScript中使用Ajax调用来处理响应。

http://jsbin.com/caguzejopu/1/edit?html, js、控制台、输出

这意味着更新你的控制器,使其在用户发出错误请求时返回响应

return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Payment declinded");

这可能不是最好的方法,但是您不能在页面加载时将按钮设置为启用吗?在初始加载时,这无关紧要,但在此之后的每次加载时,都会将其重置为启用。这样每次你加载页面时,它都是显式启用的,然后你就可以在那里随心所欲地操作它。虽然这只会在表单提交失败后重新加载页面时起作用。

如果您使用回发,则此代码在每次重新加载时重新启用按钮:

    public ActionResult Index()
    {
        return View();
    }
    [HttpPost]
    public ActionResult Index(FormCollection collection)
    {
        return View();
    }

如果你是用javascript发布,你必须在错误处理程序中重新启用。

我注意到的第二件事是您在代码块中使用jQuery。您必须确保库已经在那里加载。解决方法可能是将该代码放入scripts部分,并在jQuery加载后渲染它。

您可以在ajax调用的'done'和'fail'函数中启用按钮。

$('form').submit(function (e) {
    e.preventDefault(); // Prevent default submit action
    $('input[type=submit]', this).prop('disabled', true);
    // If you're using client side validation as well
    if ($(this).valid() === false) {
        $('input[type=submit]', this).prop('disabled', false);
        return;
    }
    // Submit manually with Ajax
    $.ajax({
        url: $('form').attr("action"),
        type: $('form').attr("method"),
        data: $('form').serialize(),
    }).done(function (data) {
        // If returning partial view
        //$("#your-form-container").html(data);
        // Else returning whole view
        $(document.body).html(data); // Haven't tested
        // I don't think you need this since the form is refreshed anyway
        $('input[type=submit]', this).prop('disabled', false);
    }).fail(function() {
        $('input[type=submit]', this).prop('disabled', false);
    });
});