I'm taking a shot in the dark here, it seems like you want to prevent these elements from submitting to the server, if that's the case instead of trying to change the name
attribute, you can set the disabled
attribute, like this:
$('#country').change(function() {
var $country = $(this), $state = $('#state'), $county = $("#county");
if($country.val() != 226) {
$state.attr('disabled', true).closest('p').hide();
$county.attr('disabled', false).closest('p').show();
} else {
$state.attr('disabled', false).closest('p').show();
$county.attr('disabled', true).closest('p').hide();
}
});
When a form element has the disabled
attribute, it can't be successful, which means it won't be included when you submit it to the server. So in the above example just give both inputs name="user[state]"
from the start, and this will exclude the one you don't want from the POST (or GET) that your <form>
does.
It doesn't answer the question directly, I realize this, but it's another (I think) simpler way to avoid the problem :) You can shorten this down further by using .toggle(bool)
but I think it destroys the example, so I left it uncompressed above, the short version would look like this:
$('#country').change(function() {
var is226 = $(this).val() == 226;
$('#state').attr('disabled', !is226).closest('p').toggle(is226);
$("#county").attr('disabled', is226).closest('p').toggle(!is226);
});