0

If i want to disable a checkbox with html i need to insert it in input tag.

<input type="checkbox" class="someone" name="any"  disabled> html

But if i want to build it with PHP and disable depends on a condition i will write:

$question = 'foo';
        echo '<input type="checkbox" class="someone" name="any"';
                if ($question == 'foo'){
                    echo 'disabled';
                }
                echo '">php';
                echo '<br>';
                echo '<input type="checkbox" class="someone" name="any"  disabled> html';

If you try you will see form google devtools that are write at same way but only html works

enter image description here

Why????

1
  • 1
    the two pieces of code are not the same - look at the extra " at the end after disabled Commented Mar 12, 2020 at 13:55

2 Answers 2

2

The problem with the above PHP is that you incorrectly have an extra closing quote - if you were to use printf you needn't have complicated/confusing syntax like this.

Consider:

printf(
    '<input type="checkbox" class="someone" name="any" value="1" %s />', 
    ( $question=='foo' ? 'disabled' : '' )
);

The %s is a placeholder which is substituted by the value from the ternary operator.

Sign up to request clarification or add additional context in comments.

Comments

0

It might be because both inputs have the same name attribute. Each checkbox is a unique input element, and generally each have their own distinct value for the name attribute. I'm not entirely sure, but having two inputs with the same name might cause unpredictable behavior in browsers.

Just as a heads up, you can also simplify the way you write that code, as well, by using a string variable inline, like so:

$question = 'foo';
$disabled = $question ? 'disabled' : ''
echo '<input type="checkbox" class="someone" name="any" '.$disabled.'>';

Even better, it's best practice to separate your HTML from your PHP for example like so:

<?php
    $question = 'foo';
    $disabled = $question ? 'disabled' : '';
?>

<input type="checkbox" class="someone" name="any" <?php echo $disabled; ?>>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.