javascript 如何在html复选框值参数中使用javaScript变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11924940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use javaScript variable, inside html checkbox value parameter?
提问by Roshanck
In my file I have javaScript variable name 'testJava'
在我的文件中,我有 javaScript 变量名称“testJava”
<script>
var testJava = 'script Test';
</script>
At the bottom of the page I have a checkbox. I need to add 'testJava' variable to the value of the checkbox.
在页面底部,我有一个复选框。我需要将 'testJava' 变量添加到复选框的值中。
<input type="checkbox" name="website[]" value= "I_WANT_TO_ADD_IT_HERE" />My Test<br />
value = "<script>document.write(testJava);</script>"
doesn't work
value = "<script>document.write(testJava);</script>"
不起作用
Can anyone please tell me how to do this?
谁能告诉我如何做到这一点?
回答by Yogu
You should add an id
tag to your <input>
element to identify it:
你应该id
给你的<input>
元素添加一个标签来识别它:
<input type="checkbox" name="website[]" id="thecheckbox" />
Using jQuery, it's quite easy to change the value:
使用 jQuery,更改值非常容易:
$('#thecheckbox').val(testJava);
To include jQuery, e.g. use the following script tag:
要包含 jQuery,例如使用以下脚本标记:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
回答by Moe
<script>
var testJava = 'script Test';
document.getElementById('checkbox_ID').value = testJava;
</script>
回答by Pointy
You can't directly do what you're asking, so just set the value after the fact:
你不能直接做你所要求的,所以只需在事后设置值:
<input type=checkbox id=cb1 ...> My Test
<script>
document.getElementById('cb1').value = testJava;
</script>
Also, Java and JavaScript are not the same thing.
此外,Java 和 JavaScript 不是一回事。
Make sure the <script>
is after the <input>
, or else that it's in a "load" or "ready" event handler.
确保<script>
位于 之后<input>
,否则它位于“加载”或“就绪”事件处理程序中。
回答by Shreedhar
<input type="checkbox" name="website[]" id="check_box" value= "I_WANT_TO_ADD_IT_HERE" />My Test<br />
in your script, after the dom ready,
在你的脚本中,在 dom 准备好之后,
document.getElementById("check_box").value("testJava");
回答by jeff
Try this:
试试这个:
var checkBox = document.getElementsByTagName("input")[0];
checkBox.value = testJava;
Note: this must be done within a window.onload
event or in a script positioned after the checkbox HTML.
注意:这必须在window.onload
事件中或在复选框 HTML 之后定位的脚本中完成。