Javascript运行在onChange而不是onLoad

Javascript run onChange not onLoad

本文关键字:onLoad onChange 运行 Javascript      更新时间:2023-09-26

我有一个非常简单的Javascript,工作完美的onLoad,但我需要它的工作onChange

我的脚本;

<form action="" method="post" name="product_search">
    <p><strong>Existing Part Number:</strong>
      <input name="v_prodref" type="text" id="v_prodref" size="25" maxlength="25" onChange="searchValue()"> 
      <input type="text" name="prodref" id="prodref">
      <input type="submit" name="search_Submit" id="search_Submit" value="Submit">
    </p>
    <div>
    <%=(rs_ProductCheck.Fields.Item("prodref").Value)%>
    // <%=(rs_ProductCheck.Fields.Item("proddesc").Value)%></div>
    <script>
        function searchValue() {
        var add = "NW";
        var c_ProdRef = document.getElementById('v_prodref');
        if(c_ProdRef.search(/GST/i) == -1) {
        n_ProdRef = c_ProdRef.concat(add) }
        else {
        n_ProdRef = c_ProdRef.replace(/GST/i,"NWGST") }
        document.getElementById("prodref").value = n_ProdRef;
        }
        </script> 
    </form>

所以,我在第一个文本框中输入零件号,我希望我的javascript运行并在第二个文本框中输入新值,但它似乎不起作用。

我错过了什么?

searchHTMLInputElement上不存在。你需要使用c_ProdRef.value.search .

(实际上,由于您在许多地方使用它作为字符串,而不是作为输入,因此您可能打算将c_ProdRef定义为var document.getElementById('v_prodref').value)

加载时也会看到这个错误

你想要onkeyup,如果它工作完美的onLoad,你想开始在文本框1输入一些东西和javascript运行,你不希望onchange

聚焦元素模糊后onchange触发

onkeyup在您释放键盘输入后触发

感谢大家的帮助。经过一些调整,我已经设法让我的代码工作。

function myFunction() {
    var add = "NW";
    var c_ProdRef = document.getElementById('v_prodref').value;
    if (c_ProdRef.search(/GST/i) == -1) {
        n_ProdRef = c_ProdRef.concat(add)
    } else {
        n_ProdRef = c_ProdRef.replace(/GST/i, "NWGST")
    }
    document.getElementById("prodref").value = n_ProdRef;
}

加上@indubitablee建议的onKeyup和指定我的第一个文本字段的.value,它都工作了