clear input with javascript onchange event

4

I have 2 input:

<input name='nome1'>
<input name='nome2'>

I need to create a javascript that clears the name2 when the value of the name1 is modified.

Can anyone help me do this quite simply?

    
asked by anonymous 20.04.2016 / 22:07

2 answers

5

This is simple:

var nome1 = document.querySelector('[name="nome1"]');
var nome2 = document.querySelector('[name="nome2"]');
nome1.addEventListener('change', function() {
    nome2.value = '';
});

jsFiddle: link

In this way, when the input changes, nome2 is erased. If you want you can also do in keyup or another event depending on the functionality you want to implement.

    
20.04.2016 / 22:09
2

See the example using jQuery. I used keyup in the event, that is, the function will be invoked each time I type something in the input.

  

One tip, prefer to use id for inputs instead of name ,   because id should always be unique, since name does not, and it gets easier   of manipulating using jQuery as well.

var $nome1 = $('input[name=nome1]');
var $nome2 = $('input[name=nome2]');
$nome1.on('keyup', function() {
  $nome2.val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name='nome1'>
<input name='nome2'>
    
20.04.2016 / 22:26