简体   繁体   中英

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?

edit:

I found that this input is insideof <form name="FORM.. ,so how to find it in that form use javascript?

edit:solved; its actually inside of FORM from iframe,so I just use this:

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.

<!-- 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.

Try with this:

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

Demo Here: JS Fiddle

Both should work for you but,make sure when you are calling document.getElementById(); or document.getElementsByName(); does the <input> element exist in your page?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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