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

时间:2019-03-29 04:40:40

标签: javascript php jquery html laravel

我正在尝试提交一个使用条纹的表单(类型为“提交”的按钮标签),并且进行了一些调试(尝试),我知道表单中的其他元素正在工作,否则我不会能够查看我使用javascript(card.mount)装入到表单中的输入。从字面上看,按钮是该表单中我无法以任何方式利用的唯一元素,也不会提交。

无论我使用哪种方法,无论是jquery还是常规的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>

1 个答案:

答案 0 :(得分:0)

我不确定这是否是因为在整个项目中,我同时使用了jQuery,或者我的代码错了,但是我做了三件事来帮助这种情况:

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

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