运行keyup函数()并更改函数()以获得一个结果

时间:2017-09-14 21:24:39

标签: javascript jquery

我正在尝试创建一个选择选项和一个输入字段。当用户选择option1并输入2时,结果为:10(随选项更改)* 2 = 20。如果用户更改所选选项,结果将会更改。我正在尝试使用keyup函数调整脚本()并更改函数()但更改函数()不起作用:



$("#mytextfield").on('keyup change', function() {
  let getValue;

  if ($("#totaldays").children(":selected").attr("id") == 'a') {
    getvalue = 10;
  }

  if ($("#totaldays").children(":selected").attr("id") == 'b') {
    getvalue = 20;
  }
  if ($("#totaldays").children(":selected").attr("id") == 'c') {
    getvalue = 30;
  }

  var total = getvalue * $(this).val()
  $(".total").html(total);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="totaldays">
        <option id="a">option 1</option>
        <option id="b">option 2</option>
        <option id="c">option 3</option>
    </select>
<input type="text" name="per_day" id="mytextfield" value="" />
<p>Total: <span class="total"></span></p>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:2)

var $dropdown = $('#totaldays');
 var $input = $('#mytextfield');

$dropdown.on('change', calculateCount);

$input.on('keyup change', calculateCount);

function calculateCount() {
  var dropDownValue = $dropdown.find('option:selected').attr('id');
  var inputValue = parseInt($input.val(), 10);
  var getvalue = 10;

  if (dropDownValue === 'b') {
    getvalue = 20;
  } else if ( dropDownValue === 'c') {
    getvalue = 30;
  }

  var total = getvalue * inputValue;

  $(".total").html(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="totaldays">
        <option id="a">option 1</option>
        <option id="b">option 2</option>
        <option id="c">option 3</option>
    </select>
<input type="text" name="per_day" id="mytextfield" value="" />
<p>Total: <span class="total"></span></p>

change处理程序与下拉列表相关联。 在您的情况下,只需将您的代码包装在document.ready处理程序中,以确保在文档准备就绪后绑定事件。

$(function() {

    // Your code here

});

答案 1 :(得分:1)

您根本没有在选择中收听更改事件,而只是在输入字段上收听更改事件。我将事件处理程序解压缩到一个单独的函数中,并将它用于两个事件:

function doStuff() {
    let getValue;

    if ($("#totaldays").children(":selected").attr("id") == 'a') {
        getvalue = 10;
    }

    if ($("#totaldays").children(":selected").attr("id") == 'b') {
        getvalue = 20;
    }
    if ($("#totaldays").children(":selected").attr("id") == 'c') {
        getvalue = 30;
    }
    var total = getvalue * $('#mytextfield').val()
    $(".total").html(total);
}
$("#mytextfield").on('keyup', doStuff);
$("#totaldays").on('change', doStuff);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="totaldays">
    <option id="a">option 1</option>
    <option id="b">option 2</option>
    <option id="c">option 3</option>
</select>
<input type="text" name="per_day" id="mytextfield" value="" />
<p>Total: <span class="total"></span></p>

答案 2 :(得分:1)

您还可以触发其他元素的更改:

application/json