M
M
Maxim K2022-04-12 17:06:31
PHP
Maxim K, 2022-04-12 17:06:31

How can JS check for emptiness or object creation?

Hello. code not working: why???
While the page is loading, text may or may not be added to the "a" variable. This is the variable that needs to be checked. Did it like this:

Всем привет.

Есть код:

Во время  загрузки страницы элемент может быть создан,  а может не  быть. Значение элемента беру через document.queryselector.

  var a = document.querySelector("#******").innerText;
  if(typeof a === "undefined"){
    document.querySelector("#******").value="123";
  }


Tried:

Если вы проверяете пустую строку:

if(myVar === ''){ // do stuff };
Если вы проверяете переменную, которая была объявлена, но не определена:

if(myVar === null){ // do stuff };
Если вы проверяете переменную, которая не может быть определена:

if(myVar === undefined){ // do stuff };
Если вы проверяете оба значения, то есть любая переменная имеет значение null или undefined:

if(myVar == null){ // do stuff };


Those. if there is nothing in the variable, then add the value to the field. What under **** is correctly executed, but the test condition is NOT. ((( I used various options, for some reason it doesn’t work. What am I doing wrong ??? THANKS

Answer the question

In order to leave comments, you need to log in

3 answer(s)
P
Pavel Zayko, 2016-09-16
@popcorn2d

In action.php make a form handler

$name = $_POST['nameplace'];
$mail = new PHPMailer();
$mail->AddAddress('куда слать письмл');
$mail->Subject = $subject;
$mail->SetFrom('от кого письмо');
$mail->MsgHTML(внутреннее содержимое письма);
$mail->CharSet = 'UTF-8';
if ($name != "")
{
    $mail->Send();
}

Roughly speaking like this

S
Sergey Sokolov, 2022-04-12
@sergiks

element can be missing?
Then it will return undefined, and an attempt to get a property from it will throw an error. Take a look at the console. Probably, you need to check two conditions: that the element is found, and that the text in it is not an empty string. Something likedocument.querySelector("#******")innerText

const el = document.querySelector("#******");
if (el) {
  const a = el.innerText;
  if (a.length === 0) {
    el.value = "123"; // а что это за элемент, у которого и innerText и value ?
  }
}

R
Rsa97, 2022-04-12
@Rsa97

If the element is not created, that is, it is not in the DOM, then querySelector will return null and the next call to innerText will generate an error

document.querySelector('#abc').innerText
//  Uncaught TypeError: document.querySelector(...) is null

There are two options.
The first is to check what the querySelector returned and then query the innerText
const el = document.querySelector('#abc');
const text = el === null ? 'default Text' : el.innerText;

The second is to use optional chaining and null coalescing
const text = document.querySelector('#abc')?.innerText ?? 'default Text';

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question