表单标记中的按钮不会提交或响应Javascript/Jquery



我正在尝试提交一个使用 stripe(带有"提交"类型的按钮标签(的表单,并且我做了一些调试(尝试(,我知道我的表单中的其他元素正在工作,否则我将无法看到我使用 javascript (card.mount( 挂载到表单中的输入。从字面上看,该按钮是该表单中唯一我无法以任何方式使用且不会提交的元素。

无论我使用什么方法,无论是jquery还是普通的vanilla javascript,我都无法让这个按钮对我分配的任何事件做出反应(点击时,我希望它提交表单(。它拒绝倾听。

<form action="{{ route('checkout') }}" method="post" id="payment-form">
    <div class="form-row">
        <label for="card-element">
            Credit or debit card
        </label><hr>
        <div id="card-element">
            <!-- A Stripe Element will be inserted here. -->
        </div>
        <!-- Used to display Element errors. -->
        <div id="card-errors" role="alert"></div>
    </div>
    {{ csrf_field() }}
    <button type="submit" id="button2" class="btn btn-success">Buy Now</button>
</form>
<script>
//in my javascript file
// Custom styling can be passed to options when creating an Element.
    var style = {
        base: {
            color: '#32325d',
            fontFamily: '"Helvetica Neue", Helvetica, sans-serif',
            fontSmoothing: 'antialiased',
            fontSize: '16px',
            '::placeholder': {
                color: '#aab7c4'
            }
        },
        invalid: {
            color: '#fa755a',
            iconColor: '#fa755a'
        }
    };
// Create an instance of the card Element.
    var card = elements.create('card', {
        style: style
    });
// Add an instance of the card Element into the `card-element` <div>.
    card.mount('#card-element'); //this portion works otherwise I would not be able to type anything within the form. and I can use javascript to manipulate it,
    var form = document.getElementById('payment-form');
    form.addEventListener('submit', function (event) {
        event.preventDefault();
        // here is the problem, I can't get a submit because the button I have in the form refuses to actually submit anything. It justs works like a regular button and randomly submits, ignoring the fact that it is inside the form
        stripe.createToken(card).then(function (result) {
            if (result.error) {
                // Inform the customer that there was an error.
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                // Send the token to your server.
                stripeTokenHandler(result.token);
            }
        });
    });
</script>

我不确定这是否是因为在整个项目中,我混合了两种jQuery,或者我的代码可能是错误的,但我做了三件事来帮助这种情况:

  1. 将我所有的 JavaScript 包装在 $(document(.on('ready', function(({}( 和中。
  2. 从我的按钮元素中删除了名称、类型以及除类之外的几乎所有内容。
  3. 我没有将表单 id 放入变量中,而是使用 jQuery 直接分配表单。 例如:$('#payment-form'(.on('submit', function(({}(,我必须这样做,因为当我不管所有其他东西都单独使用变量时,它仍然不起作用。

如果有人对此有实际的解释,那就太好了,但我设法解决了这个问题,并且提交实际上正在被记录。希望如果其他人遇到这个问题,他们可以提供帮助。

最新更新