【问题标题】:Prevent Form Submission if dynamic field is blank....Php / Jquery / Ajax如果动态字段为空,则阻止表单提交.... Php / Jquery / Ajax
【发布时间】:2017-10-23 16:09:05
【问题描述】:

你好朋友,我需要你的帮助,

如下图所示,我正在根据资产标题值从 mysql 数据库的下拉列表中动态加载问题选择框和问题答案选项。 (这工作正常)

但我的主要问题是我希望用户选择所有问题答案,然后只运行 ajax 函数并在 mysql 中插入数据库。

注意:有些资产有 1 个问题,有些有 3 个问题,有些资产有没有问题,这就是我没有使用以下代码的原因。

if(assettitle && customquestion1 && customquestion2){ ajax 等*** [如果我使用此代码,那么我将在没有任何问题的资产上遇到问题。]

【问题讨论】:

    标签: php jquery mysql ajax dynamic


    【解决方案1】:

    您可以在资产的某些数据属性中添加一个计数器,并在 AJAX 之前一次性对其进行验证。

    $('.assets-selected').on('change', function(){
       $(this).data( "selecteds", $(this).find('option').length);
    });
    
    function checkAssets(){
       $('.assets-selected').each(function(){
           if (typeof $(this).data('selecteds') == undefined ||  $(this).data('selecteds') < 1) {
                return false;
           } else {
                return true;
           }
       });
    }
    
    if(checkAssets()) {
                //submit the form to server
                $.ajax({
                    url : '../pages/php_action/addnewlead/creatlead.php',
                    type : 'POST',
                    data : form.serialize(),
                    dataType : 'json',
                    success:function(response) {
    
    
                        // remove the error 
                        $(".form-group").removeClass('has-error').removeClass('has-success');
    
                        if(response.success == true) {
                            $(".messages").html('<div class="alert alert-success alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-ok-sign"></span> </strong>'+response.messages+
                            '</div>');
    
                            // reset the form
                            $("#newleadform")[0].reset();
                            // reload page after 7 sec.
                            setInterval(function () {
                            location.reload(null, false);
                            }, 7000);
    
                        } else {
                            $(".messages").html('<div class="alert alert-warning alert-dismissible" role="alert">'+
                              '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+
                              '<strong> <span class="glyphicon glyphicon-exclamation-sign"></span> </strong>'+response.messages+
                            '</div>');
                        }  // /else
                    } // success  
                }); // ajax subit               
            } /// if
    

    从数据库中获取资产问题和答案 (PHP) - 将我在示例中展示的类放入

    你看你所有的问题都调用一次。在执行此操作之前进行检查以避免错误和其他问题

    <?php  
     //load_data.php  
     $connect = mysqli_connect("localhost", "root", "", "test");  
     $output = '';
     if(isset($_POST["assetid"]))  
     {  
    
      if($_POST["assetid"] != '')
      {  
           $sql = "SELECT * FROM customquestions WHERE assetid = '".$_POST["assetid"]."'";
    
      }  
      else
      {  
           $sql = "SELECT * FROM customquestions WHERE assetid = 'akash'";
    
      }
      $result = mysqli_query($connect, $sql);
      $quesno = 1;
    
      while($row = mysqli_fetch_array($result))  
      {  
          //poor and ugly way to do something to filter, the best solution is the questions have a table 1 to N, where the 1 table is cover, main information and the N the questions, so each index from your array will be filled only with the questions that db has stored else will bring nothing and you can validate better the frontend, besides provides more scalability.
            if ($row['colqa1'] == '' && $row['colqa2'] == '' && $row['colqa3'] == '' && $row['colqa4'] == '' && $row['colqa5'] == '' && $row['colqa5'] == '' && $row['colqa6'] == '' && $row['colqa7'] == '' && $row['colqa8'] == '' && $row['colqa9'] == '' && $row['colqa10'] == ''){
                 continue;
                //don't show dropdown if you don't have questions!  
           }
           $output .= '<div class="col-sm-6">';
           $output .= '<div class="form-group">';
           $output .= '<label for="campaignname">'.$row["cqname"].'</label>';
           $output .= '<select name="cq'.$quesno.'" size="5" class="form-control assets-selected" required>';
           // $output .= '<div style="border:1px solid #ccc; padding:20px; margin-bottom:20px;">'.$row["product_name"].'</div>';
           // $output .= '<tr><td>'.$row["cqname"].'<br></td>';
           $output .= '<option value="" required>Select Custom Question Answer</option>
                       <option value="'.$row["cqa1"].'">'.$row["cqa1"].'</option>
                       <option value="'.$row["cqa2"].'">'.$row["cqa2"].'</option>
                        <option value="'.$row["cqa3"].'">'.$row["cqa3"].'</option>
                        <option value="'.$row["cqa4"].'">'.$row["cqa4"].'</option>
                        <option value="'.$row["cqa5"].'">'.$row["cqa5"].'</option>
                        <option value="'.$row["cqa6"].'">'.$row["cqa6"].'</option>
                        <option value="'.$row["cqa7"].'">'.$row["cqa7"].'</option>
                        <option value="'.$row["cqa8"].'">'.$row["cqa8"].'</option>
                        <option value="'.$row["cqa9"].'">'.$row["cqa9"].'</option>
                        <option value="'.$row["cqa10"].'">'.$row["cqa10"].'</option>
                       </select>';
           // $output .= '<tr><td colspan="10"><hr></td></tr>';
           $output .= '</div></div></div>';
           $quesno++;
      }  
      echo $output;
     }  
     ?>
    

    【讨论】:

    • 感谢卡洛斯。我已经为您重新更新了我的问题...请重新检查
    • 我不明白我的回答中有什么不适合你,请给我澄清一下,好吗?
    • 太棒了.. 我对正在运行的 php 文件进行了更改,但仍然面临 jquery $('.assettitle').on('change', function(){ $(this) 中的问题.data("cq1", $(this).find('option').length); }); function checkAssets(){ $('.assettitle').each(function(){ if (typeof $(this).data('cq1') == undefined || $(this).data('cq1')
    • 什么问题?请告诉我错误或更具体的内容
    • @AkashSethi 注意,你把 cq1 作为数据名,不是很直观,其他是选项,你选择了所有选项,但你想要选择的,所以 $ (this).find('option:selected').length,检查控制台上的数据值是否正常,并在此处输入一些错误以允许我调试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 2017-11-18
    • 2012-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多