Frage

Is there a way to populate a JavaScript array with form fields that have the required attribute?

I tried this bit of code...

var requiredfields = new Array();

function getInputs() {
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
        alert('I am input field ' + i);
        //var required = fields[i].getAttribute('required');
        if (fields[i].getAttribute('required')) {
            fields[i].style.border = '1px solid #ff0000';
            requiredfields.push(fields[i]);
        }
    }
}

Unfortunately, it's not even putting the border or showing the alerts. I'm not really even sure if getElementsByTagName is returning the data, correctly.

It's probable that my code is wack. Hehehe...

War es hilfreich?

Lösung

You can use this script:

http://jsfiddle.net/2u3kZ/

var requiredfields = new Array();

var fields = document.getElementsByTagName('input');
for (var i = 0; i < fields.length; i++) {
    if (fields[i].getAttribute("required") != null) {
        fields[i].style.border = '1px solid #ff0000';
        requiredfields.push(fields[i]);
    }
}

Andere Tipps

In modern browsers you can do this:

var required = document.querySelectorAll('input[required]');

Array.prototype.forEach.call(required, function(element){
  element.style.border = '1px solid #ff0000';
});

Or just use a CSS rule in your stylesheet:

input[required] {
  border: 1px solid #ff0000;
}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top