无法将输入值分配给 JQuery 中的变量 - var newserial = $(“#myserial”).val()

Can't assign input value to a variable in JQuery - var newserial = $("#myserial").val();

本文关键字:newserial var val #myserial 变量 输入 分配 JQuery      更新时间:2023-09-26
Model #     : <input type="text" name="model" id="newmodel" value="" >
Serial #    : <input type="text" name="fserial" value="" class="serialClass" id="myserial">
in script I have: enter code here

<script>
       //Here I can't get the value of serial# with the id="myserial"
       var newserial = $("#myserial").val();
    
    
    	$(document).ready(function(){
    		$('#myserial').change(function(){
            //this is a test alert, (OUTPUT = "seial number: undefined variable"), which means that 
    		alert("serial number: "+ newserial);
    			
               $.ajax({
    				type: 'GET',
    				url: 'toshGet.php',
                    //upon success, pass newserial
    				data: {keyword: newserial},
    				success: function(msg){
    					$('#txtHint').html(msg);
    				}
    			});//ajax()
    		});//change()
    	});//document.ready()   
    </script>

我知道这真的很奇怪,但无法将文本输入的值分配给变量"newserial"。到目前为止,这是一段代码:

您在这种情况下的问题是,当变量在 DOM 中未正确呈现时,您将带有 id 'myserial' 的元素分配给变量。

与其在外部分配var newserial = $("#myserial").val(); document.ready()请尝试以下操作:

var newserial;
$(document).ready(function(){
  newserial = $("#myserial").val();
  ....
});

或者(如果您希望更新'#myserial'值,则(

在更改事件处理程序本身中使用var newserial = $("#myserial").val();var newserial = $(this).val();

只需直接赋值,而无需在 ajax 调用中获取任何额外的变量,如下所示:

data: { keyword: $("#myserial").val() }, //or $(this).val()

旁注:- 您的alert("serial number: "+model);是绝对错误的,因为您的代码中没有带有名称模型的变量。