简体   繁体   English

从输入框中获取值并使用Javascript将其分配给变量

[英]Getting a Value from an Input Box and Assign it in a Variable using Javascript

Hi I'm just new to Javascript and I am trying to assign a value to a variable coming from the input box then access that variable in a loop. 嗨,我只是Java语言的新手,我想为来自输入框的变量分配一个值,然后在循环中访问该变量。 I have tried using document.getElementbyID('inputboxID').value; 我已经尝试使用document.getElementbyID('inputboxID')。value; and document.getElementbyName('inputboxName').value; 和document.getElementbyName('inputboxName')。value; but it didn't work. 但这没用。

Here's my code: 这是我的代码:

<script>
var count = 0;

$(function(){
$('p#add_field').click(function() {
var num = document.getElementById('enfonum').value;
while (count < num) {
count +=1;
$('#container').append( 
'<strong>Enforcer #'+count+'</strong><br/>'
+'<input id="field_  '+count+'"name="field[]'+'"type="text"/><br/>');
}
});
});
}
</script>

Here's the code for the input box: 这是输入框的代码:

<input type="text" id="enfonum" name="enfotxt"/>

and here's the code for the link that will trigger the script to be executed: 这是将触发脚本执行的链接的代码:

<p id="add_field">< a href="#"><span>&raquo; Add Enforcer</span></a></p>

The reason your code is not working, is simply that document.GetElementById does not exists, the correct syntax is document.getElementById . 您的代码无法正常工作的原因仅在于document.GetElementById不存在,正确的语法是document.getElementById

Here's a jsfiddle with an example. 这是一个带有示例的jsfiddle

Good luck and good continuation, 祝你好运和延续!

Cheers ! 干杯!

You have to get value of enfonum input at run-time, not storing it at num var during initial page loading. 您必须在运行时获取enfonum输入的值,而不是在初始页面加载期间将其存储在num var中。 Here is the working sample with correct code: 这是带有正确代码的工作示例:

 var count = 0; var num = document.getElementById('enfonum'); $('p#add_field').click(function () { while (count < num.value) { count += 1; $('#container').append('<p><strong>Enforcer #' + count + '</strong><br/>' + '<input id="field_' + count + '" name="field[]' + ' "type="text"/><br/></p>'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p><input type="text" id="enfonum" name="enfotxt" /></p> <p id="add_field"><a href="#"><span>&raquo; Add Enforcer</span></a></p> <div id="container"></div> 

Remove the extra } in the code, it will give you syntax error. 删除代码中多余的 } ,它将为您提供语法错误。 Tried it afterwards,the code works. 之后对其进行尝试,该代码可以正常工作。 Syntax errors can break your javascript, it is wise to use plugins like firebug for firefox to fish out javascript errors. 语法错误可能会破坏您的JavaScript,明智的做法是使用firebug之类的插件来启用 Firefox,以发现javascript错误。

Let me know if it works. 让我知道它是否有效。

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

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