سؤال

I try to post the selected value and check if the variable is empty.

html:

<select id="monitors-old" class="form-control" name="monitors-old">
   <option value="">Auswählen...</option>
   <option value="0" <?php if ($personData["cmo_mon"] == "0"){echo 'selected';}?>>0</option>
   <option value="1" <?php if ($personData["cmo_mon"] == "1"){echo 'selected';}?>>1</option>
   <option value="2" <?php if ($personData["cmo_mon"] == "2"){echo 'selected';}?>>2</option>
   <option value="3" <?php if ($personData["cmo_mon"] == "3"){echo 'selected';}?>>3</option>
   <option value="4" <?php if ($personData["cmo_mon"] == "4"){echo 'selected';}?>>4</option>
</select>

Result html:

<select id="monitors-old" class="form-control" name="monitors-old">
   <option value="">Auswählen...</option>
   <option value="0" selected="">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
   <option value="4">4</option>
</select>

POST Check:

if (empty($_POST["monitors-old"])) {
   $errors[] = "Alt-Monitore is required.";
   die;
} else {
   $monitors_old = validateInput($_POST["monitors-old"]);
}

the value 0 is always empty and the script fired the die, all other values are working. Is the value 0 like ""?

Also tried:

<select id="monitors-old" class="form-control" name="monitors-old">
   <option>Auswählen...</option>
   <option selected="">0</option>
   <option>1</option>
   <option>2</option>
   <option>3</option>
   <option>4</option>
</select>

This is also working, but the same issue. And another question, why is the selected allocated to ="" ? I thought it is only a tag for html, that this value is the selected?

validateInput:

function validateInput($value) {
    $value = trim($value);
    $value = stripslashes($value);
    $value = htmlspecialchars($value);
    return $value;
}
هل كانت مفيدة؟

المحلول

The empty() function will return TRUE if the value is even 0.

So you should use the isset() function and != operation for checking

if(isset($_POST["monitors-old"]) and $_POST["monitors-old"]!=''){
    // code here
}
else{
    // code here
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top