简体   繁体   English

从输入中获取和设置值使用javascript

[英]Getting and setting the value from input use javascript

I have a input from website which defines like this: 我有一个来自网站的输入,定义如下:

<input type="text" name="postdb[title]" size="60" value id="title" class="input_text">

I've tried this: 我已经试过了:

document.getElementsByName('postdb[title]')[0].value='test'

and this: 和这个:

document.getElementById('title').value='test'

but it doesn't work,how to set the value of this input use javascript? 但它不起作用,如何使用javascript设置此输入的值?

edit: 编辑:

I found that this input is insideof <form name="FORM.. ,so how to find it in that form use javascript? 我发现此输入在<form name="FORM.. ,那么如何使用javascript在该表单中找到它?

edit:solved; 编辑:解决; its actually inside of FORM from iframe,so I just use this: 它实际上位于iframe的FORM内部,因此我只使用了以下代码:

var vform =document.frames['main'].document.forms['FORM'];
vform.elements['title'].value='test'; thanks for help,

use this 用这个

<input type="text" name="postdb[title]" size="60" value="" id="title" class="input_text">

document.getElementById('title').value='test';

Your DOM was probably not loaded yet. 您的DOM可能尚未加载。

<!-- this will fail -->
<script type="text/javascript">var el = document.getElementById('element');</script>
<div id="element"></div>

The above example will fail because we are trying to search an element that has not yet loaded. 上面的示例将失败,因为我们正在尝试搜索尚未加载的元素。 A mistake easily made! 容易犯错误!

<!-- this will not -->
<div id="element"></div>
<script type="text/javascript">var el = document.getElementById('element');</script>

By running the javascript after the required DOM has loaded, we are able to find it. 通过在加载所需的DOM后运行javascript,我们可以找到它。

Try with this: 试试这个:

$(document).ready(function() {
    document.getElementById('title').value = 'test';
});

Demo Here: JS Fiddle 此处演示: JS小提琴

Both should work for you but,make sure when you are calling document.getElementById(); 两者都应该为您工作,但请确保何时调用document.getElementById(); or document.getElementsByName(); document.getElementsByName(); does the <input> element exist in your page? 页面中是否存在<input>元素?

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

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