0

I have an input-field in my form which sometimes gets displayed and sometimes not. When the input-field doesn´t get displayed and the form is about to get sent the script throws an error:

Cannot read property 'value' of undefined

I tried to catch that with this code:

if (typeof document.forms["add-new-job"].addjob_companyselect.value !== 'undefined') {
        // do something
}

But the same error comes again on this line. How can I skip an undefined field?

BenMorel
  • 34,448
  • 50
  • 182
  • 322
  • 1
    Maybe just check to see if it's defined first, before trying to extract its `.value`? (though this sounds like a bit of an X/Y problem) – CertainPerformance Feb 19 '19 at 22:41
  • 2
    You'll want to check the `typeof document.forms["add-new-job"].addjob_companyselect`, not its `.value` – Bergi Feb 19 '19 at 22:41
  • Oh, thanks.. I feel stupid now :) – Andreasschnetzer Feb 19 '19 at 22:43
  • 1
    Check out this solution... [https://stackoverflow.com/questions/46700783/any-script-to-ignore-undefined-variable/46700934](https://stackoverflow.com/questions/46700783/any-script-to-ignore-undefined-variable/46700934) – mindmaster Feb 19 '19 at 22:44

1 Answers1

1
var addNewJobElement = document.forms["add-new-job"].addjob_companyselect;
if (addNewJobElement && addNewJobElement.value) {
    // do something
}
Tony Gentilcore
  • 193
  • 1
  • 11