I have the following form (below) which has a hidden input tag. On form submission and response back I want to change the name of that hidden inputs name to have a value of “__REMOVE__”. Then on submission of the response of the form again I want it to go back to “__ADD__”, and so on. The code however is not working for me, the name=”__ADD__” never changes on the form. I’m very new to jQuery so please excuse my ignorance. Note, the value of __BRONZE__ should never change – it is a requirement of the backend PHP that the name changes.
Form:
<form action="cart.php" method="post" class="cart-ajax">
<input type="hidden" name="__ADD__" value="__BRONZE__" />
<br><button type="submit" class="add-more-top dark cart-button-eight">Add to Cart</button>
<div class="cart-ajax-response"></div>
</form>
jQuery:
$(document).ready(function() {
// code here snipped out to keep this question short
// Shopping Cart Form
$("form.cart-ajax").submit(function(e) {
e.preventDefault();
var form = $(this);
// update the submit buttons text on form submission
if(form.find('input:hidden').attr('name', '__ADD__'))
{
form.find('button:submit').html('Adding...');
}
else if(form.find('input:hidden').attr('name', '__REMOVE__'))
{
form.find('button:submit').html('Removing...');
}
$.post(form.attr('action'), form.serialize(),
function(data) {
// update the submit buttons text after successful response
// update the hidden form field with the opposite of the current value
if(form.find('input:hidden').attr('name') == '__ADD__')
{
form.find('button:submit').html('Remove');
form.find('input:hidden').attr('name', '__REMOVE__');
}
else if(form.find('input:hidden').attr('name') == '__REMOVE__')
{
form.find('button:submit').html('Add');
form.find('input:hidden').attr('name', '__ADD__');
}
// do something with the returned data - used in cart-ajax-response div
form.find('.cart-ajax-response').empty().html(data.aResults[0]);
}, 'json');
});
}); // <-- document ready
isn’t doing what you think. You’re actually setting that field’s name not asking if it exists.
Use
and note
.lengthgets you an integer. Without it you’ll be returned an object, which is true even if its length is 0.However, take a look at this http://jsfiddle.net/3xTfX/2/ – same thing, less code