问题描述
我的目标是用户可以通过两种方式调整 Belopp,通过输入字段或通过滑块。后者现在正在工作,所以一个问题还没有解决。
我希望我的滑块根据输入字段中输入的值进行调整
在截图中,Belopp 的值为 40。但范围滑块仍在中间。因为输入的值为40,所以应该在最左边是不正确的。
我的 HTML:
<div class="col-12 mx-auto ">
<div class="slider-wrapper slider-ghost">
<input class="input-range"
id='priceSlider'
type="text"
data-slider-min="40"
data-slider-tooltip="hide"
data-slider-max="120"
data-slider-step="1"
data-slider-value=""
/>
</div>
</div>
和我的 JS,我已经将滑块的值分配给 newBeloppValue 但范围滑块不会移动。
$(document).ready(function () {
$("#belopp").change(function () {
let newBeloppValue = parseFloat($("#belopp").val());
if ($("#belopp").val().length > 0) {
// belopp value should not be lower or higher than the minmax range
if (newBeloppValue < minValue || newBeloppValue > maxValue) {
console.log("error");
} else {
//value of slider should get the input value
$("#priceSlider").slider({
value: newBeloppValue,});
}
}
});
$("#priceSlider").slider();
$("#priceSlider").on("slide",function (slideEvt) {
// slider value will be displayed on the belopp input
$("#belopp").val(slideEvt.value);
});
}); })
我在这里遗漏了什么?
解决方法
您需要从滑块中获取 min 和 max 值以比较输入的值是否在范围内,并在滑块中设置此值使用 $("#priceSlider").slider('setValue',newBeloppValue);
演示代码:
$(document).ready(function() {
$("#belopp").keyup(function() {
//get min & max values from slider
let minValue = $("#priceSlider").data('slider-min')
let maxValue = $("#priceSlider").data('slider-max')
console.log(minValue + " " + maxValue)
let newBeloppValue = parseInt($("#belopp").val());
if ($("#belopp").val().length > 0) {
if (newBeloppValue < minValue || newBeloppValue > maxValue) {
console.log("error");
} else {
//set same inside slider
$("#priceSlider").slider('setValue',newBeloppValue);
}
}
});
$("#priceSlider").slider();
$("#priceSlider").on("slide",function(slideEvt) {
// slider value will be displayed on the belopp input
$("#belopp").val(slideEvt.value);
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.css" integrity="sha512-SZgE3m1he0aEF3tIxxnz/3mXu/u/wlMNxQSnE0Cni9j/O8Gs+TjM9tm1NX34nRQ7GiLwUEzwuE3Wv2FLz2667w==" crossorigin="anonymous" />
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.min.js" integrity="sha512-f0VlzJbcEB6KiW8ZVtL+5HWPDyW1+nJEjguZ5IVnSQkvZbwBt2RfCBY0CBO1PsMAqxxrG4Di6TfsCPP3ZRwKpA==" crossorigin="anonymous"></script>
<div class="col-12 mx-auto ">
<div class="slider-wrapper slider-ghost">
<input class="input-range" id='priceSlider' type="text" data-slider-min="40" data-slider-tooltip="hide" data-slider-max="120" data-slider-step="1" data-slider-value="40" />
</div>
</div>
<input type="text" id="belopp">