简体   繁体   English

如何在JavaScript的while循环中检索文本字段的值?

[英]How to retrieve value of text field inside while loop with JavaScript?

Inside the while loop there are text boxes. 在while循环内有文本框。 There is JavaScript function called checkNum() which is use to retrieve the text box value but i don't get it how to do that? 有一个名为checkNum()的JavaScript函数,该函数用于检索文本框值,但我不知道该怎么做?

 <script> function isNumberKey(evt) { var charCode = (evt.which) ? evt.which : evt.keyCode; if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } function checkNum() { var num = document.getElementById('num'); } </script> 
 <table width="506" border="0"> <tr> <td width="189" align="center">Text One</td> </tr> <?php $i =0; $data = "select * from tbl_person"; $query = mysqli_query($conn,$data); while($row = mysqli_fetch_array($query)) { $i++; ?> <tr> <td align="center"><input type="text" name="num<?php echo $i;?>" id="num<?php echo $i;?>" onkeypress="return isNumberKey(event)"/></td> </tr> <?php } ?> </table> 

    function loopTexts(numRows)
    {
      for(var i = 1; i <= numRows; i++)
      {
        var txt = document.getElementById('txt'+i);
        var str = txt.value;
        alert(str);
      }
    }


<?php
//Some query here
    $numRows = mysqli_num_rows($resultSet);
//Loop through the result set and create the fields as you did
?>

    <input type="text" value="text1" id="txt1"/>
    <input type="text" value="text2" id="txt2"/>
    <input type="text" value="text3" id="txt3"/>
    <input type="text" value="text4" id="txt4"/>
    <input type="text" value="text5" id="txt5"/>
//echo the parameter $numRows to pass it to the JS function
    <input type="button" value="Loop!" onclick=<?php echo "loopTexts($numRows);"; ?>/>

If you don't know how many text boxes will be created during runtime, pass it as an argument to the javascript function and use it in the for loop. 如果您不知道在运行时将创建多少个文本框,请将其作为参数传递给javascript函数,然后在for循环中使用它。

Call the function in whatever event you are supposed to use it. 在您应该使用该函数的任何情况下都调用该函数。

Have the function accept the input as a parameter: 让函数接受输入作为参数:

function checkNum(input)
{
    var num = input.value;

}

Then add the onblur attribute to the field, and pass this as a parameter: 然后将onblur属性添加到该字段,并将this作为参数传递:

<input type="text" onblur="checkNum(this)" name="num<?php echo $i;?>" id="num<?php echo $i;?>" onkeypress="return isNumberKey(event)"/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM