简体   繁体   中英

Reset SPAN value to Default

I have the following HTML code and would like to reset the SPAN value back to 0. Textarea and textbox both works fine.

HTML

<div id="Match">FULL MATCH: <span class="fullMatch">0</span></div>
<input type="text" id="c-match" value="" />

JS

jQuery('.c-reset').on('click', function() {
    jQuery('span').text(''); //this only removes the values without reverting back to 0
    jQuery('textarea, #c-match').val(function() {
        return this.defaultValue;
    });
});

Any help will be much appreciated. Thanks

try html() instead of text() :

jQuery('span').html('0');

Update: span doesn't have a default value, you have to manually set it's content.

jQuery('span').text('0'); will also work

There are several ways to do this I will suggest two that I personally consider the best:

Store default value in variable

jQuery.ready(function(){//ready function
    var spanDefault = jQuery('#Match span').text();
    jQuery('.c-reset').on('click', function() {
        jQuery('textarea, #c-match').val(function() {
            setTimetou(function(){
                jQuery('#Match span').text(spanDefault);
            }, 1);
            return this.defaultValue;
        });
    });
});

Using data attribute

Set in <span> the attribute data-value="0" , see:

<div id="Match">FULL MATCH: <span data-value="0" class="fullMatch">0</span></div>
<input type="text" id="c-match" value="" />

JS:

jQuery('.c-reset').on('click', function() {
    var fullMatch = jQuery('#c-match span');
    fullMatch.text(fullMatch.data("value"));

    jQuery('textarea, #c-match').val(function() {
        return this.defaultValue;
    });
});

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