How to apply javascript to only 1 of 2 form submit

2019-07-18 13:06发布

Hi I'm using this script to prevent users from submitting specific blank form text input fields. Does a great job but I have 2 submit buttons within 1 form and I need this to work for only 1. Is there any way to make this code below apply to 1 specific button using the button id or name?

 <script type="text/javascript">
    $('form').on('submit', function () {
        var thisForm = $(this);
        var thisAlert = thisForm.data('alert');
        var canSubmit = true;
        thisForm.find('[data-alert]').each(function(i) {
            var thisInput = $(this);
            if ( !$.trim(thisInput.val()) ) {
                thisAlert += '\n' + thisInput.data('alert');
                canSubmit = false;
            };
        });
        if( !canSubmit ) {
            alert( thisAlert );
            return false;
        }
    });
    </script>

2条回答
一纸荒年 Trace。
2楼-- · 2019-07-18 13:45

Your first line:

 $('form').on('submit', function () {

will take all form elements in the document. You can change the 'form' part of that to the ID of the form element i.e.

 $('#form1').on('submit', function () {
查看更多
叼着烟拽天下
3楼-- · 2019-07-18 13:49

You have one form and two submit buttons which, by default, will both submit the form. To prevent one button from submitting, add a click handler that both prevents the default submit action and does whatever else you want that button to do.

HTML

<form id="form1">
    <input type="text" value="something" />
    <input id="submit1" type="submit" value="send" />
    <input id="submit2" type="submit" value="ignore" />
</form>

JavaScript

$('#submit2').on('click', function (event) {
    event.preventDefault();
    // Form will not be submitted
    // Do whatever you need to do when this button is clicked
});


$('form ').on('submit ', function () {
    var thisForm = $(this);
    var thisAlert = thisForm.data('alert');
    var canSubmit = true;
    thisForm.find(' [data - alert]').each(function (i) {
        var thisInput = $(this);
        if (!$.trim(thisInput.val())) {
            thisAlert += '\n ' + thisInput.data('alert ');
            canSubmit = false;
        };
    });
    if (!canSubmit) {
        alert(thisAlert);
        return false;
    }
});

Demo https://jsfiddle.net/BenjaminRay/ccuem4yy/

查看更多
登录 后发表回答