Decrease the lines of code by maintaining the function of getElementByID?

Asked

Viewed 108 times

2

Is there any way to eliminate these numerous lines of code keeping the same function? (the function would be to Keep the content of textarea hidden until the check-box be selected and keep it only readable) so it would make my code a little smaller and easier to understand as well.

So far I’ve used the element extensively document.getElementById and I was able to understand until in an easy way its functioning.

function consulta1() {
  if (document.getElementById('checkBA').checked) {
    document.getElementById('consT').value = "R$ 75,00";
    document.getElementById('consT').disabled = true;
  } else {
    document.getElementById('consT').value = "";
    document.getElementById("consT").readOnly = true;
    document.getElementById('consT').disabled = false;
  }
}

function consulta2() {
  if (document.getElementById('checkBB').checked) {
    document.getElementById('interT').value = "R$ 510,00";
    document.getElementById('interT').disabled = true;
  } else {
    document.getElementById('interT').value = "";
    document.getElementById("interT").readOnly = true;
    document.getElementById('interT').disabled = false;
  }
}

function consulta3() {
  if (document.getElementById('checkBC').checked) {
    document.getElementById('examT').value = "R$ 150,00";
    document.getElementById('examT').disabled = true;
  } else {
    document.getElementById('examT').value = "";
    document.getElementById("examT").readOnly = true;
    document.getElementById('examT').disabled = false;
  }
}
<form><fieldset><legend><font color="darkblue">Serviços</font></legend><br>
		<table width="80%" border="0" style= "border-color: Gainsboro" cellpadding="10">
				
		<tr>
		<td>
		<input type="checkbox" name="servico1" id="checkBA" onclick='consulta1()'; > 				
		Consulta <td><input type="text"  id="consT"  size="20" maxlength="35"readonly/></td>
		</td>
		</tr>
		<tr>
		<td>
		<input type="checkbox" name="servico2" id="checkBB" onclick='consulta2()'; />
	Internação <td><input type="text" id="interT" size="20" maxlength="35" readonly/></td>
		</td>
		</tr>
		<tr>
		<td>
		<input type="checkbox" name="servico3" id="checkBC" onclick='consulta3()'; />
		Exames Laboratoriais <td><input type="text" id="examT" size="20" maxlength="35" readonly /></td>
		</td>
		</tr>			
	</table><br>
 </fieldset> </form>

3 answers

3


You can reduce some things. You can create auxiliary variables so you don’t have to stay the same element multiple times. Can cause what does not vary to be done outside the if. Actually one of the values is already a boolean, so you can use the condition as its value. There remaining only 1 variable to decide what to do just use the conditional operator in place of the if.

You can reduce the number of lines, but the code as a whole will get bigger.

function consulta1() {
  var elemento = document.getElementById('consT');
  var checado = document.getElementById('checkBA').checked;
  elemento.value = checado ? "R$ 75,00" : "";
  elemento.readOnly = true;
  elemento.disabled = checado;
}

function consulta2() {
  var elemento = document.getElementById('interT');
  var checado = document.getElementById('checkBB').checked;
  elemento.value = checado ? "R$ 510,00" : "";
  elemento.readOnly = true;
  elemento.disabled = checado;
}

function consulta3() {
  var elemento = document.getElementById('examT');
  var checado = document.getElementById('checkBC').checked;
  elemento.value = checado ? "R$ 150,00" : "";
  elemento.readOnly = true;
  elemento.disabled = checado;
}
<form><fieldset><legend><font color="darkblue">Serviços</font></legend><br>
        <table width="80%" border="0" style= "border-color: Gainsboro" cellpadding="10">
                
        <tr>
        <td>
        <input type="checkbox" name="servico1" id="checkBA" onclick='consulta1()'; >                
        Consulta <td><input type="text"  id="consT"  size="20" maxlength="35"readonly/></td>
        </td>
        </tr>
        <tr>
        <td>
        <input type="checkbox" name="servico2" id="checkBB" onclick='consulta2()'; />
    Internação <td><input type="text" id="interT" size="20" maxlength="35" readonly/></td>
        </td>
        </tr>
        <tr>
        <td>
        <input type="checkbox" name="servico3" id="checkBC" onclick='consulta3()'; />
        Exames Laboratoriais <td><input type="text" id="examT" size="20" maxlength="35" readonly /></td>
        </td>
        </tr>           
    </table><br>
 </fieldset> </form>

I put in the Github for future reference.

  • I think it would be better to use Let to create variables, or if constants use const'.

  • @Ronaldoperes limits where it can run.

2

One of the ways to reduce a lot is to store the elements brought by getElementById variables outside the functions and only use them within the functions. This can also make your code more efficient as you are not constantly browsing html to get the same elements. You may not be able to do this if html is dynamically updated.

