How to appear required in an input without form?

1

I wanted to make a form but not use <form> because I want to send inputs to ajax . The problem is that if you take the form, it will not be required because as you said in W3Schools

  

The required attribute specifies that a input must be   filled before to be submitted

So, what can I do to achieve this? I searched and found this code:

document.getElementById('put_id_here').validity.valid;

But the above code did not work.

    
asked by anonymous 06.10.2017 / 17:33

2 answers

3

You can use the :invalid selector to apply CSS to the unvalidated input. The only drawback is that CSS loads from the very beginning. So you can join a class to join the element when it receives focus for the first time.

var input = document.getElementById('put_id_here');
var button = document.querySelector('button');
var info = document.querySelector('p');

input.addEventListener('focus', function() {
  this.classList.add('validate');
});

button.addEventListener('click', function() {
  if (input.validity.valid) {
    info.textContent = 'Tudo OK!';
  } else {
    info.textContent = 'O input tem de ser preenchido!';
  }
});
.validate:invalid {
  border: 1px solid red;
}
<input type="text" id="put_id_here" required>
<button>Enviar</button>
<p></p>
    
06.10.2017 / 17:57
0

You can put it like this.

<form action="javascript:enviar();"> 
   <input type="text" name="text" required>
</form>

<script>

    function enviar() {
        var text = document.getElementsByName('text')[0].value;
        alert( text );
    }

</script>
    
06.10.2017 / 17:54