Is it possible to change the name value of an input element?
Here is my code but i can set anything but the name.
$('#country').change(function(){
var $country = $(this);
var $state = $('#state');
var $county = $("#county");
if($country.val() != 226){
$state.attr('name', '');
$state.closest('p').hide();
$county.attr('name', 'user[state]');
$county.closest('p').show();
}else{
$state.attr('name', 'user[state]');
$state.closest('p').show();
$county.attr('name', '');
$county.closest('p').hide();
}
});
Any ideas why setting a name attr does not work ?
Hope you can advise
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
nameattribute, you can set thedisabledattribute, like this:When a form element has the
disabledattribute, 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 inputsname="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: