How to know that a particular input type is present or not in a div?
If I use
$("#inputId").val()
And there is no element present on this, then js gives an error.
So how could I know that the input element named inputId is present or not?
Reply me ASAP
You could check if
i.e. if the current selector matched any elements.
But if
$('#inputId').length == 0then$('#inputId').val()will beundefined. This is different from the scenario where the input exists, becauseval()would always yield a string, that is or isn’t null.Now, you would produce an error only if you’re trying to do stuff with the value, that may or may not be
undefined. For instance, the following would not work if#inputIddoes not exist in the DOM:… since you’d be trying to access
undefined.length. However, you could still doIf you’re writing form validation, it might be more useful to do
The former condition checks that the result of
.val()resolves to true, which is not the case for an empty string or for undefined. (It is also not the case fornull,NaN,falseor0, but.val()will never yield any of those results)The latter checks that the result of
.val()is not exactly an empty string, which is true for an actual value, as well as forundefined.