简体   繁体   中英

enabling and disabling a button using javascript and php

hi i really dont know a lot about javascript so sorry for this amatuer question. im trying to make a quiz page using php with 2 sets of questions. i want to disable the 2nd button for the other quiz and only be enabled when the user passed the first one.

this is what i wanted to happen:

<?php

require 'config.php';
$name = "kevin";
$result =mysql_query("select score from members where Username = '$name' " );

?>

<input name="button1" type="button" value="1" />
<input name="button2" type="button" value="2" disabled="disabled" />
<script type="text/javascript">

  if<?php $score is greater than  5 ?>{
         $('#button2').removeAttr('disabled');
    }
    else {
        $('#button2').attr("disabled","disabled");   

    }
});
</script>

any help will be much appreciated, thanks in advance.

You're trying to mix PHP and JavaScript, you can't do that. They run on completely different machines at completely different times.

Since the score is known server-side (in PHP) before the page is even sent to the client, make the conditional happen in the PHP code and only emit to the client the markup that you want. Something like this:

<?php

require 'config.php';
$name = "kevin";
$result =mysql_query("select score from members where Username = '$name' " );

?>

<input name="button1" type="button" value="1" />
<?php
    // use a real conditional, I'm just duplicating you for simplicity
    if ($score is greater than  5) {
?>
    <input name="button2" type="button" value="2" />
<?php
    } else {
?>
    <input name="button2" type="button" value="2" disabled="disabled" />
<?php
    }
?>

There's no need for JavaScript at all in this case, since the logic is all server-side.

Now you can still use JavaScript for more client-side interactions of course. Also, be aware that this isn't really any kind of security measure to prevent users from clicking on the button. Any user can modify the HTML/JavaScript being sent to them and still click on the button if they really want to. So if you need to prevent the user from doing something then that would need to be done server-side as well, in response to whatever action the user should not be authorized to perform.

You can try like this

if($score > 5){
?>
    <script>
    $(document).ready(function(){
        $('#button2').removeAttr('disabled');
    });
    </script>
<?
}else{
?>
    <script>
    $(document).ready(function(){
        $('#button2').attr('disabled');
    });
    </script>
<?
}

or if removeAttr/attr are not working then you can do like this

$('#button2').prop('disabled', false);
$('#button2').prop('disabled', true);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM