Home > Net >  Rendering conditional HTML elements with PHP
Rendering conditional HTML elements with PHP

Time:12-06

Sup' There! I'm trying to learn PHP to solve an Assesment challenge, where I have to build a Product List & Add Product pages. Reading here and there, watching some tutorials I was able to develop this code so far:

Index.php:

<?php include("db.php"); ?>

<?php include("includes/header.php"); ?>


<div class="container p-4">
    <div class="row">
        <div class="col-md-4">
            <div class="card card-body">
                <!--INPUT FORM
                it will contains the form to add new product to the database:
                Fields: SKU / NAME / PRICE / PROD_TYPE / DVD / BOOK / FUR_H / FUR_W / FUR_L -->
                <form action="index.php" method="POST">
                    <div class="form-group">
                        <input type="text" name="sku" class="form-control" placeholder="Enter SKU Code">
                        <hr/>
                        <input type="text" name="name" class="form-control" placeholder="Enter Product Name">
                        <hr/>
                        <input type="text" name="price" class="form-control" placeholder="Enter Price">
                        <hr/>
                        <label>Product Type</label>
                        <select id="prod_type" name="prod_type" class="form-control" >
                            <option value="">Select Product Type</option>
                            <option value="DVD">DVD</option>
                            <option value="BOOK">BOOK</option>
                            <option value="FUR">FURNITURE</option>
                        </select>
                        <!-- <hr/> -->
                        <!--if the select(prod_type) option = DVD, then show the following fields:
                        Fields: DVD_SIZE
                        if the select(prod_type) option = BOOK, then show the following fields:
                        Fields: BOOK_WEIGHT
                        if the select(prod_type) option = FUR, then show the following fields:
                        Fields: FUR_H / FUR_W / FUR_L -->
                        <hr/>
                        <?php if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'DVD'){ ?>
                            <input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size">
                        <?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'BOOK'){ ?>
                            <input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight">
                        <?php } else if(isset($_POST['prod_type']) && $_POST['prod_type'] == 'FUR'){ ?>
                            <hr/>
                            <input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
                            <hr/>
                            <input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
                            <hr/>
                            <input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
                        <?php } ?>
                        <!-- <hr/>     -->
                    </div>
                    <hr/>
                    <input type="submit" name="add_product" class="btn btn-success w-100" value="Add Product">

                </form>
            </div>
        </div>
        <div class="col-md-8">

        </div>
    </div>
</div>


<?php include("includes/footer.php"); ?>
    

Thing is, inputs for DVD Size, BOOK Weight and Forniture dimensions ( H, W & L ) should be render depending User selection on #prod_type. Currently those inputs show up after the User choose a select option, and hit Add Product button ( related to POST method I pressume, is the closest that i get ) Regards in advance...

CodePudding user response:

PHP runs entirely on the server. If you want things to happen in the browser when your user interacts with your webpage (without performing a round-trip to the server), Javascript is your friend.

In this case, I would give each input a data attribute to say which product type they are relevant for. Then you can write a Javascript function to handle changes to the prod_type field and show/hide the correct fields.

For example:

function toggleFields() {
    var productType = document.getElementById('prod_type').value;
    var fields = document.querySelectorAll('[data-if-prod-type]');
    
    fields.forEach(function (field) {
        if (field.dataset.ifProdType === productType) {
            field.style.display = '';
        } else {
            field.style.display = 'none';
        }
    });
}

document.addEventListener('DOMContentLoaded', function() {
    document.getElementById('prod_type').addEventListener('change', toggleFields);
    
    // Run the toggle function when the DOM is ready loading,
    // so that fields that are not relevant to #prod_type's
    // initial value are hidden.
    toggleFields();
});
<select id="prod_type" name="prod_type" class="form-control">
    <option value="">Select Product Type</option>
    <option value="DVD">DVD</option>
    <option value="BOOK">BOOK</option>
    <option value="FUR">FURNITURE</option>
</select>

<input type="text" name="dvd_size" class="form-control" placeholder="Enter DVD Size" data-if-prod-type="DVD">
<input type="text" name="book_weight" class="form-control" placeholder="Enter Book Weight" data-if-prod-type="BOOK">
<div data-if-prod-type="FUR">
    <hr/>
    <input type="text" name="fur_h" class="form-control" placeholder="Enter Furniture Height">
    <hr/>
    <input type="text" name="fur_w" class="form-control" placeholder="Enter Furniture Width">
    <hr/>
    <input type="text" name="fur_l" class="form-control" placeholder="Enter Furniture Length">
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can try AJAX. It's easy to use and also you will like it's functionalities. The thing you wanted in your page can be done easily with the AJAX. If you know little bit about Javascript and jQuery, you will love it. W3School can explain you in detail about it - AJAX Introduction

Example of usage of AJAX into your code,

index.php:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>Index Page</title>
</head>
<body>
<?php
if(isset($_POST['prod_type'])){
   print_r($_POST); die;
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
    <select name="prod_type" onchange="getProdOptions(this.value)">
        <option value="">Select Product Type</option>
        <option value="DVD">DVD</option>
        <option value="BOOK">BOOK</option>
        <option value="FUR">FURNITURE</option>
    </select>
    <div id="option_area"></div>
    <input type="submit" name="add">
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> // CDN link of jQuery, you can get from - https://cdnjs.com/libraries/jquery

<script type="text/javascript">
    function getProdOptions(val) {
        val = val.trim();
        if(val !== '') {
            $.ajax({
                url: "/ajax_request.php", // url is the destination to receive the request
                data: {
                    prod_type: val
                }, // data is the key and the value you are sending
                type: "POST", // method is GET, POST, etc..
                success: function( response ) {
                    response = JSON.parse( response );
                    if( response.status ){
                        document.getElementById( 'option_area' ).innerHTML = response.data; // Pure JS Syntax
                    }else{
                        alert('No data for the selected prod type.');
                    }
                }
            });
        }else{
            $("#option_area").html(""); // jQuery Syntax
        }
    }
</script>

ajax_request.php:

<?php
if( isset( $_POST['prod_type'] ) && !empty( $_POST['prod_type'] ) ) {
$response = ['status' => true];
// any condition to check and the condition not met thenn send the status as false
$html = '<input type="text" name="dvd_size"  placeholder="Enter DVD Size">';
$html .= '<input type="text" name="book_weight"  placeholder="Enter Book Weight">'; // `.=` will concatenate the strings
$response['data'] = $html;
echo json_encode( $response );
}
?>
  • Related