I want to write hidden inputs to the form based on which checkboxes are selected. In my example im not getting errors but it still wont pass the hidden fields-(edited)
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<div id="test"></div>
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="youremail@mail.com">
<input type="hidden" name="currency_code" value="US">
<input type="checkbox" id="chkbox1" name="camp1" value="a">
<input type="checkbox" id="chkbox2" name="camp2" value="b">
<input type="submit" value="PayPal">
</form>
<script type="text/javascript">
var element = document.getElementById('test');
if(element != null && element.checked) {
var newElement = document.createElement('input');
newElement.type = "hidden";
newElement.name = "item_name_1";
newElement.value = "MyItem #1";
document.getElementById('chkbox1').appendChild(newElement);
var newElement2 = document.createElement('input');
newElement2.type = "hidden";
newElement2.name = "amount_1";
newElement2.value = "7.00";
document.getElementById('test').appendChild(newElement2);
}
Theoretically this should work, but it’s got me stumped. If anyone can offer some advice it would be much appreciated.
First, never use
document.writewhile in the context of a webpage. That’s bad practice. If you want to dynamically add an element with pure javascript, you would simply create a new element:Secondly, the error means that the
document.getElementByIdcall for one of your statements did not find the specified element. You need to be null checking the results:Now, without knowing the placement of where your script is, and where this form is in your page, you could suffering from the loading placement. If your script runs before the HTML is loaded, you wont find the elements.