首页 > 解决方案 > How to change the input type range value after entering the value in the input box?

问题描述

I have an input type range and it's working. If I drag the then the value will be display in the input field. Is it possible vice versa?

I mean I can add some value n the input field and the range can drag accordingly?

enter image description here

For example, if I add 50 in the input box then I have to display the output like below

enter image description here

$("input[type=range]").on("change input", function() {
  $("[name=values]").val($(this).val()) //assign value..
})
.customRange {
  -webkit-appearance: none;
  width: 100%;
  height: 25px;
  background: transparent;
  outline: none;
  opacity: 0.7;
  -webkit-transition: .2s;
  transition: opacity .2s;
}

.customRange:hover {
  opacity: 1;
}

.customRange::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 25px;
  height: 25px;
  background: #04AA6D;
  cursor: pointer;
}

.customRange::-moz-range-thumb {
  width: 25px;
  height: 25px;
  background: #04AA6D;
  cursor: pointer;
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="w-50 mx-auto">
  <div class="d-flex justify-content-between"><label>Range</label>
    <div><input type="text" name="values" value="1">%</div>
  </div>
  <!--use value=1-->
  <input type="range" class="form-range customRange" value="1" min="1" max="100">
  <div class="d-flex justify-content-between">
    <span>1</span>
    <span>100</span>
  </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

标签: javascripthtmljquery

解决方案


Why not?

I just modify your code and add it to your file, it works.

$("input[name=values]").on("change input", function(){
    if ($(this).val()==='' || isNaN($(this).val())){
       $("input[type=range]").val(0);
    } else {
       $("input[type=range]").val($(this).val());
    }
})

Here is the demo.


推荐阅读