The logic you’re applying to each check in it’s the same changing just the <input> and the value, which allows you to generalize the code if you receive the 3 changing elements.

Example:

function consulta(checkId, inputId, valor) {
  const input = document.getElementById(inputId);

  if (document.getElementById(checkId).checked) {
    input.value = valor;
    input.disabled = true;
  } else {
    input.value = "";
    input.readOnly = true;
    input.disabled = false;
  }
}
<form>
  <fieldset>
    <legend>
      <font color="darkblue">Serviços</font>
    </legend><br>
    <table width="80%" border="0" style="border-color: Gainsboro" cellpadding="10">
      <tr>
        <td>
          <input type="checkbox" name="servico1" id="checkBA" onclick='consulta("checkBA","consT","R$ 75,00")' ;> Consulta
          <td><input type="text" id="consT" size="20" maxlength="35" readonly/></td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="servico2" id="checkBB" onclick='consulta("checkBB","interT","R$ 510,00")' ; /> Internação
          <td><input type="text" id="interT" size="20" maxlength="35" readonly/></td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="servico3" id="checkBC" onclick='consulta("checkBC","examT","R$ 150,00")' ; /> Exames Laboratoriais
          <td><input type="text" id="examT" size="20" maxlength="35" readonly /></td>
      </tr>
    </table><br>
  </fieldset>
</form>

I had to change the onclick of cadca element to send to the function the 3 parameters:

onclick='consulta("checkBA","consT","R$ 75,00")'

Who are the ones who change for each option.

You can simplify even more by swapping the first parameter for this in the onclick of html:

onclick='consulta(this,"consT","R$ 75,00")'

That makes it already receive the element in the function, not being necessary to do the document.getElementById:

function consulta(check, inputId, valor) {
  const input = document.getElementById(inputId);

  if (check.checked) { //check já é o elemento e não precisa de getElementById
    input.value = valor;
    input.disabled = true;
  } else {
    input.value = "";
    input.readOnly = true;
    input.disabled = false;
  }
}

Using ternary operators and double assignment allows to compress much more:

function consulta(check, inputId, valor) {
  const input = document.getElementById(inputId);
  input.value = check.checked ? valor : "";
  input.readOnly = input.disabled = check.checked;
}
<form>
  <fieldset>
    <legend>
      <font color="darkblue">Serviços</font>
    </legend><br>
    <table width="80%" border="0" style="border-color: Gainsboro" cellpadding="10">
      <tr>
        <td>
          <input type="checkbox" name="servico1" id="checkBA" onclick='consulta(this,"consT","R$ 75,00")' ;> Consulta
          <td><input type="text" id="consT" size="20" maxlength="35" readonly/></td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="servico2" id="checkBB" onclick='consulta(this,"interT","R$ 510,00")' ; /> Internação
          <td><input type="text" id="interT" size="20" maxlength="35" readonly/></td>
      </tr>
      <tr>
        <td>
          <input type="checkbox" name="servico3" id="checkBC" onclick='consulta(this,"examT","R$ 150,00")' ; /> Exames Laboratoriais
          <td><input type="text" id="examT" size="20" maxlength="35" readonly /></td>
      </tr>
    </table><br>
  </fieldset>
</form>

1

Another very short form would be creating an array with [id_do_campo=preço] without having to change anything in the original HTML:

var els = ['consT=75,00','interT=510,00','examT=150,00'];
chks = document.querySelectorAll('input[type=checkbox]');
for(x=0;x<chks.length;x++){
   chks[x].addEventListener('change', function(e){
      var idx = (/.$/).exec(e.target.name);
      elp = els[idx-1].split('=');
      var el = document.getElementById(elp.shift());
      this.checked ?
      (el.value = 'R$ '+elp.pop(), el.disabled = true) :
      (el.value = '', el.readOnly = true, el.disabled = false)
   });
}
<form><fieldset><legend><font color="darkblue">Serviços</font></legend><br>
   <table width="80%" border="0" style= "border-color: Gainsboro" cellpadding="10">
      <tr>
         <td>
            <input type="checkbox" name="servico1" id="checkBA" > 				
            Consulta <td><input type="text"  id="consT"  size="20" maxlength="35" readonly/></td>
         </td>
      </tr>
      <tr>
         <td>
            <input type="checkbox" name="servico2" id="checkBB" />
            Internação <td><input type="text" id="interT" size="20" maxlength="35" readonly/></td>
         </td>
      </tr>
      <tr>
         <td>
            <input type="checkbox" name="servico3" id="checkBC" />
            Exames Laboratoriais <td><input type="text" id="examT" size="20" maxlength="35" readonly /></td>
         </td>
      </tr>			
   </table><br></fieldset>
</form>

Browser other questions tagged

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