PHP and Javascript - Disable a submit button if textarea is empty

2

In the form of my site, I have a textarea field and a submit button. Here is the code for both:

<textarea name='texto1' id="txtBriefing" rows="5" style="font-family: Trebuchet MS; font-size: 16px; width: 394px; height: 100px" onkeyup="doSomething(this.value)" ></textarea>
<input name="btnEnvia" type="submit" value="Enviar" style="font-family: Trebuchet MS; font-size: 20px" />

However, I would like this button to only be enabled if textarea txtBriefing is not empty. I have tried some javascript codes with the onkeyup and onchange functions searching the internet, but none worked so far.

What can be done for this case?

    
asked by anonymous 29.10.2015 / 13:12

2 answers

1

I believe that the oninput event is ideal for this type of situation, I say this because it fires only when the input value changes.

In any case, I advise you to avoid setting JS events and styles in the HTML file.

var txtBriefing = document.getElementById("txtBriefing");
var btnEnvia = document.getElementById("btnEnvia");

var onBriefingInput = function (event) {
  btnEnvia.disabled = !event.target.value;
}

txtBriefing.addEventListener("input", onBriefingInput);
txtBriefing.dispatchEvent(new Event('input'));
#txtBriefing {
  font-family: Trebuchet MS; 
  font-size: 16px; 
  width: 394px; 
  height: 100px
}

#btnEnvia {
  font-family: Trebuchet MS; 
  font-size: 20px
}
<textarea id="txtBriefing" name="texto1" rows="5"  ></textarea>
<input id="btnEnvia" name="btnEnvia" type="submit" value="Enviar" />

Another option is to use an HTML5% validation with%, so the form will not be sent if the textarea is empty.

#txtBriefing {
  font-family: Trebuchet MS; 
  font-size: 16px; 
  width: 394px; 
  height: 100px
}

#btnEnvia {
  font-family: Trebuchet MS; 
  font-size: 20px
}

/* O Estilo abaixo é valido apenas no FireFox. */
#form1:invalid #btnEnvia {
  color: grey;
}
<form id="form1">
  <textarea id="txtBriefing" name="texto1" rows="5" required ></textarea>
  <input id="btnEnvia" name="btnEnvia" type="submit" value="Enviar" />
</form>
    
29.10.2015 / 14:08
4

With JavaScript

Just add the ID on your button, and change your onkeyup from textarea to onkeyup="javascript: doSomething(this)"

function doSomething(input) {
    document.getElementById('btnEnvia').disabled = (input.value.length == 0);
}

Example: link

With jQuery

$(function(){
   $('#txtBriefing').on('keyup', function(){
      $('#btnEnvia').prop('disabled', ($(this).val().length == 0)); 
   });
});

Example: link

    
29.10.2015 / 13:25