Toggle visibility of html using javascript checkbox event
I've cobbled together these javascript functions to hide the delivery address fields on my shopping cart address form if goods are going to billing address. The functions toggle visibility of html wrapped by ..
function getItem(id) {
var itm = false;
if(document.getElementById)
itm = document.getElementById(id);
else if(document.all)
itm = document.all[id];
else if(document.layers)
itm = document.layers[id];
return itm;
}
function showHideItem(id) {
itm = getItem(id);
if(!itm)
return false;
if(itm.style.display == 'none')
itm.style.display = '';
else
itm.style.display = 'none';
return false;
}
It works fine if were loading a new address form, the problem I have is if they submit the form with checkbox ticked, and validation fails, the form reloads with the checkbox ticked but unfortunately the fields are visible so now the removing the checkbox hides the fields!!
<tr><td class="white"><strong>Delivery Address</strong></td>
<td>Tick <input Type="checkbox" id="deliver_same" value="yes" onClick="showHideItem('delAddress')" />
If delivery address is billing address</td></tr>
<tbody id="delAddress">
<tr><td>Address line 1</td><td><input class="text" name="saddr1" value="" /></td></tr>
...
<tr><td>Post /Zip Code</td><td><input class="text" name="spostalcode" value="" /></td></tr>
</tbody>
I guess what I need is an onload event which hides the fields if checkbox is ticked when the form loads. Having just written that, I might have a go but not confident. Please, no mention of jquery, its not an option at this point of project.
function checkDeliverSame() {
var deliverSame = getItem('deliver_same');
var deliveryAddress = getItem('delAddress');
if (deliverSame.checked) {
deliveryAddress.style.display = 'none';
} else {
deliveryAddress.style.display = 'block';
}
}
checkDeliverSame(); /* This runs the function on page load */
Put that function, along with your getItem
function, right above the </body>
tag, and call it in the checkbox input onclick. You will also need to change the id#delAddress
element from a tbody
to a div
so that the getItem function will work on it.
Here's a fiddle: http://jsfiddle.net/JuNhN/1/
I modified Josh's function to make it more generic, prefer document.getElementById() too as it fits in better with itm.style.display. I don't entirely trust checkDeliverSame(); going for a direct call in the html shortly after the closing tag.
function checkHiddenRows(id) {
deliverSame = getItem('deliver_same');
itm = document.getElementById(id);
if (deliverSame.checked == true) {
itm.style.display = 'none';
} // else { alert('Checkbox not checked') } // Verify the checkbox state
}
<script>checkHiddenRows('deliveryAddress');</script>
The form is now working as intended.
链接地址: http://www.djcxy.com/p/56056.html上一篇: 类型的HTML无效值