简体   繁体   中英

Resetting a jQuery input field character countdown after the form has been submitted

I aim to limit a form input to 220 characters. I can do this with some server side PHP and the maxlength attribute.

My problem relates to a character countdown I am displaying on the page which shows the user how many characters they have left before they've reached the maximum they can type in the input field.

I've got as far as the demo below.

Demo: http://jsfiddle.net/GPmq8/

You will see that the counter decreases as the user types into the input field. This bit is working.

After the user has submitted the form, I'd like the counter to return to 220 (ie reset itself). How can I modify my script to do that? Note , my form is submitted via AJAX so there is no page reload.

I don't see any form tag in your example, but you can try when someone click submit restore the values of the input

<input type="text" placeholder="Type something..." class="form-entry" name="form-entry" rows="1" maxlength="220" value="" />
<div><button name='Mybutton' id='MyButton'>Submit</button></div>
<hr />
<span class="countdown"></span>

function updateCountdown() {
    // 220 is the max message length
    var remaining = 220 - jQuery('.form-entry').val().length;
    jQuery('.countdown').text(remaining + '');
}

jQuery(document).ready(function($) {
    updateCountdown();
    $('.form-entry').change(updateCountdown);
    $('.form-entry').keyup(updateCountdown);

    $('#MyButton').click(function(){
        jQuery('.countdown').text('220');
        jQuery('.form-entry').val('');

    });

});

http://jsfiddle.net/GPmq8/

Just reset the input field to an empty string after submitting it. Your counter will be reset by your present code. You can do this by adding the following line to your script where your ajax returns (eg. success ).

$.ajax({
     type: "POST",
     url: '/YOUR.php',
     data: formData,
     success: function (data) {
          $('.form-entry').val(''); 
     }
 });

在ajax调用成功的情况下,重置您的东西。

You could do something like:

function resetCountdown(){
 $('.countdown').text('220');
 $('.form-entry').val('');  
}

$.ajax( "example.php" )
  .done(function() {
    resetCountdown();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM