且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

根据textfield中的输入更改下拉列表值

更新时间:2022-10-17 23:15:01

You could handle this by taking advantage of data-* attributes and using jQuery to determine which values should be shown based on your selection :

<!-- Assumes a valid year is entered -->
<input name="Year" type="text" value="" />

<!-- Notice your possible values data options -->
<select name="Results">
   <option selected="selected" value="">please choose:</option>
   <option value="300" data-under-18="100" data-over-18="300">300.-</option>
   <option value="500" data-under-18="200" data-over-18="500">500.-</option>
   <option value="1000" data-under-18="300" data-over-18="1000">1000.-</option>
   <option value="1500" data-under-18="400" data-over-18="1500">1500.-</option>
   <option value="2000" data-under-18="500" data-over-18="2000">2000.-</option>
   <option value="2500" data-under-18="600" data-over-18="2500">2500.-</option>
 </select>
  <script>
    $(function(){
        // When your year changes...
        $('[name="Year"]').change(function(){
            // Check that the value is a year (assumes 4 digit number)
            if(/^\d{4}/.test($(this).val())){
                // Parse the value
                var year = parseInt($(this).val());
                // Determine the user's age
                var age =  new Date().getFullYear() - year;
                // Use the data attributes to set each value (ignore the first one)
                $('[name="Results"] option:not(:first)').each(function(){
                    var valueToUse = (age >= 18) ? $(this).attr('data-over-18') : $(this).attr('data-under-18');
                    $(this).val(valueToUse).text(valueToUse);
                });
            }                
            else{
              alert('Please enter a year! (any 4-digit number will do)');
              $(this).val('').focus();
            }
        })
    })
  </script>

You can see a complete working example here and demonstrated below :