ch**************@ntlworld.com wrote:
I'm trying to write a simple JavaScript function which will use a
button to copy table cell data into a form input text box as the
"value" attribute.
The following is intended to test the function, but doesn't work. I'm
new to this - previous JavaScript experience mostly copy & paste -
could somebody please point to where I'm going wrong.
~~~~~~~~~~~~~~~~~~~~~~~~~
<head>
<title>Testing JavaScript</title>
<script language="JavaScript">
The language attribute is deprecated, type is required:
<script type="text/javascript">
function copytext(source_id, dest_id)
{
var s = getElementById(source_id);
Please don't indent using tabs when posting, use 2 (preferred) or 4 spaces.
getElementById is a method of the DOM 2 Core document interface:
var s = document.getElementById(source_id);
It is also best to test features that may not be supported by some browsers:
if (document.getElementById){
var s = document.getElementById(source_id);
...
var d = getElementById(dest_id);
var d = document.getElementById(dest_id);
var text = s.innerText;
The innerText property is IE proprietary and not widely implemented.
The W3C equivalent is textContent, which naturally isn't implemented by
IE. Alternative utilities have been posted here, search the archives
for 'innerText textContent'.
d.setAttribute("value", text);
setAttribute is known to be a bit buggy on some browsers - though I
don't think there should be a problem here. Anyhow, it's much simpler
to write:
d.value = text;
}
</script>
</head>
<body>
<h1>Testing JavaScript</h1>
<form>
The action attribute is required for HTML forms, even if it has no value:
<form action="">
[...] <button onclick="copytext('cell1', 'input1')">>></button>
Inside a form, a button element is by default a submit button. So even
if the value is copied to the input, the form is posted to the current
page, causing it to re-load and clear the value.
<URL:http://www.w3.org/TR/html4/interact/forms.html#edef-BUTTON>
If you don't want it to be a submit button, give it a type attribute
value of 'button'. Anyhow, it seems better to use an input with
type="button" and avoid the issue:
<input type="button" value=">>"
onclick="copytext('cell1', 'input1')">
[...]
--
Rob