简体   繁体   中英

How to update input value reflecting the current value?

I'm building a slider with a tooltip showing the updated value when the thumb is moved either by dragging or by clicking plus/minus button.

It works fine, but when I click plus/minus button AFTER dragging thumb it jumps to another position instead of continuing from where it is. How can I fix it to reflect the last value? Here's fiddle: https://jsfiddle.net/2q1rg56z/12/ .

var update_num = $('output').text() * 1;

$('.plus').on('click', function() {
    if (update_num < 100) {
        $('output').text(++update_num);
        $('input').val(update_num).trigger('input');
    } else {
        $('output').text(100);
    }
});

$('.minus').on('click', function() {
    if (update_num > 0) {
        $('output').text(--update_num);
        $('input').val(update_num).trigger('input');
    } else {
        $('output').text(0);
    }
});

(It seems that the latest value should be stored in a var, so what should be the best way to do it?)

The problem is that this line only runs once:

var update_num = $('output').text() * 1;

You should turn it into a function

var update_num = function() { return +$('output').text(); };

Now call it in your code:

if (update_num() < 100) {
  /***/
}

See this updated fiddle

Side Note: Note my use of + to convert a string to an integer.See http://www.jstips.co/en/converting-to-number-fast-way/

You have almost given the answer yourself. Whenever the slider is used, you have to update the variable update_num .

In your fiddle there is already the handler to do this:

$('.range-control > input').on('input', function() { 
    var value = this.value;
    //...

So you only have to pull up your update_num so you can access it from the scope of the slider input handler and set it the value .

I updated the fiddle to make it work: https://jsfiddle.net/2q1rg56z/14/

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