简体   繁体   中英

If one field in row is entered, all the other fields in the row are required

This is a code to enter date, select in/out and location. If the user want more fields to enter i also added a addRow function.

<table>    
for($i=0;$i<15;$i++){ 
<tr><td>
<input type='datepick' name='scheduledatepick[$i]' />
<select name='schedulein[$i]' /><option>--</option>
<input type='text' name='location[$i]' />
</td></tr>
}
</table>

Now my question is if a user entered a field in a row(maybe datepick or schedulein or location) then he must enter all the other fields in that same row. How to achieve this? 在此输入图像描述

PHP-side:

$errs = array();
for ($i = 0; $i < 15; $i++) {
    $cnt = empty($_REQUEST['scheduledatepick'][$i]) + empty($_REQUEST['schedulein'][$i]) + empty($_REQUEST['location'][$i]);
    if ($cnt > 0) && ($cnt != 3) {
        $errs[] = "Row $i not completed";
    }
}
if (count($errs) > 0) {
   ... at least one incomplete row
}

Javascript-side would be somewhat equivalent, with extra code to handle differences between selections, checkbox, text fields, textareas, etc...

Assuming you want this to happen on a button click, you can do this: Working Demo

jQuery

$('button').click(function() {
    // set up an array to store the invalid rows
    var rows = new Array();
    $('table tr')
        // reset all rows before we validate
        .removeClass("error")
        // loop over each row
        .each(function(i) {
            // work out whether the fields are completed or not
            var filledFieldCount = 0;
            filledFieldCount += $("[name='scheduledatepick[" + i + "]']", this).val().length > 0 ? 1 : 0;
            filledFieldCount += $("[name='schedulein[" + i + "]']", this).val() !== "--" ? 1 : 0;
            filledFieldCount += $("[name='location[" + i + "]']", this).val().length > 0 ? 1 : 0;

            // if the total completed fields for this row
            // is greater than none and less than all
            // then add the row to the invalid rows list
            if (filledFieldCount > 0 && filledFieldCount < 3) {
                rows.push(this);
            }
         });

    // finally, change the background of the
    // rows to mark them as invalid
    if (rows.length > 0){
        $(rows).addClass("error");
    }

});

CSS

.error { background-color: red; }

You need to parse the form.
If a line is incomplete, throw an error message to the user.
All this in Javascript.

Then you have to implement the same check in PHP. The Javascript check is convenient to give an immediate response to the user, but it can be easily neutralized.

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