MCM MCM - 4 months ago 35
PHP Question

Update variable depending on form selection

I currently have the following form :

<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<label for="categorie"> Tipul testului</label><br>
<select name="categorie" class="selectpicker">
<option value="1">Geometrie</option>
<option value="2">Algebră</option>
<label for="cerinta"><span class="glyphicon glyphicon-pencil"></span> Cerinţă</label>
<textarea type="text" class="form-control" id="cerinta" name="cerinta" placeholder="Cerinţă"></textarea>
<label for="rezolvare"><span class="glyphicon glyphicon-pencil"></span> Rezolvare</label>
<textarea type="text" class="form-control" id="rezolvare" name="rezolvare" placeholder="Rezolvare"></textarea>
<label for="nr_raspunsuri"><span class="glyphicon glyphicon-pencil"></span> Număr de raspunsuri</label>
<select class="selectpicker" name="nr_raspunsuri">
<option value="1">1</option>
<option value="2">2</option>

<table class="table">
<td class="col-md-6">
<button type="submit" class="btn btn-success btn-block" name="btn-add"><span class="glyphicon glyphicon-off"></span> Adăugare</button>
<td class="col-md-6">
<input type = "reset" class="btn btn-danger btn-block " label="Resetare"/>

What I am trying to do is to set a variable named $nr_raspunsuri to 1 or 2, depending on the selection of the user without refreshing the page.

For example, if he selects 2 in the second select field, I want to set the variable $nr_raspunsuri=2, so I can show one more input field in the form with an if in php. I think this can only be accomplished with AJAX. Is it true? If yes, how would you do it?


Your if in php will not run again until the page is reloaded. You can achieve it by toggling the view with javascript - when option with value 1 is selected from first select hide the element which shouldn't be seen, if option with value 2 is selected show it. You can achieve it using change event.