08 Oct, 2004
Copy values from one field to another with javascript
Posted by: Jennifer In: Bookmarks|Script snippet
Needed to write a javascript that would take the values of one select box – and copy it to all the other select boxes on the same page. I found this script which will take all the values from one set of fields – and copy it to another set of fields (kind of like those billing / shipping forms, where if your billing and shipping address is the same, you just check a box – and it prefills the other set of fields for you with the same info from above). And while it "inspired me" – it wasn't exactly what I was looking for. In my case – I didn't know the exact names of all the other fields, and I didn't even know how many of them there would be – they are generated dynamically. It's a pretty simple script, but here it is anyway:
<script type="text/javascript">
function applyToAll()
{
for (var i=0; i< document.YOURFORMNAME.length; i++) {
document.YOURFORMNAME[i].selectedIndex = document.YOURFORMNAME.NAMEOFMAINSELECT.selectedIndex;
}
}
</script>
So your select box probably looks like this:
<select name="NAMEOFMAINSELECT">
<option value="1">1</option>
<option value="2">2</option>
… etc. …
</select>
and then, next to the select box (which will be the one all the others are based on) put a link like this: