
Originally Posted by
Symptom7
<input type=button name="thebutton" [...] onclick="youchangethecolor(form.thecolor.value)">
You're rather fortunate that the emphasised part above works. The code currently relies on undefined behaviour that has added the form object to a custom scope chain (used to look up identifiers). In fact, the form object is a property of the input element, to the correct way to access it is:
Code:
<input ... onclick="youchangethecolor(this.form.thecolor.value);">
A small adjustment, but a potentially important one.
Now, as for your question, here's one possible solution:
Code:
function setColour(colour) {var b, s;
if((b = document.body) && (s = b.style)) {s.backgroundColor = colour;}
}
HTML Code:
<form onsubmit="setColour(this.elements.colour.value); return false;">
<input type="text" name="colour">
<input type="submit" value="Set colour">
</form>
If either Enter is pressed within the text box, or the button is activated, the form is submitted. That event is then captured and cancelled, changing the colour in the process.
You should be aware that whilst this will work, it suffers from the fact that users without client-side scripting support will actually end up submitting a form because the submit event won't be cancelled. So, an alternative could be:
HTML Code:
<script type="text/javascript">
function setColour() {
var e = document.getElementById('colour');
if(e) {document.body.style.backgroundColor = e.value;}
}
if(document.body && document.body.style
&& document.getElementById && document.write)
{
document.write([
'<input id="colour" type="text" value=""',
' onkeydown="if((13 == event.keyCode) || (13 == event.which)) {setColour();}">',
'<input type="button" value="Set colour" onclick="setColour();">'
].join('\n'));
if(document.close) {document.close();}
}
</script>
When included within your markup (at the location where the elements should appear), the code first examines the environment to ensure that what it needs is supported. It then writes the two input elements into the document stream.
The code now uses a combination of a click and keydown event listener to catch activation of the button, and an Enter keystroke, respectively, to change the colour.
Hope that helps,
Mike
Bookmarks