仅两个按钮中的一个需要输入

Required Entry for only one button of two

本文关键字:一个 输入 按钮 两个      更新时间:2023-09-26

我有一个表单,其中包含一个文本字段,该字段是我的两 (2) 个按钮中的一个 (1) 个的必填条目。 第一个(1st)按钮将文本字段中的代码应用于我商店购物车部分中的产品。 第二个(2nd)从购物车部分的所有产品中删除所有代码。

最好的

方法是什么?

感谢。

<div id="cart-coupon-menu" class="coupon-menu-hide">
<form id="discount-coupon-form" action="<?php echo $this->getUrl('checkout/cart/couponPost') ?>" method="post">
    <div class="discount">
        <div class="discount-form">
            <input type="hidden" name="remove" id="remove-coupone" value="0" />
            <div class="input-box">
                <input class="input-text" id="coupon_code" name="coupon_code" value="<?php echo $this->escapeHtml($this->getCouponCode()) ?>" placeholder="Enter a Coupon or Promo Code" autocomplete="off"/>
            </div>
            <div class="buttons-set">
                <button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="discountForm.submit(false)" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>
                <button type="button" title="<?php echo $this->__('Cancel Coupon') ?>" class="button" onclick="discountForm.submit(true)" value="<?php echo $this->__('Cancel Coupon') ?>"><span><span><?php echo $this->__('Cancel Coupon') ?></span></span></button>
            </div>
        </div>
    </div>
</form>
</div>

上述表单将通过 AJAX 序列化并设置为控制器,并将返回适当的响应。

当输入框

为空时,我希望输入框充当必填字段并禁止通过第一个按钮提交。 但是,当它为 null 时,第二个按钮仍应允许提交。 当文本输入到输入框中时,它们都表现正常。

目前我正在尝试做这样的事情:

<script type="text/javascript">
    //<![CDATA[
    var discountForm = new VarienForm('discount-coupon-form');
    discountForm.submit = function (isRemove) {
        if (isRemove) {
            $('coupon_code').removeClassName('required-entry');
            $('remove-coupone').value = "1";
        } else {
            $('coupon_code').addClassName('required-entry');
            $('remove-coupone').value = "0";
        }
        if(something where I identify if it is required and the field is null){return null;}
        else{continue with ajax call;}

我认为这只是一个简单的JavaScript,如下所示:

<button type="button" title="<?php echo $this->__('Apply Coupon') ?>" class="button" onclick="isValid() ? discountForm.submit(false) : handleInvalid()" value="<?php echo $this->__('Apply Coupon') ?>"><span><span><?php echo $this->__('Apply Coupon') ?></span></span></button>

我在那里使用了三元运算符...所以基本上它说如果isValid()返回 true,则执行:discountForm.submit(false)否则执行:handleInvalid()

然后javascript函数将是:

function isValid() {
    var couponCode = document.getElementById('coupon_code').value;
    return /* whatever logic you want here... */
}
function handleInvalid() {
    // do whatever you want to the coupon_code input to indicate it's required and pop up an error message
    alert("Please enter a coupon code!");
}

你应该试一试淘汰赛。它根据js代码中的更改更新您的视图(html)。请参阅此示例。