Change 'id' from Form element javascript or jquery

2

I need to change the id of a form in HTML with javascript at runtime.

I'm trying with JQuery and Javascript, but it's not working.

jQuery(this).prev("form").attr("form", "form_modulo");

or

document.getElementById('form').id = 'form_form_modulo';

Neither works, when I go to see the page code is still the old value

    
asked by anonymous 10.07.2017 / 03:12

3 answers

2

To change the ID you can change the property of the DOM object or the attribute of the HTML element. It's different things, I explained more about this here in this other answer .

Change ownership:
(You mentioned this way in the answer, and it's correct.)

// JavaScript nativo
document.getElementById('form').id = 'form_form_modulo';
// jQuery:
$('#form').prop('id', 'form_form_modulo');

Change attribute:

// JavaScript nativo
document.getElementById('form').setAttribute('id', 'form_form_modulo');
// jQuery:
$('#form').attr('id', 'form_form_modulo'):

Both do what you want, but changing the property only will not be visible in HTML when you inspect with the dev tools.

I read in the comments that you tried

function SalvarBotoes() {
  alert($('#form').attr('id'));
  $('#form').attr('id', 'form_modulo');
  alert($('#form').attr('id'));
  form.submit();
}

The reason this gives undefined is because the last call to $('#form') will not give anything exactly because you changed the ID and this selector no longer finds any element with that ID. You would have:

function SalvarBotoes() {
  var $form = $('#form');
  alert($form.attr('id'));
  $form.attr('id', 'form_modulo');
  alert($form.attr('id'));
  $form[0].submit();
}
    
10.07.2017 / 10:05
3

You can try something like:

$('#meu_form').attr('id','novo_id');
    
10.07.2017 / 03:14
1

$(document).on('click', '#texto', function(){
  alert($(this).attr('id'));
  $(this).attr('id', 'NewID');
  alert($(this).attr('id'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="texto">TEXTO</button>

Follow the example

    
10.07.2017 / 03:31