Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

185
Visualizações
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;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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').

about 4 years ago · Juan Pablo Isaza Relatório

0

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>

This checks is x is undefined or if the length of the String is long enough be sliced.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda