如何根据变量值获取选项类值


<form>
    <select id="ammount">
        <option value="">- Select -</option>
        <option class="100" value="0"></option>
        <option class="200" value="5,01"></option>
        <option class="300" value="10,01"></option>
    </select>
    <input class="height" id="height" name="height" value="">
</form>
<script type="text/javascript">
    $(document).ready( function () {
        $('form').on('change', '#height', function(){
            var height  = "3,00";
            // HERE I NEED TO GRAB THE RIGHT OPTION CLASS FROM SELECT OPTIONS
        });
    });
</script>

我的问题是如何找到正确的选项并获取类名?规则是,它应选择小于高度值 (3,00( 的选项行和大于高度值 (3,00( 的第一个下一个选项行。

所以,在这种情况下,这将是<option class="100" value="0"></option>

但是,如果高度5,55则正确的选项行将是<option class="200" value="5,01"></option>的,对于10,01也是如此。

但是,对于高度 = "10,01" 或更多,右侧选项行将<option class="300" value="10,01"></option>

我在想找到第一个更大的值 (5,01( 和减去 1 行是正确的方法,但我不确定如何做到这一点。

请记住,高度可以是任何值(它来自用户键入的输入框(,并且选项是从 db 动态提取的。

这应该可以解决问题:

$(document).ready( function () {
     $('form').on('change', '#height', function(){ 
        var height  = "3,00";
        var height_num = parseFloat(height.replace(',','.'));
        var selected_item_value;
        var heights = [];
        $('#ammount option').each(function(i, item){
            heights.push(item);
        });
        $(heights.reverse()).each(function(i, item){
            if (parseFloat($(item).val().replace(',','.')) < height_num) {
                 alert($(item).val())
                 selected_item_value = $(item).val();
                 return false;
            }
        });
         $('#ammount').val(selected_item_value);
    });
});
<form>
<select id="amount">
    <option value="">- Select -</option>
    <option class="100" value="0">0</option>
    <option class="200" value="5,01">5,01</option>
    <option class="300" value="10,01">10,01</option>
</select>
<input class="height" id="height" name="height" value="55">
</form>

脚本

var t;
$('#height').focus(function () {
var that = $(this)
t = setInterval(function () {
    var height = parseFloat(that.val().replace(',', '.'))

    $('#amount').children('option').each(function () {
        var compareTo = parseFloat($(this).val().replace(',', '.'))
        var compareToNext = 0
        if ($(this).next().length > 0) 
          compareToNext =parseFloat($(this).next().val().replace(',', '.'))
        if (compareTo < height && height < compareToNext && !isNaN(height)) {
            $('#amount').val($(this).val())
        } 
        else if (compareTo < height && $(this).is(':last-child') && !isNaN(height)) {
            $('#amount').val($(this).val())
        } 
        else if (isNaN(height)) {
            $('#amount').val($('#amount').children('option:first').val())
        }

    }) //end of each
}, 500) //end of setInterval
})  //end of focus
$('#height').blur(function () {
    window.clearInterval(t)
})

演示

最新更新