Input is not being checked via php

Asked

Viewed 57 times

1

I have the following input:

<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" <?php if(Mage::getSingleton('core/session')->getInputMensagem() == 1){echo "checked='checked'"} ?> /> 

Trying to check he saw php is not working because the same is not coming checked. Doing this via jQuery, it is checked correctly, but it takes too long to perform it and ends up affecting the functionality of the page.

Check via jQuery:

$j(document).ready(function () {
     <?php 
        if(Mage::getSingleton('core/session')->getInputMensagem() == 1) {
     ?>
          $j('#isgift0').prop('checked','checked');
          $j('#isgift0').click();
     <?php
        }
     ?>
});

I was wondering if you had any way to do that same check, but in a faster way.

2 answers

1


The way you did using PHP is correct, just forgot to close the code line with ;, that would look like this (as quoted in the other answer, one can only use checked):

<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" <?php if(Mage::getSingleton('core/session')->getInputMensagem() == 1){echo 'checked';} ?> />

Alternatively, you can check the radio so instant using Pure Javascript instead of jQuery with document ready (which takes longer to load). Simply insert a script right after the element:

<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" />
<?php
if(Mage::getSingleton('core/session')->getInputMensagem() == 1){
   echo '<script>document.getElementById("isgift0").checked = true;</script>';
}
?>

Why do I say "instantly"?

How the page is loaded from above down, the Javascript browser interpreter will already be ready and will run the script just after loading the widget radio in question, checking it immediately before the rest of the page is loaded.

But the first option using only PHP is still the best, as it is direct and will not need to add more code on the page.

  • Excellent explanation. Thank you so much for your help!

1

Matheus if you want via PHP do so:

<?php
$checkedisgift0 = Mage::getSingleton('core/session')->getInputMensagem() == 1 ? 'checked' : '';
?>

<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" <?php echo $checkedisgift0; ?> />

And remove the jQuery part you created just for this, so when you have the session ==1 will display something like:

<input type="radio" id="isgift0" name="isgift" value="0" class="arredondado" checked />

In Html5 it is not necessary checked=checked suffice checked.

Still it is good to note that the elements can not repeat the Ids and the radio type is usually used for multiple choice, if there will only be a radio with the same name (name="isgift") so it is preferable to use type="checkbox"

Browser other questions tagged

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