Search code examples
javascriptphphtmlrequired

How to add a required attribute?


I have a script that shows some and hides some html but I dont know how to add the required tag when it is shown, I have already tried to add the attribute in the section that I want it but it requires it even when not shown... can someone help me out. thanks in advance!

<div  class="start"><select name="start" class="form-control">
           <option value="0" class="select">Select City</option>
                <?php foreach($rows as $row): ?> 
                    <option <? echo 'value="'.$row['id'].'"';
                        echo ($row['id'] == $job['start'])?' selected>':'>'; 
                        echo $row['name']; ?></option>
                <?php endforeach; ?>
            </select></div><br />
            <br />
            <script>
            $('select[name=start]').change(function () {
                if ($(this).val() == '89') {
                    $('#otherStart').show();
                } else {
                    $('#otherStart').hide();
                }
            });
            </script>
            <br />
            <div id="otherStart">
                <input type="text" name="otherStart" placeholder="Other City" <? echo ($job['otherStart'])?' value="'.$job['otherStart'].'"':''; 
            ?> class="form-control" >
            </div>

Solution

  • First of all, you need to assign an id-attribute to the input you're modifying, so that we can change the attributes with jQuery. You already use <div id="otherStart"> to show/hide the entire div, so select another name, for example id="inputOtherStart" (IDs should always be unique).

    Then we use jQuery to add and remove the attribute when we show and hide the div, respectively.

    <script>
    $(function() {
        // Function to show/hide the extra subject-field, and making it required or not
        var Start = '#Start';
        var otherStart = '#otherStart';
        var otherStartInput = '#otherStartInput';
    
        $(otherStart).hide(); 
        $(Start).change(function(){
            if($(Start).val() == 89) {
                $(otherStart).show();
                $(otherStartInput).prop('required',true);
            } else {
                $(otherStart).hide(); 
                $(otherStartInput).prop('required',false);
            } 
        });
    });
    </script>
    <br />
    <div id="otherStart">
        <input type="text" id="otherStartInput" name="otherStart" placeholder="Other City" <? echo ($job['otherStart'])?' value="'.$job['otherStart'].'"':''; ?> class="form-control" />
    </div>