简体   繁体   中英

Add Validation to dynamically created text boxes JavaScript PHP

I am creating dynamic text boxes based on user input in Jquery. Now I want to validate those dynamic text boxes either in Php or in JavaScript so that empty values did not enter in my database . I tried a lot but still if I left the text boxes blank Empty values enter in database . I don't know where is the problem.

Below is my Code..

(JavaScript)

var p_number = $("#p_number").val();
var quantity = $("#quantity").val();

if(p_number!="" && quantity!=""){

         var x = 0;
        $("#btn").hide();
        $("#p_number").hide();
        $("#quantity").hide();
        //alert("hello");
        for(var i=0;i<quantity;i++){

        $("#contact-form").append('<div class="control-group"><input type="text" class="form-control" name="mytext[]" style="float:left; margin-top:25px; width: 40%;height: 40px; margin-left: 260px;"/></div>');  

        x++;

       if(x==6) break;      

    }

    $("#contact-form").append('<input type="submit" class="btn btn-theme" name="p_submit" id="btn_package" value="Add Package"  style="float:left; margin-left:-260px; margin-top:80px;"/>');


   return false;   


}

(PHP)

if(isset($_POST['mytext'])){

    //$hall_id = $_SESSION['hall_id'];
    $hall_id = 7;
    $package_id = $_POST['p_number'];

    if($_POST['mytext'] == ''){
        $error = "Error";
    }
    else{
    $i=0;
    foreach($_POST["mytext"] as $key => $text_field){
        $capture_field_vals[$i] = $text_field;
        $i++;
        //echo $text_field;


    $food_items = $capture_field_vals[$itr];


    $query = mysql_query("INSERT INTO shaadi_hall_package (id, hall_id, package_id, food_item) VALUES ('', '$hall_id', '$package_id', '$food_items')") or die (mysql_error());

   $itr++;

    }
}

if($query){
       $message = "<span class='success'>Information Added Successfully!! </span>";
}
else{
       $error = "<span class='error'>OOPS!! An Error occured. Try Again</span>";

}


}

Please help me out. Thanks in advance.

foreach ( $_POST['mytext'] as $key => $val ) {
    // ignore any empty values
    if ( $val == '' ) {
        $error = 'ERROR';
        continue;
    }

    // do something with $val here
}

if ( $error ) {
    // output error message here
} else {
    // output a happy message here :)
}

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