简体   繁体   English

检查输入文本字段是否具有特定数值并使用 jquery 更改选择的选定选项

[英]Check if an input text field has a specific numeric value and change the selected option of a select using jquery

I have a select menu with 3 options and i want to have the 3d option selected on page load when the input text fields has value 0 (zero) and 2nd option selected when the input text field is empty.我有一个包含 3 个选项的选择菜单,当输入文本字段值为 0(零)时,我希望在页面加载时选择 3d 选项,当输入文本字段为空时选择第二个选项。 Here is my code:这是我的代码:

 /*$(document).ready(function() { if($('#price').val('0')) { $('#pricetypeselect').val()=='3'; } else if ($('#price').val('')) { $('#pricetypeselect').val()=='2'; } });*/ //HERE IS THE WORKING CODE BASED ON THE SELECTED ANSWER BELOW $(document).ready(function() { $select = $('#pricetypeselect'); $priceVal = $('#price').val(); if($priceVal=='0'){ $select.val('3') }else if($priceVal==''){ $select.val('2') } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <select id="pricetypeselect"> <option value="1">Option 1</option> <option value="2">Option 2</option> <option value="3">Option 3</option> </select> <input id="price" type="text" name="price" value="0" placeholder="price in USD $"/>

What i 'm doing wrong ?我做错了什么?

$(document).ready(function() { 
    $select = $('#pricetypeselect');
    $priceVal = $('#price').val();

    if($priceVal=='0'){
       $select.val('3')
    }else if($priceVal==''){
        $select.val('2')
     }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM