Search code examples
jqueryotree

How to label an oTree Slider widget using a jQuery selector?


I am trying to label a slider as in jQuery UI Slider Labels Under Slider. I am not dealing with a ui-slider however, but rather with the slider widget from oTree.

The excellent answer to the question Mandatory slider in oTree/django explains how to use a jQuery selector to select an oTree slider:

$('[data-slider] input[type="range"]')

I have a slider that shows the current selected value (0-100). What I would like to do is to add a few labels below the slider (e.g. "cold", "neutral", "warm" if the slider value is a temperature). I tried the following code to select the oTree slider and append labels, but no labels appear.

{% formfield player.mySliderInput type="Slider"}

{% block scripts %}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var mylabel = $('<label>25</label>').css('left', '25%');
    $('[data-slider] input[type="range"]').append(mylabel);
});
</script>
{% endblock %}

The HTML of the page looks as follows:

<div class="form-group required">     
  <label class="col-form-label" for="id_myInput">How hot is it? (0-100):</label>
  <div class="controls  field-myInput">
    <div class="input-group slider" data-slider>
      <input type="range" name="myInput" value="None"
        step="1"
        min="0"
        max="100"
        required
        id="id_myInput"
        class="form-control"
      />

      <div class="input-group-append">
        <span class="input-group-text" data-slider-value title="current value"></span>
      </div>
    </div>
  </div>
</div>

I am unsure of which object (div? input?) to select and append the labels to.


Solution

  • Update..

    As per OP comments, the selector that ended up being appended to for the oTree slider was .controls

    var $label = $('<label>sometext</label>').css('left', '10%'); 
    $('.controls').append($label);
    

    Original...

    Using the has attribute selector (https://api.jquery.com/has-attribute-selector/) you can select by an attribute.

    <input type="range" data-slider="someval">
    

    Given above html.. You can select it with...

    [data-slider] 
    

    Adding in input[type="range"] will further qualify result to only include type range.