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;
>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.