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;
CodePudding user response:
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.
CodePudding user response:
In JavaScript both the value undefined
and empty strings are considered falsy and will evaluate as false if used as boolean arguments.
You can use this behaviour to create very simple null checks with some parentheses.
w = ($('#x').val() || '').slice(3,5) || 0;
This code will first add an undefined/null safe check to your $(...).val()
operation using a logical or operation ( ||
). So if there is no value to be found, then an empty string will be returned instead.
Once this has been done the slice will be applied to either the value or an empty string. If the result from the slice is an empty string then a 0
is returned instead.
Please be advised that in your initial example you are also attempting to address the variable x
instead of using $('#x')
. These are not interchangeable unless you first assign var x = $('#x')
.
CodePudding user response:
Consider the following.
$(function() {
var w;
$("#btn").click(function() {
var x = $("#x").val();
w = (x !== undefined || x.length >= 4 ? x.slice(3, 5) : "0");
console.log(w);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" id="x"> <button id="btn">Go</buton>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
This checks is x
is undefined
or if the length of the String is long enough be sliced.