Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

the value is undefined and applying a check in the javascript

the issue i am having is the slice is undefined – Cannot read properties of undefined (reading ‘slice’)
how can i write a code to use if the value is not defined or error, just use $("#x").val().slice(3,5)

tried like this but seems not working

w = (typeof x.val() !== 'undefined') ? $("#x").val().slice(3,5)  : 0;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

x.val() and $("#x").val() are very different things, unless it just happens that x is the result of a previous call to $("#x").

The only time jQuery’s val returns undefined is if you call it on an empty set (which would mean there is no element with id="x" in the DOM when you do $("#x")). The simple way to do this is to grab the value, then do the check:

const val = x.val(); // Or `= $("#x").val()`, whatever is the one you actually want
w = typeof val !== "undefined" ? val.slice(3,5) : 0;

Beware, though, that you’re assigning a string to w in one case but a number in the other. Typically you’re best off being consistent, either always use a string, or always use a number.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading