Lee
Lee

Reputation: 20934

Changing input name value

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

Upvotes: 2

Views: 644

Answers (2)

Nick Craver
Nick Craver

Reputation: 630389

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);
});

Upvotes: 2

Jonathan S.
Jonathan S.

Reputation: 541

If I remember correctly, this is an IE bug. I had to convert the JQuery obj to a string, do the name changing as a string and then create a new jquery object around the html string.

so

var form = $('#myForm').html();
form.replace('name', 'newName');
$('#myFormWrapper').html(form);

Apparently changing the name attribute is more difficult than it should be :/

Upvotes: -1

Related Questions