Decrement the lines of the code while maintaining the function of getElementByID?

2

Is there any way to eliminate these many lines of code while maintaining the same function? (The function would be to keep hidden textarea content until check-box is selected and keep it just readable) so that would make my code a little smaller and easier to understand as well.

So far, I've used the document.getElementById element quite a bit and I've been able to understand it in an easy way.

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>
    
asked by anonymous 26.11.2017 / 23:30

3 answers

3

You can reduce some things. You can create auxiliary variables so that you do not have to stick to the same element multiple times. You can make what does not vary outside of if . Actually one of the values is already a boolean, so you can use the condition as its value. There is only one variable left to decide what to do, just use the conditional operator instead of if .

You can reduce the number of lines, but the code as a whole will be larger.

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>
    
26.11.2017 / 23:42
2

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

The logic you are applying to each check is equal changing only the <input> and value, which allows you to generalize the code if you receive the 3 elements that change.

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")'

Which are the ones that change for each option.

You can simplify further by changing the first parameter by this in onclick of html:

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

That causes you to already receive the element in the function, not having to do 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 and dual-assignment operators can pack a lot 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>
    
27.11.2017 / 00:27
1

Another very short way would be to create an array with [id_do_campo=preço] without needing 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>
    
27.11.2017 / 03:47