I've build a form but I'm kind of stuck at this thing where I have a yes or no field, and upon selecting yes some of the fields should appear otherwise those should be hidden if the user selects no. I'm not sure how to do it.
Here's the code:
<div class="container">
<h1>Research</h1>
<div class="form-group col-md-3">
<p>Do you have previous research experience? If yes, answer Questions...</p>
<input type="checkbox" name="yes" value="yes">
<label for="yes">Yes</label><br>
<input type="checkbox" name="no" value="no">
<label for="no">No</label><br>
</div>
<div class="form-group col-md-6" style="display: none">
<label for="lengthinresearch">Length of time in Research</label>
<input type="text" class="form-control" id="lengthinreseasrch" name="lengthinresearch">
</div>
<div class="form-group col-md-3">
<p>Type of Research</p>
<input type="checkbox" name="basic" value="basic">
<label for="basic">Basic</label><br>
<input type="checkbox" name="clinical" value="clinical">
<label for="clinical">Clinical</label><br>
</div>
<div class="form-group col-md-6">
<label for="researchinstitution">Research Institution</label>
<input type="text" class="form-control" id="researchinstitution" name="researchinstitution">
</div>
<div class="form-group col-md-6">
<label for="researchmentor">Research Mentor</label>
<input type="text" class="form-control" id="researchmentor" name="researchmentor">
</div>
</div>
My Answer:
You can achieve this functionality using JavaScript in combination with PHP. Here's an example of how you can do it:
1. Add an onchange event to your yes/no field in your form:
html
2. Add a JavaScript function to toggle the visibility of the additional fields based on the user's selection:
javascript
3. In your PHP file (submit.php), you can check the value of the yes/no field and process the form data accordingly:
php
if ($_POST['yesno'] === 'yes') {
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
// Process the form data for yes selection
} else {
// Process the form data for no selection
}
?>
With this setup, the additional fields will be hidden by default, and they will only appear if the user selects "Yes" from the dropdown. You can then process the form data in your PHP file based on the user's selection.
Rate this post
4 of 5 based on 2702 votesComments