Reputation: 3648
I have a form that allows the user to pay via credit card or paypal using radio buttons and when they click on each one respectively - the correct form loads via ajax.
My problem is: after the new form is loaded (via .html()
) all my jquery doesn't work. For example the price of a donation is a radio field and on change it populates a span in order review. After the form loads all this doesn't work.
I'm also using floatlabel.js which doesn't work on the loaded form either.
HTML - Donation Amount
<input type="radio" name="amounts" value="3000"><span class="radio-span">$3000</span>
<input type="radio" name="amounts" value="1800"><span class="radio-span">$1800</span>
<input type="radio" name="amounts" value="500"><span class="radio-span">$500</span>
<input type="radio" name="amounts" value="360"><span class="radio-span">$360</span>
<input type="radio" name="amounts" value="180"><span class="radio-span">$180</span>
<input type="radio" name="amounts" value="other" id="other"><span class="radio-span radio-span-other">Other</span> <input type="text" name="other_amt" class="other-amt"/>
HTML Payment Method
<input type="radio" class="radio-cc" name="method" value="creditcard"><span class="radio-span">Credit Card</span>
<input type="radio" class="radio-paypal" name="method" value="paypal"><span class="radio-span">Paypal</span>
HTML - Order Review (this is in the ajax loaded form)
<div class="order-review">
<span class="amount"></span>
</div>
jQuery - Populating span in order review
$("input[name=amounts]").change(function (e) {
if ($(this).val() == 'other') {
$("input[name=other_amt]").bind("change paste keyup", function() {
$("input.hidn-amt").val( '$'+$(this).val());
$("span.amount").val( '$'+$(this).val());
});
}else{
var selected = $("input[name=amounts]:checked");
$("input.hidn-amt").val( '$'+selected.val());
$("span.amount").val( '$'+$(this).val());
}
});
Upvotes: 0
Views: 227
Reputation: 123
Your jQuery runs before the AJAX request completes, so it does not apply to the new elements which are fetched later.
You can wrap your entire bindings in a function wrapper, maybe call it initForms()
, and call that function after the .html()
code.
There are more ways to bind elements automatically using the $("body").on
syntax of jQuery if you want to have a look at.
Upvotes: 0
Reputation: 5672
Since new fields are being loaded in via AJAX, the eventing bindings are being lost. You can use .delegate() to prevent this.
$(document).delegate('input[name="amounts"]', 'change', function (event) {
// code here
})
I believe you can use .on()
as well, in a similar format, provided you use the document as the selector.
Upvotes: 1