0

I need one help. I have some multiple textarea, radio button and dropdown list which are created by clicking on a button. I need to validate them for textarea has blank value, radio button check and dropdown select using JavaScript/jQuery. I am explaining my code below.

<div style="width:24%; float:left; padding:10px;">No of questions : 
<input name="no_of_question" id="ques" class="form-control" placeholder="no of question" value="<?php if($_REQUEST['edit']) { echo $getcustomerobj->no_of_question; } else { echo $_REQUEST['no_of_question']; } ?>" type="text" onkeypress="return isNumberKey(event)">
</div>
<div style="padding-bottom:10px;">
Questions : <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+" onClick="addQuestionField();"><input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-" onClick="deleteQuestionField();">
</div>

<script>
function addQuestionField(){
    var get =$("#ques").val();
    if(get==null || get==''){
        alert('Please add no of questions');
    }else{
        var counter = 0;
        if (counter > 0){
            return;
        }else{
             counter++;
              <?php
                   $status=array("status"=>'1');
                   $feeddata=$db->kf_answertype->find($ustatus); 
            ?>
            <?php
                 $status=array("status"=>'1');
                $feeddatascale=$db->kf_scale->find($ustatus);
            ?>
             for(var i=1;i<get;i++){

                  $('#container').append('<div><div style="width:24%; float:left; padding:10px;"> <textarea class="form-control" name="questions'+ i +'" id="questions'+ i +'" placeholder="Questions"  style="background:#FFFFFF;"  rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea></div><div style="float:left;margin-top:37px;"><div style="float:left; margin-right:10px;"><?php foreach($feeddata as $v){?> <input type="radio" name="answer_type'+i+'" id="answer_type0" onClick="selectScale(this.value,'+i+');" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?> <?php }?></div><div style="float:left; margin-top:-10px;display:none;" id="scaleid'+i+'"><select class="form-control" id="nscale'+i+'" name="noofscale'+i+'"><option value="">Select Answer Type</option><?php foreach($feeddatascale as $v){ ?><option value="<?php echo $v['_id']; ?>" <?php if($getcustomerobj->no_of_scale == $v['_id'] or $_REQUEST['no_of_scale'] == $v['_id']){ print 'selected'; } ?>><?php echo $v['noofscale']; ?></option><?php } ?></select></div><div style="clear:both;"></div></div><div style="clear:both;"></div></div>');

             }

        }
    }
}
</script>

Here when user will click on + button some multiple textarea, radio button and dropdown list dynamically. Here I need when my form will submit I need to check the validation of all whether those are not blank/checked. Please help me.

Midas
  • 7,012
  • 5
  • 34
  • 52
  • You're trying to output the html string in your loop using PHP. PHP does not work on client side. You need to use JS/jQuery to generate the elements string after getting number of questions and then appending them to your page ( DOM ). – Mohit Bhardwaj Jun 10 '16 at 12:56
  • i know this.Here user can validate this by taking each name attribute.I need how to do this in a loop. –  Jun 10 '16 at 12:58
  • Sorry, but I think you did not get my point. PHP should not be there in your JS code, if it depends on some user's input. PHP outputting is done on the server before the html page is sent to the client. So, you cannot expect PHP to run after getting input from user in an html `input` box. – Mohit Bhardwaj Jun 10 '16 at 13:00
  • Here user is using PHP for appending some dynamic data from DB. –  Jun 10 '16 at 13:02
  • Ok. May be because I can't see the surrounding PHP code, I got confused. Can you post a sample of the dynamic form generated so? I mean, the select, radio and textarea elements? What I do usually for such tasks is add a common class to all these elements, and a class identifying their type e.g. 'select-input', 'radio-input','textarea-input'. Then on form submit event, loop through all these elements using that common class and using a switch for the question type, check the condition e.g. if it's a select-input or text-area, check if( $(this)val().trim() != "" ). Makes sense? – Mohit Bhardwaj Jun 10 '16 at 13:10
  • let me to explain again.No matter what ever the php code its only setting the level text and value.suppose user is going to submit the form before submission user can validate these multiple fields using its id/name.I just wanted that. –  Jun 10 '16 at 13:14
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/114362/discussion-between-mike-and-subhra). – Mohit Bhardwaj Jun 10 '16 at 13:19

2 Answers2

1

From what I can understand from the question, I have deduced that you have a form with input controls. The user can press '+' to replicate/clone a div containing all input thus providing an additional form filled with input controls. If this is the case, you can use the following for validation to ensure that all currently visible input controls have been filled with data.

Pre-requisite: Ensure that all forms are assigned the same class name.

Example:

var visibleDivs = $(".DisplayableDiv:visible"); // .DisplayableDiv name of all class containing form controls
var hasValue = true;
// loop over all visible divs
for(i = 0; i < visibleDivs.length; ++i)
{
    $(visibleDivs[i]).find('input')
    .each(function() { // iterates over all input fields found
        if($.trim($(this).val()).length === 0) {
            hasValue = false; // if field found without value
            break;
        }
    });
}

if(hasValue === false) {
    // handle validation logic here (prompt user to complete all input areas etc)
}
Sandman
  • 2,247
  • 1
  • 13
  • 26
0

There are a number of problems with your code, but in particular you have the wrong approach.

Note that after the page is rendered and the DOM displayed, PHP has finished and no more PHP can run. So how do you do more stuff in PHP? Two options:

(1) Forms, or
(2) AJAX - it's pretty easy, see these simple examples

Ajax sends specified data to a backend PHP file. Note that you cannot post AJAX data to the same file that contains the AJAX javascript. You must use a second PHP file.

The backend PHP file receives the data, uses the incoming data (e.g. num of ques) to create new HTML in a $variable and then just echos that $variable back to the originating file, where it is received in the .done() function (aka the success function), as a variable (e.g. recvd). If you receive HTML code, then that code can be injected back into the DOM via methods like .append() or .html() etc.

Here is a rough approximation of how you might proceed.

$('#plus').click(function(){
  addQuestionField();
});
$('#minus').click(function(){
  deleteQuestionField();
});

function addQuestionField(){
  var numques = $("#ques").val();
  if(numques==null || numques==''){
    alert('Please add no of questions');
    return false;
  }
  var myAj = $.ajax({
    type: 'post',
     url: 'ajax.php',
    data: 'numques=' + numques,
  });
  myAj.done(function(recvd){
    $('#container').append(recvd);
  });
}
<style>
  #d1 {width:24%; float:left; padding:10px;}
  #d2 {padding-bottom:10px;}
</style>
<div id="d1" style="">No of questions : 
  <input id="ques" class="form-control" placeholder="no of question" type="text" />
</div>
<div id="d2">
  Questions : 
  <input type="button" class="btn btn-success btn-sm" name="plus" id="plus" value="+">
  <input type="button" class="btn btn-danger btn-sm" name="minus" id="minus" value="-">
</div>

Validating user-submitted data is a separate issue, but the basic idea is shown above when the $('#ques') value is validated -- if empty, we alert a message and return false to return control to the user.

Note that you can validate either client-side (jQuery) or server-side (PHP). The difference is that when you validate client-side, you can return control to the user without losing anything they typed. When you validate server-side, you must send back all the user-typed data and re-populate the controls manually (i.e. it's a lot more work)

Also note that if you validate client side, and you have ANY concern about hacking, then you must also re-validate server side because client-side validation can be easily hacked. But if it fails server-side validation you will know the user monkeyed with your validation and you can be less kind about re-populating their entries...

Here is a basic example of client-side field validation.

Community
  • 1
  • 1
cssyphus
  • 37,875
  • 18
  • 96
  • 111