views:

123

answers:

3

Hi, I've been trying for a couple hours now to figure out why JavaScript wouldn't work. The code works, but here it is anyway.

<script type="text/javascript">
function change(text)
{
document.f1.ta.value="Hi!";
}
</script>
<form name="f1">
<input type="textarea" id="ta"/>
<input type="button" action='change("Hi!")'/>
</form>

When I click the button, it does nothing. When I write "document.f1.ta.value="Hi!";" in the Chrome's inspector console, it works. I am using XAMPP (for Windows) 1.7.3 Windows 7 Ultimate.

+1  A: 

Your button is using "action" - that should be "onclick" for an element itself..

and/or

document.f1.ta.value="Hi!"; is failing... try

function test() {
   alert('test');
}

and add

<button onclick="test();">Test</button>

to your body

Dan Heberden
Oh, it was you, not CMS. Thanks, though! :D
Anonymous the Great
A: 

That is not a standard way of accessing elements. Use document.getElementsByName or document.getElementById.

document.getElementById("ta").value="Hi!";

As noted by CMS, you also want onclick for the button.

Matthew Flaschen
I tried that way, but it did not work. It does now though, thanks to CMS. (:
Anonymous the Great
@Anon, `getElementById` should work. Did you also correct the `onclick`?
Matthew Flaschen
Yes, that is what I said. It worked after I did the onclick that CMS suggested. :P
Anonymous the Great
+1  A: 

Two things:

You have specified an action attribute on the button, I think you are looking for the onclick intrinsic event:

<input type="button" onclick='change("Hi!")'/>

The standard way (DOM0) to access forms and form elements would be:

function change(text) {
  document.forms[0].elements.ta.value = text;
}

Check an example here.

CMS
Thank you very much! The onclick worked. I did not need to do "forms["*"]" and elements. Thanks a lot, though!
Anonymous the Great