将提交按钮更改为关闭按钮

Change submit button to close button

本文关键字:关闭按钮 提交 按钮      更新时间:2023-09-26

如果表单提交成功,我如何改变按钮的行为?

<form method="post" enctype="multipart/form-data" style="margin: 0;" id="frmGenerate">
    <div class="clearfix">
        <div class="input-group">
            <input type="text" placeholder="Customer Name:" name="CustomerName">
            <input type="text" placeholder="Generated Url:" name="CustomerUrl" readonly="readonly" />
        </div>
     </div>
     <div class="clearfix">
         <div class="input-group">
             <button type="submit" class="btn">Generate</button>
         </div>
     </div>
 </form>

下面是我的JS代码:

 $('#frmGenerate').submit(function(e) {
        var clientName = $(this).find('input[name="CustomerName"]').val();
        $.ajax(
            {
                url: '@Url.Action("GenerateToken","Admin")',
                type: 'GET',
                data: { customerName: clientName },
                success: function(response) {
                    if (response.result) {
                        $('#frmGenerate').find('input[name="CustomerUrl"]').val(response.message).select();
                        $('#frmGenerate').find('button.btn').text('Close');
                    } else {
                        alert(response.message);
                    }
                }
            });
        e.preventDefault();
    });

这是模态窗口,我打开它来生成令牌。当它生成成功,然后我设置生成的令牌在模态输入和改变按钮的文本关闭,但我不知道如何改变按钮的行为。

更好的方法是不改变现有的按钮,而是隐藏它并显示另一个。

HTML:

<div class="clearfix">
    <div class="input-group">
        <button type="submit" class="btn">Generate</button>
        <button type="button" class="btn btn-close hide">Close</button>
    </div>
</div>

JS:

$('#frmGenerate').find('.btn').hide();
$('#frmGenerate').find('.btn-close').show();

取决于你使用的是什么类型的按钮。按钮必须像这样使用:<button></button>不像<button/>

然后使用:

 $(".btn").html('Close');

您可以更改按钮属性

 $('#frmGenerate').find('button.btn').attr('type', 'button');

然后:

$('#frmGenerate').find('button.btn').on('click', function(){ /*close function */});

我看到您在提交表单后将按钮的文本更改为'Close'。所以剩下的部分是处理按钮点击事件的jQuery。

     $('.btn').click(function(){
         var buttonText = $(this).val();
         if(buttonText === 'Close'){
         //code when close button is clicked
         }else if(buttonText === 'Generate'){
            //code when Generate button is clicked...
         }
      });//end button.click function

我会使用input type='button'或者button而不是input type='submit'。为什么不使用ajax提交表单呢?好多了。