Digital Puer wrote:
I have the following HTML form:
- radio button A (default selected)
- radio button B
- input field, of type "file" with "Choose" button
- submit button
I would like to have it so that if the user clicks on the
"Choose" button of the input field (to select a file on
the local disk), then radio button B is automatically
selected. Can someone tell me how to do that? I'm a
complete Javascript newbie. Thanks.
Neither of the above suggestions will provide a button that reflects the
state of the file input. Below is a suggested strategy:
If JavaScript is disabled, you can't reliably say whether a file has
been selected or not, so don't show the radio buttons.
Change the selected radio button based on the actual state of the file
select. Check the status whenever some action happens on any of the 3
form controls involved and set the appropriate button to checked.
The following script runs whenever the radio buttons are checked or the
value of the file input is changed. The checkboxes also reflect the
value of the input if the user manually clears the input, the page is
re-loaded or the reset button clicked. The radio buttons are only shown
if JavaScript is available and appropriate features supported courtesy
of an onload function.
It still has a problem that the user may want to change the value of the
radio button (but they can't). And if the user changes the availability
of JavaScript after loading the page, all bets are off!
It is just a demo to show the lengths you must go to to support
something which seems quite simple but requires significant effort to
make worthwhile. Note also that browser behaviour differs on page
re-load - some will clear the file input, others won't, so the onload
must check the status of the file input (or just reset the form).
In the head:
<style type="text/css">
..Vis {display: inline;}
..NVis {display: none;}
</style>
<script type="text/javascript">
function checkMe( el ){
var f = el.form;
if ( '' != f.fileSelect.value ) {
f.rBut[1].checked = true;
} else {
f.rBut[0].checked = true;
}
}
window.onload = function() {
if ( !document.getElementById && !document.body.style ){
return;
}
document.getElementById('fileAdviceJS').className = 'Vis';
document.getElementById('fileAdvice').className = 'NVis';
checkMe( document.forms['fileForm'].elements['fileSelect'] );
}
</script>
In the body:
<form name="fileForm" action="">
<span id="fileAdviceJS" class="NVis">File selected?
<input type="radio" value="n" name="rBut" checked
onchange=" checkMe(this);">No <input
type="radio" value="y" name="rBut"
onchange="checkMe(this);">Yes</span>
<span id="fileAdvice" class="Vis">Select a file</span><br>
<input id="fileSelect" name="fileSelect" type="file"
onchange="checkMe(this);">
<br>
<input type="reset">
</form>
--
Rob