【问题标题】:Javascript output to textbox based on another textbox value基于另一个文本框值的 Javascript 输出到文本框
【发布时间】:2012-12-14 00:43:09
【问题描述】:

我正在尝试创建一个 javascript 表单,其中有一个将单词输出到文本框中的输入,然后根据该框中某些单词(不是确切的短语)的存在,在另一个文本框中有第二个输出。 我有一种感觉,它可能需要一个 .search 命令和一些与正则表达式有关的东西,但我正在努力弄清楚如何实现它。

以下不是最终实现,而是相同思想的一个示例形式:

<html>
<head>
<script type="text/javascript">

function calculate(){

var input = document.input.value;
var output1 = document.output1.value;

if (input = 1){
output1 = "x type 1";
}

else if (input = 2){
output1 = "y type 1";
}

else if (input = 3){
output1 = "y type 2";
}

if (output1.search("type 1"){
document.output2.value = "z";
}

}
</script>
</head>
<body>
<form>
Input<input type="textbox" name="input"><br>
<input type="button" onclick="calculate()" value="Calculate" /><br>
<textarea rows="2" name="output1" ></textarea>
<textarea rows="2" name="output2" ></textarea>
</form>
</body>
</html>

所以我试图让函数搜索文本框“output1”,如果它在此示例中包含单词“type 1”,那么它将输出一些内容到文本框“output2”中。我不认为作为输入结果的 output1 在这个例子中是有效的(不知道为什么),但我主要是想根据 box output1 中包含的单词来找出 output2。

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • input = 1 将永远为真。您需要在if 语句中使用===== 运算符,而不是赋值运算符。您还有一个缺少) 的语法错误。查找错误的第一步正确缩进您的代码并使用JSLint

标签: javascript forms search textbox output


【解决方案1】:

我猜你要找的是String.indexOf()。示例:

var input = 'here i have some words';
var out;

if (input.indexOf('some') !== -1) {
    out = 'I have some in input!';
}

【讨论】:

    【解决方案2】:

    您的代码有几个错误标记,这些错误如下:

    1. document.input.value 而不是 document.getElementById("input").value
    2. var output1 = document.output1.value; 而不是 var output1;
    3. 如果方法改变input = 1而不是input == 1
    4. 更改 document.output2.value 而不是 document.getElementsByName("output2").value
    5. 为设定值添加document.getElementsByName("output1").value=output1;
    6. html元素中添加id

    我曾经从 id 获取元素,所以如果你使用其他方式学习 javaScript,我会添加到 html 元素中

    我认为您应该需要learn JavaScript

    重新格式化您编写的 systex 代码我修复了很多错误并遵循完整代码:

    function calculate(){
    var input = document.getElementById("input").value;
    var output1;
    if (input == 1){
    output1 = "x type 1";
    }
    
    
    else if (input == 2){
    output1 = "y type 1";
    }
    
    else if (input == 3){
    output1 = "y type 2";
    }
    
    if (output1.search("type 1")){
    document.getElementById("output2").value="z";
    }
    document.getElementById("output1").value=output1;
    
    }
    <form>
    Input<input type="textbox" name="input" id="input"><br>
    <input type="button" onclick="calculate()" value="Calculate" /><br>
    <textarea rows="2" name="output1" id="output1"></textarea>
    <textarea rows="2" name="output2" id="output2"></textarea>
    </form>

    如果有帮助或有任何问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2023-03-16
      • 1970-01-01
      • 2020-04-05
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多