Ad

Form Validation Project

- 1 answer

I am working on a project for my company and we are not allowed to alter the HTML in any way. There is already a Page set up in the Using html to do Data Validation. There are to separate forms of validation questions on the page and each form contains its own "submit" button. Although both submit buttons have the same "id". is there any way to figure out how isolate each button to apply a different ".onclick" method to them. Thanks in advance.

Ad

Answer

So, this is doable if you go step-by-step (on a side note: a HTML document should NEVER have more than one element sharing the same id tage).

My solution requires that you know exactly how many type="submit" inputs are on the page and in what order, which I assume you do since you say the HTML can't change.

Let's do it:

// 1. Get all the inputs on page
var inputs = document.getElementByTagName('input');

// 2. Let's grab only the submit ones
var submits = [];
for(var i = 0; i < inputs.length; i++) {
  if(inputs[i].getAttribute('type') === 'submit') {
    submits.push(inputs[i]);
  }
}

// 3. Add the correct onclick listeners
submits[0].addEventListener("click", onclick1, false); // Button 1
submits[1].addEventListener("click", onclick2, false); // Button 2

// 4. Define the onclick functions
function onclick1(event) {
  // Do something
}

function onclick2(event) {
  // Do something
}

The above could be expanded to first grab each form and then go through the inputs within that form, but that isn't required if you know exactly the number of forms and type="submit" inputs per form.

Ad
source: stackoverflow.com
Ad