Attribute set to false comes out as true

2

I'm trying to create a function in Javascript with which to check the inputs with the required attribute in true.

The problem is that although this is specified as false, the result it gives is true.

Sample code:

var serial_no = document.getElementsByName('serial_no')[0];
console.log(serial_no);
console.log(serial_no.required);
<form>
	<input type="text" name="serial_no" placeholder="serial_no" value="" required="false">
</form>

Is there a solution?

    
asked by Yonkykong 09.08.2018 в 09:01
source

1 answer

1

The required attribute works in the present or absent boolean way. This means that if it exists, it is true, if it does not exist, it is false .

So to put required="false" you are not saying that it is not required, you are saying that if the attribute exists.

So that it is not simply required, do not put it.

var serial_no = document.getElementsByName('serial_no')[0];
console.log(serial_no.required); //true

serial_no = document.getElementsByName('serial_no')[1];
console.log(serial_no.required);// false

serial_no = document.getElementsByName('serial_no')[2];
console.log(serial_no.required);//  true

serial_no = document.getElementsByName('serial_no')[3];
console.log(serial_no.required);//  true
<form>
	<input type="text" name="serial_no" placeholder="serial_no" value="" required>
  <input type="text" name="serial_no" placeholder="serial_no" value="" >
  <input type="text" name="serial_no" placeholder="serial_no" value="" required="loquesea">
  <input type="text" name="serial_no" placeholder="serial_no" value="" required="">
</form>

This type of attribute is a Boolean attribute , such as checked , disabled , ... here the source

    
answered by 09.08.2018 в 09:59