在选择框中选择不同选项时更改数字值

时间:2017-07-25 08:46:40

标签: javascript jquery html

只需在选择框中选择其他选项时更改输入类型编号的值。

我可以申请if else然后这样做但我想要一个不那么复杂且很少行代码,这很容易。 例如:如果我选择A,B,C,那么输入的值将是" A" 同样,如果我选择a,b,c那么输入的值将是" a",基本上我只想在输入类型编号中使用它们的首字母。

HTML:

<select name="number_select" id="number_select" class="number_select div_height font_size" accesskey="n">
<option value="1" selected="selected">1, 2, 3, ...</option>
<option value="2">a, b, c, ...</option>
<option value="3">A, B, C, ...</option>
<option value="4">i, ii, iii, ...</option>
<option value="4">I, II, III, ...</option>
</select>
<input type="number" name="start_number" id="start_number" class="start_number div_border font_size" value="1" min="1" max="9" accesskey="s"/>

3 个答案:

答案 0 :(得分:1)

您可以运行代码段并检查<!DOCTYPE html> <html> <head> <title>Test</title> <style type="text/css"> #container { background-color: grey; height: 45px; width: 70px; padding-top: 15px; text-align: center; vertical-align: middle; border-radius: 3px; } span { font-size: 20px; -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; } </style> </head> <body> <div id="container"> <span id="left"> &#x21D0; </span> <span id="number"> 0 </span> <span id="right"> &#x21D2; </span> </div> <script src="http://code.jquery.com/jquery-3.2.1.slim.min.js"></script> <script type="text/javascript"> $('#left').click(function() { number = $('#number'); if (number.html() != '0') { number.html(parseInt(number.html()) - 1); } }); $('#right').click(function() { number = $('#number'); if (number.html() != '10') { number.html(parseInt(number.html()) + 1); } }); </script> </body> </html> 中的值,但这些值不会反映在console.log中,因为您已将其类型定义为input

number
$("#number_select").change(function() {
  var selectedValue = $(this).find("option:selected").text();
  console.log("Initials: " + selectedValue[0]);
  $("#start_number").val(selectedValue[0]);
});

答案 1 :(得分:0)

$("#number_select").change(function() {
  var option = $(this).find("option:selected").text();
  if ($.isNumeric( option[0] ))
    $("#start_number").attr("type", "number");
  else 
    $("#start_number").attr("type", "text");
  $("#start_number").val(option[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="number_select" id="number_select" class="number_select div_height font_size" accesskey="n">
<option value="1" selected="selected">1, 2, 3, ...</option>
<option value="2">a, b, c, ...</option>
<option value="3">A, B, C, ...</option>
<option value="4">i, ii, iii, ...</option>
<option value="4">I, II, III, ...</option>
</select>
<input type="number" name="start_number" id="start_number" class="start_number div_border font_size" value="1" min="1" max="9" accesskey="s" />

答案 2 :(得分:-1)

试试这个:

$('#number_select').change(() => {
    $('#start_number').val($('#number_select').val());
});