How to put a default php option Selected

Asked

Viewed 433 times

-1

Boa wanted that if the year was 2012 paste the value with Selected is possible to do?

$ano[] = "<option value='$row[ano]'/>" 

2 answers

0

Here is the solution. If the year is 2012 the option is Selected. Now have to ensure that the year is 2012 only once.

$ano[] = "<option ".($row[ano]=='2012'?'selected':'')." value='$row[ano]'/>"
  • 1

    $row[ano]==12 That’s not right, the year comes with 4 digits, and he didn’t report that he’s only filtering the final two.

  • Thank you, I was distracted. :)

  • not the . I am using the datalist will be so

  • I’ve already solved...missing "" inside Row

  • Was useful then? If yes, great and good "coding" ! :)

0

To capture the current year, use

$anoAtual = date('Y');

To do what you want, you can use the PHP conditions

<?php

$anoAtual = date('Y');

if ($anoAtual == $row['ano']) {
    $ano[] = "<option value='{$row['ano']}' selected>";
} else {
    $ano[] = "<option value='{$row['ano']}'>";
}

Or so

<?php

if ($row['ano'] == '2012') {
    $ano[] = "<option value='{$row['ano']}' selected>";
} else {
    $ano[] = "<option value='{$row['ano']}'>";
}

There are many other ways, but this has to be evaluated according to your needs. Your question is not very clear.

I hope I’ve contributed.

  • I’m using a datalist maybe that’s why I wasn’t getting it

  • <input list ="years" class="form-control" placeholder="Year "type="search" id="year" Hidden="Hidden" name="Year" value="" /> <datalist id="years" > </datalist>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.