Skip to content Skip to sidebar Skip to footer

Add/remove Required Attribute Dynamically

I want to add/remove the required attribute of an input element. But somehow it doesn't work. If offender Plate# text field is empty, Describe vehicle text field should be required

Solution 1:

works when you sort the html out and remove space after brackets, edited again to remove after details if corrected

functioncheckForRequired() {

    var plateLength = document.getElementById("plate_num_id").value.length;
var vehicle = document.getElementById("vehicle")
    if (plateLength < 1) {

        vehicle.setAttribute('required','required');
    } else {
 
      vehicle.removeAttribute('required');
    }
}
input:required{border:1px solid red;}
<inputtype="text"id="plate_num_id"name="plate_num"onblur/onfocusout="checkForRequired()"><br/><br><inputtype="text"id="vehicle" />

Post a Comment for "Add/remove Required Attribute Dynamically"