开发者

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 en开发者_如何学运维ter 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?

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


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; }


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...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