如何使用string,for循环添加表单文本框的值

时间:2011-12-09 11:53:26

标签: javascript html

大家好我是js和html的新手。我需要一个o / p,因为当点击按钮时应该显示在表单中输入的所有内容... 我的代码用于将所有输入数据的alert单独提供 如何使用字符串添加表单文本框的值,for循环都应该只在javascript中...或者用我说的条件给出你自己的代码....

<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
function processFormData() 
{
var len= document.getElementsByTagName('name');

var str1=null;
for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);

str=str1+str; 
 }
  alert(str);

}

</script>
</head>
<body>

<form name ="subscribe" > 
    <p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
    <p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">


</form>
</body>
</html>

4 个答案:

答案 0 :(得分:0)

<html>
<head>
<title>elements in a form</title>
<script type="text/javascript">
var str1=null;
function processFormData() 
{
var len= document.getElementsByTagName('name').length;

for(i=0;i<=len;i++)
{
var str=(subscribe.name[i].value);

str1=str1+str; 
 }
  alert(str1);

}

</script>
</head>
<body>

<form name ="subscribe" > 
    <p><label for="name">Your Name: </label><input type="text" name="name" id="txt_name" value="name"></p>
    <p><label for="email">Your Email: </label><input type="text" name="email" id="txt_email" value="mail"></p>
<input type="button" value="submit" onclick="processFormData()">


</form>
</body>
</html>

您使用str代替str1时犯了一个小错误;现在使用上面的代码。

答案 1 :(得分:0)

尝试开始

var len= document.getElementsByTagName('input').length; 
// add that you want the number of element
// Change 'name' for 'input' when using 'name' you are looking for <name in the HTML
// if you want the element with the name ABC use getElementsByName()

var str1='';
for(i=0;i<=len;i++)
{
    var str=(subscribe[i].value);

    str1=str1+str; 
 }
  alert(str1);

jsFiddle示例(在jQuery中调用函数):http://jsfiddle.net/DavidLaberge/HPuhg/1/

答案 2 :(得分:0)

尝试类似:

function processFormData() {
    var inputs = document.getElementsByTagName("input"),
        i,
        len,
        stringBuffer = [],
        str;

    for (i = 0, len = inputs.length; i < len; i++) {
        if (inputs[i].type.toLowerCase() === "text") {
            stringBuffer.push(inputs[i].value);
        }
    }

    str = stringBuffer.join(""); // str contains concatenated values of all inputs
}

答案 3 :(得分:0)

试试这个:

function processFormData() 
{
var len= document.getElementsByTagName('input').length;


var str = '';
for(i=0;i<len-1;i++)
{
 str += document.subscribe[i].value;

}
  alert(str);

}