更改另一个字段中的值

Changing a value from another field

本文关键字:字段 另一个      更新时间:2023-09-26

我正在尝试更改从另一个字段的javascript(jQuery)设置的值。我只想针对这个值中的一个单词。这是我的代码(http://jsfiddle.net/zL4pc90d/):

<html>
<head>
  <title>jQuery get input Text value example</title>
  <script
  src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
  type="text/javascript"></script>
  <script
  src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"
  type="text/javascript"></script>
  <script type="text/javascript">
    $(function() {
      $("#select_car").change(function()
      {
        if ($("#select_car").val() == "")
        {
          terms = "";
        } else if ($("#select_car").val() == "Honda")
        {
          terms = "One year lease on <car>.";
        } else if ($("#select_car").val() == "Toyota")
        {
          terms  = "Two year lease on <car>.";
        } else if ($("#select_car").val() == "Ford")
        {
          terms = "Three year lease on <car>.";
        }
        $("#contract").val(terms);
      });
    }); 
  </script>
  <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <div>
    <form>
      <fieldset>
        <legend>jQuery Get and Set input Text value</legend>
        <p>
          <label for="carModel">
            Car Model:
          </label>
          <input id="myInputText" type="text" name="inputBox" />
        </p>
        <p>
          Make:
          <select id="select_car">
            <option value></option>
            <option value="Honda">Honda</option>
            <option value="Toyota">Toyota</option>
            <option value="Ford">Ford</option>
          </select>
        </p>
        <p>
          <label for="contract">
            Contract:
          </label>
          <input id="contract" type="text" name="outputBox" readonly="readonly" />
        </p>
      </fieldset>
    </form>
  </div>
</body>
</html>

对于新值,无论它在哪里写着",我都希望它是我在第一个输入字段中输入的值。我也更喜欢动态地执行,所以可能会调用keyup函数之类的。我该怎么做?

您可以使用input事件来跟踪用户在您的输入字段中输入的内容,并根据另一个框更新值

 $("#myInputText").on("input", function () {
        if ($("#myInputText").val() != "") {
            terms = "Three year lease on " + $("#myInputText").val();
        } else terms = terms = "Three year lease on <car>";
        $("#contract").val(terms);
    });

查看演示小提琴