clear input with event onchange javascript

Asked

Viewed 720 times

4

Guys I have 2 input:

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

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

Can someone help me make it very simple?

2 answers

5


That’s simple:

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

jsFiddle: https://jsfiddle.net/tvrgsou2/

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

  • 1

    Very good was just what I needed ;)

2

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

A tip, prefer to use id for the inputs instead of name, for id should always be unique, already the name no, and it gets easier to manipulate 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'>

  • 1

    Very good was just what I needed ;)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.