2011-09-20 107 views
2

我用ajax發佈了一些數據,並想更改按鈕文本。我不知道從哪裏開始。我到目前爲止的代碼如下:用jquery修改按鈕後的文本

$("input[type='button'][name='Subscribe']").click(function(e){ 
$.ajax({ 
    type: "POST", 
    url: "test.php", 
    data:{ 
    id: $(this).attr('id'), 
    idMembers: $(this).attr('idMembers') 
    }, 
    success: function(msg){ 
     alert("Subscribed"); 

    } 
}) 
}); 
+0

$('#buttonid')。val('micimacko');或在你的情況下 $(this).val('rofibeka'); – Jauzsika

回答

5
$("input[type='button'][name='Subscribe']").click(function(e){ 
$this = $(this); 
$this.val("processing") // or: this.value = "processing"; 
$this.prop('disabled', true); // no double submit ;) 
$.ajax({ 
    type: "POST", 
    url: "test.php", 
    data:{ 
    id: $this.attr('id'), 
    idMembers: $this.attr('idMembers') 
    }, 
    success: function(msg){ 
     alert("Subscribed"); 
     $this.val("i'm finally done!"); // pfewww, that's was hard work! 
    } 
}) 
}); 
+0

以上和以上,非常感謝 – Textus

0
$("input[type='button'][name='Subscribe']").attr('value', 'newvalue here!'); 
2

試試這個:

$("input[type='button'][name='Subscribe']").click(function(e){ 

$(this).text('My new text'); 

$.ajax({ 
    type: "POST", 
    url: "test.php", 
    data:{ 
    id: $(this).attr('id'), 
    idMembers: $(this).attr('idMembers') 
    }, 
    success: function(msg){ 
     alert("Subscribed"); 

    } 
}) }); 
2
$("input[type='button'][name='Subscribe']").click(function(e){ 
    var _button = $(e.target); 
    $.ajax({ 
     type: "POST", 
     url: "test.php", 
     data:{ 
     id: $(this).attr('id'), 
     idMembers: $(this).attr('idMembers') 
     }, 
     success: function(msg){ 
      alert("Subscribed"); 
      _button.val('Subscribed') 
     } 
    }) 
    }); 
0

這是在所有這些的最佳解決方案,讓您以當控制你想顯示什麼文字 -

只需添加beforeSendcomplete方法在你的jQuery請求中。下面是一個例子

// contact form handling using AJAX 
$('#contact-form').submit(function() { 
    var contactForm = $('#contact-form'), 
     btnSubmit = $('.btn-submit'); 
    $.ajax({ 
     type: contactForm.attr('method'), 
     url: contactForm.attr('action'), 
     data: contactForm.serialize(), 
     beforeSend: function() { // while sending the request the button is disabled and it shows loading spinner 
      btnSubmit.prop('disabled', true); 
      btnSubmit.html('<i class="fa fa-spinner fa-spin fa-fw btn-icon fa-2x"></i>'); 
     }, 
     complete: function() { // after the request is sent, the spinner is gone and now it's back to normal. One can submit again 
      btnSubmit.prop('disabled', false); 
      btnSubmit.html('<i class="fa fa-paper-plane fa-lg btn-icon" aria-hidden="true"></i> Submit'); 
     }, 
     success: function(response) { 
      if (response == 'success') { 
       alert("Hi, your query has been sent. I will be back to you soon. Thank you :)"); 
      } else { 
       var erroMsg = response.split('<br/>').join('\n'); 
       alert(erroMsg); 
      } 
     } 
    }); 
    return false; 
}); 

正如你可以看到beforeSend使您能夠控制發送請求時,該怎麼辦,complete讓你在何時請求發送成功會發生什麼控制。

希望它有幫助。謝謝。