0


I'm very new to javascript, and I'm not sure what to do with my script below.

Please see script below which is a resource I found to help me activate input's within iscroll4...

var inputSubmit = document.getElementById('gform_submit_button_1');

inputSubmit.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);



This is great for one input, but I've got an entire form to apply this too. So this is how I wrote it...

var inputSubmit = document.getElementById('gform_submit_button_1'),
    inputName = document.getElementById('input_1_1'),
    inputEmail = document.getElementById('input_1_2'),
    inputPhone = document.getElementById('input_1_3'),
    inputMessage = document.getElementById('input_1_4'),
    inputCaptcha = document.getElementById('input_input_1_5');

inputSubmit.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);

inputName.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);

inputEmail.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);

inputPhone.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);

inputMessage.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);

inputCaptcha.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
}, false);


The variables are probably fine as the are, but is there some way I can have less script and combine the bottom part into one?

If this is how it's got to be then no worries.

Any advice would be really helpful.


Thanks

Joshc
  • 3,825
  • 16
  • 79
  • 121

1 Answers1

0
var formInputs = [
  document.getElementById('gform_submit_button_1'),
  document.getElementById('input_1_1'),
  document.getElementById('input_1_2'),
  document.getElementById('input_1_3'),
  document.getElementById('input_1_4'),
  document.getElementById('input_input_1_5')
];
for(var i = 0; i < formInputs.length; i++) {
  formInputs[i].addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
}

Or you can loop it by

formInputs.forEach(function(el) {
  el.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
});

Or.. (Not recommended because of: Why is using "for...in" with array iteration a bad idea?)

for(var el in formInputs) {
  el.addEventListener('touchstart' /*'mousedown'*/, function(e) {
    e.stopPropagation();
  }, false);
}
Community
  • 1
  • 1
sirhc
  • 6,097
  • 2
  • 26
  • 29
  • Thanks Sirhc! I went with the top one. The second one showed an error 'undefined' type erro is not a function. I could not see any typos it? Weird. Thanks for your help. – Joshc Feb 08 '12 at 22:08