How to link the values of 2 inputs using JavaScript

139 views Asked by At

I have a form with 2 inputs: a select that is rendered from DB, and a input type text. I need to link the value of both inputs using JavaScript in the front end.

This is the code of the front end:

<div class="form-group col-md-1">
        <label for="cc02">Num</label>
        <input type="text" class="form-control" id='cc02' name="tipoDeComprobante">
      </div>
      <div class="form-group col-md-5">
        <label for="cc03">Tipo de comprobante 3 TABLA </label>
        <select class="form-control" id="cc03">
            <% for( let index = 0; index < cccompras.length; index++ ) { %>
                <option id='cccompras<%= cccompras[index].id %>' value= '<%= cccompras[index].codigoFactura %>' ><%= cccompras[index].denominacion %></option> 
            <% } %>
          </select>
      </div>

Tried to do and onChange event on both, but the change on 2, triggers change on 3 which triggers change again on 2.

    let but = document.getElementById('btnsubform')
    let cc02 = document.getElementById('cc02')
    let cc03 = document.getElementById('cc03')

        cc03.addEventListener('change', ()=>{
            cc02.value = cc03.value
    })

    cc02.addEventListener('change', ()=>{
        cc02.value = cc03.value
})
1

There are 1 answers

0
CertainPerformance On

You could only assign a value if it's different from the current value:

const cc02 = document.getElementById('cc02')
const cc03 = document.getElementById('cc03')

cc03.addEventListener('change', () => {
  if (cc02.value !== cc03.value) cc02.value = cc03.value;
})

cc02.addEventListener('change', () => {
  if (cc03.value !== cc02.value) cc03.value = cc02.value;
})
<input id="cc02">
<input id="cc03">