VeloxTheFox
VeloxTheFox

Reputation: 23

jQuery reaction to slider change

So I have table data HTML element I want to reflect whatever value a slider has.

<td id="firstBox"></td>
<td>
    <div class="sliderHolder">
        <input type="range" min="1" max="10" step="1" id="first">
    </div>
</td>

Now, when I used normal JavaScript code, I could change the value of the #firstBox

firstSlider.oninput = function(){
    document.getElementById("firstBox").innerHTML = this.value;
}

But when I tried to use jQuery, I couldn't do anything (not even put a simple static int or string value)

firstSlider.oninput = function(){
    $("#firstBox").val(this.value);
}

ps.: even giving the HTML elements a name attribute haven't helped

Upvotes: 1

Views: 66

Answers (4)

Kevin
Kevin

Reputation: 1357

The HTML5 does only handle one value between min and max attribute. If you want to have the slide handle a min and a max value in one UI-input you could possibly use jQueryUI's slider: https://jqueryui.com/slider/#range

var value = $("input[type=range]").val();
$('#val').html(value)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="1" max="10" value="7" step="1" id="first">

<p id="val"></p>

Upvotes: -1

Tomir Rogi Szawok
Tomir Rogi Szawok

Reputation: 609

In first example (vanilla JavaScript) you are directly setting innerHTML of #firstBox, whilist in second example you are setting #firstBox value. This is not right as firstBox is not an input so it doesn't really have a value.

To set it's inner html using jQuery you should do something like this

$('#firstBox').html(this.value);

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

td elements don't have a value. Use text() instead.

jQuery(function($) {
  $('#first').on('input', function() {
    $("#firstBox").text(this.value);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td id="firstBox">5</td>
    <td>
      <div class="sliderHolder">
        <input type="range" min="1" max="10" step="1" id="first" value="5" />
      </div>
    </td>
  </tr>
</table>

Upvotes: 3

Emiel Zuurbier
Emiel Zuurbier

Reputation: 20944

The jQuery equivalent of .innerHTML is the .html() method. Right now you are adding this.value to the value attribute of the #firstBox element.

So try this instead.

firstSlider.oninput = function(){
    $("#firstBox").html(this.value);
}

Upvotes: 3

Related Questions