簡體   English   中英

如何將JavaScript的字符串變量傳遞給html表單輸入,

[英]how to pass string variable of JavaScript to html form input,

就像我有數組name[1]='ahmad'元素,並且希望將其以html形式發布一樣。

我用了

document.getElementById('n').value=name[1];

但它沒有發布。

表格有:

<input type="text" id="n" readonly="true">

我想按用戶填充數組,並在網頁的輸入只讀框中顯示這些值。 完整的代碼是:

<!dochtml html>
<title>Arrays of Js</title><!--different methods of using declaring arrays-->
<head>
<h3>Arrays usage by AFRN</h3>
    <script>
    alert('hey');
    var names=[];
    //var n = prompt('enter name');
        for(var i=0; i<=4; i++){
            names[i]=prompt('enter name: ');
        }
    /*var ids=['r1','r2','r3','r4','r5']
        for(var i=0; i<=4; i++){
            document.getElementById(ids).value=name[i];
        }*/
    document.getElementById("r1").value=names[0];
    document.getElementById("r2").value=names[1];
    document.getElementById("r3").value=names[2];
    document.getElementById("r4").value=names[3];
    document.getElementById("r5").value=names[4];
    </script>
        <noscript>JS not supported</noscript>
</head>
<body bgcolor="yellow">
    <form name="arryForm">
        <input type="text" id='r1' name="a1" readonly="true"> 
        <input type="text" id='r2' name="a2" readonly="true"> 
        <input type="text" id='r3' name="a3" readonly="true"> 
        <input type="text" id='r4' name="a4" readonly="true"> 
        <input type="text" id='r5' name="a5" readonly="true"> 
    </form>
</body>
</html> 

您可以嘗試此代碼! 將您的javascript代碼放在body中的輸入標簽下方,就不能使用變量名'name',我認為這在javascript中是不允許的,因為我也遇到了可變名稱'name'的問題,因此我在使用'_name'。

 var _name = ["usman","ahmed"]; document.getElementById("n").value = _name[1]; 
 <input type="text" id="n" readonly="true"/> 

如果將<script>標記及其內容移動到底部</body>標記之前的底部,它將起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM