如何根据用户输入自动填充相应的字段

时间:2017-04-20 15:53:28

标签: javascript php html forms

我有一个表单,或者说有一些表单,但概念应该类似,我需要从一个字段中获取用户输入值并自动填充相应的字段。例如,为了乘以矩阵,矩阵A的行必须等于矩阵B的列。

所以,我的表格:

<?php
    case 'Multiply':
         echo "<p>Matrix Multiplication requires Matrix B to have the same number of rows as Matrix A has columns.</p>"
            . "<p> What size matrices would you like? </p>";
         echo "  <form method='POST' action='$_SERVER[PHP_SELF]' onsubmit='return param_check_mux();'>                                            
                     <p>A Rows:<input type='text' name='arows' id='arows'> A Columns:<input type='text' name='acolumns' id='acolumns'></p>
                     <p>B Rows:<input type='text' name='brows' id='brows'> B Columns:<input type='text' name='bcolumns' id='bcolumns'></p>
                     <input type='submit' value='Compile my Matrices!' name='submit'>                            
                 </form>";
    break;
?>

所以基本上,如果用户要输入“A行”字样。数字&#39; 3&#39;,我想要&#39; B列&#39;自动填充并持有&#39; 3&#39;值。我希望这也是另一种方式,所以如果&#39; B列&#39; =&#39; 3&#39;然后&#39; A Rows&#39;将=&#39; 3&#39;也。

我似乎无法在任何地方在线找到正确的示例,或者更确切地说,我不知道如何在搜索中说出问题,因为它非常具体。

提前感谢任何帮助。谢谢。

3 个答案:

答案 0 :(得分:2)

使用jQuery:

jQuery(document).ready(function()
{
    // Set the B Columns if A rows changed
    jQuery('#arows').on('change', function()
    {
        jQuery('#bcolumns').val(jQuery('#arows').val());
    });

    // Set the A rows if B Columns changed
    jQuery('#bcolumns').on('change', function()
    {
        jQuery('#arows').val(jQuery('#bcolumns').val());
    })
});

答案 1 :(得分:1)

对于这样的事情,我们会使用javascript来获取值。我试图让这个例子保持相当基本,这样你就可以很好地理解如何使用JavaScript来提取和填充值。

&#13;
&#13;
FontSize
&#13;
function fillB(){
	var anum = document.getElementById('aRow').value;
  var bnum = document.getElementById('bRow');
  bnum.value = anum;
}

function fillA(){
	var bnum = document.getElementById('bRow').value;
  var anum = document.getElementById('aRow');
  anum.value = bnum;
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以尝试在客户端使用Javascript。您可以侦听输入值的更改,然后执行相应的操作。示例:

<body>
    <form action="#" method="post">
        <div> Matrix A  <br/> 
            <label> Rows </label><input type='text' name='arows' id='arows'></input>
            <label> Columns </label> <input type='text' name='acolumns' id='acolumns' onchange=columnChange(this.value)></input>
        </div>
        <br/>
        <div>  Matrix B <br/> 
            <label> Rows </label> <input type='text' name='brows' id='brows' onchange=rowChange(this.value)></input>
            <label> Columns </label> <input type='text' name='bcolumns' id='bcolumns'>
        </div>
        <input type="submit" name="send" value="Send">
    </form>
    <script type="text/javascript">
        function columnChange(input){ 
            document.getElementById("brows").value=input;
        } 
        function rowChange(input){ 
            document.getElementById("acolumns").value=input;
        }
    </script>
</body>