How to validate textarea and radio button in a loop - javascript

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.

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

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.

Related

prevent result, show through AJAX, after reload browser

I have a insert query through ajax. It is working correctly. But when I reload browser then result disappears from div section and if I insert form through ajax again then result is showing.
I have a file first.php (in which, form is present), a AJAX code and a firstcall.php where query will be execute.
My first.php (html form) is:
<form class="reservation-form mb-0" action="" method="post" autocomplete="off">
<input name="name1" id="name1" class="form-control" type="text" placeholder="Enter Name" required aria-required="true">
<input name="age" id="age" class="form-control" required type="number" placeholder="Enter Age" aria-required="true">
<input type="checkbox" id="checkbox" class="checkbox1" name="namec[]" value="<?php echo $value['id']; ?>" >
<input type="button" class="pull-right btn btn-warning" value="Submit" id="submit">
</form>
Here data should be display:
<div class="col-md-5">
<div class="panel panel-primary" id="showdata">
<!-- Here is the results, but when reload browser then result disapper-->
</div>
</div>
AJAX is:
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(){
var name1 = $("#name1").val();
var age = $("#age").val();
var chkArray=[];
$('.checkbox1:checked').each( function() {
chkArray.push($(this).val());
} );
var selected;
selected = chkArray.join(',') ;
if(selected.length > 1){
$.ajax( {
url:'firstcall.php',
type:'POST',
data:{name1: name1,age: age,namec: chkArray},
}).done(function(data){
$("#showdata").html(data);
});
}
else{
alert("Please at least one of the checkbox");
}
});
});
</script>
firstcall.php is:
<div class="panel panel-primary" id="showdata">
<?php
foreach($_POST['namec'] as $selected){
echo $selected;
$_SESSION['name1']=$_POST["name1"];
$_SESSION['age']=$_POST["age"];
echo $name1=$_SESSION['name1'];
echo $age=$_SESSION['age'];
$query=mysql_query("insert into patient_details (p_name,p_age,g_number) values ('$name1','$age','$selected')") or die(mysql_error());
}
?>
First of all fix your query to use MySQLi, instead of MySQL, check this or the PHP manual
Also don't ever add direct $_POST or $_GET variables into your mysql query, filter them first using mysqli_real_escape.
$name1 = mysqli_real_escape($link, $_POST["name1"]);
$age = mysqli_real_escape($link, $_POST["age"]);
After that, to show the data when the page reloads, you need to load the data with the page, easiest way to do that is just add in your HTML PHP tags with an echo command inside, adding your variables.
If I understand your question correctly, you want the Ajax result to also show on page load?
Right now you only execute the JS after a click (so on page load/relaod you will just see the html), you might want to execute it after page load aswell (so execute the script without the .click)
You could create a function once, and call it when the page is ready and on click.

Javascript button click change / create PHP variable on same page

I have searched stackoverflow for the past hour and have found similar questions but attempting the solution has given me only errors - it may be as I am trying to load it on the same page.
I have tried saving the value to a cookie in JS then loading it in php, also attempted through ajax, etc.
From what I've read it can't just be done within as PHP is server side and Javascript is browser side which I get.
I currently have a .html page with a form that sends values through POST:
form.html
<form id="calc" form name="calculator" method="post" action="/calculate.php">
The solution is not with the form, I can't have hidden fields as I need to user input. I could have a radio box in the form yes and then get the value that way, but that's not my question. My question is how I can get the user's input and turn it into php on the page the form redirects to calculate.php:
calculate.php
<?php
if(isset($_POST['submit'])){
$x= $_POST['value'];
echo "your something:";
echo $x;
?>
Click button below for option one to do this, or click two for that, or three for something else...
<button id="one"> one </button>
<script>
$(document).ready(
function() {
$("#one").click(function() {
make php value 1
});
</script>
use php value from click
So the user will already have clicked submit. Then be redirected onto the .php page with their inputs, they can then choose button 1, 2 or 3 for example through javascript on calculate.php NOT the form.
My problem is I need to know on the same page - calculate.php, which button has been clicked in php. So that I can use their input and do different things with it depending on which button.
Is it possible to get a value to be set or create one from a button click on calculate.php itself with the javascript button producing a php value on the same page? Does it need to be loaded from an external.php page through ajax? Is there any other way?
PHP Option:
<?php
if(isset($_POST['submit'])){
$x= (isset($_POST['one'])) ? $_POST['one'] : '';
$y = (isset($_POST['two'])) ? $_POST['two'] : '';
$z = (isset($_POST['three'])) ? $_POST['three'] : '';
echo "your something:";
echo $x;
echo $y;
echo $z;
?>
<form name="calculator" method="post">
<INPUT TYPE="RADIO" NAME="one" VALUE="1"> ONE
<INPUT TYPE="RADIO" NAME="two" VALUE="2"> TWO
<INPUT TYPE="RADIO" NAME="three" VALUE="3"> THREE
<input type="submit" value="Submit">
</form>
JS mode:
if(isset($_POST)){
$value= (isset($_POST['value'])) ? $_POST['value'] : '';
$previous = (isset($_POST['previous'])) ? $_POST['previous'] : '';
//play with value and previous one
$x = //your algorithm;
echo "your something:";
echo $x;
?>
<form name="calculator" method="post">
<button type="button" value='1'>ONE</button>
<button type="button" value='2'>TWO</button>
<button type="button" value='3'>THREE</button>
<input name='value' type='hidden' value=''>
<input name='previous' type='hidden' value='<?= (isset($x)) ? $x : ''?>'>
</form>
<script>
$(document).ready(
function() {
$("button").click(function() {
$('input[name=value]').val($(this).val());
$('form').submit();
});
</script>
use php value from click

Submit arrays from form fields to database [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
There is a sewing management app am working on and on the order page, someone can have multiple orders, but all orders are to be invoiced using one reference code. First page, I collected basic details such as pricing, but on next page, each individual order has to be entered in more detail, a sample picture of the material, instructions and style code if any.
So I've been able to successfully create the page where the data entry person can add multiple details and even select whether there's a style or not, but am stuck in the database submission.
Remember, every other pages am working with, like staff management and others are working just fine, so this error of not submitting to the database is not relative to an external page included or any other thing except probably how the arrays are handled. Below is a breakdown of the code;
JavaScript:
<script>
function showfield(name,event){
if(name=='iHaveStyle') {
$(event).next('#div1').html('<label>Enter Style Code</label><br /> <input type="text" name="style[]" />');
} else{
$(event).next('#div1').html('');
}
}
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".form-group"); //Fields wrapper
var add_button = $(".add_field_button"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div style="margin-top:20px; border-top:1px solid #333333;"><label>Upload Sample Material</label><br /><input type="file" name="sample_material[]" style="width:200px; height: 40px;" /><br/><br/><label>Customer&#39s Requirement</label><br /><textarea name="cust_requirement[]" style="width:200px; height: 150px;" /></textarea><br/><br/><label>Do you have a style</label><br /><select name="sketch_code" id="sketch_code" onchange="showfield(this.options[this.selectedIndex].value,this)"><option value="">I don&#39t have a style code</option><option value="iHaveStyle">I have a style code</option></select><div id="div1"></div><br />Remove</div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
</script>
HTML:
<form action="orderadd1.php?id=<?php echo "".$order_id; ?>" method="post" enctype="multipart/form-data">
<div class="form-group">
<button class="add_field_button">Add another sub-order</button>
<div style="margin-top:20px;">
<label>Upload Sample Material</label><br />
<input type="file" name="sample_material[]" style="width:200px; height: 40px;" /><br/><br/>
<label>Customer's Requirement</label><br />
<textarea name="cust_requirement[]" style="width:200px; height: 150px;" /> </textarea><br/><br/>
<label>Do you have a style</label><br />
<select name="sketch_code" id="sketch_code" onchange="showfield(this.options[this.selectedIndex].value,this)">
<option value="">I don't have a style code</option>
<option value="iHaveStyle">I have a style code</option>
</select>
<div id="div1"></div>
</div>
</div>
<input type="submit" class="btn btn-lg btn-color btn-block" value="Continue Order" name="submit_val">
</form>
PHP Code:
<?php
$order_id = $_REQUEST['id'];
if (isset($_POST['submit_val'])) {
if(is_array($_POST['cust_requirement']))
{
for($i=0; $i < count($_POST['cust_requirement']); $i++ ) {
$cust_requirement = mysql_real_escape_string($_POST['cust_requirement'][$i]);
$style = mysql_real_escape_string($_POST['style'][$i]);
$folder = "sample_material/";
$extention = strrchr($_FILES['sample_material']['name'], ".");
$new_name = $order_id."-".$i++;
$sample_material = $new_name.'.jpg';
$uploaddir = $folder . $sample_material;
move_uploaded_file($_FILES['submit_material']['tmp_name'], $uploaddir);
$data_submit = $pdo->query("INSERT INTO `order_desc` (order_id, sample_photo_url, cust_requirements, style_code) VALUES ('".$order_id."', '".$uploaddir."', '".$cust_req."', '".$style."')");
}}
}
?>
The error it is showing is:
Warning: strip_tags() expects parameter 1 to be string, array given in C:\xampp\htdocs\tms\header.php on line 2
I checked the header.php and this is exactly what I have there:
<?php
$_POST = array_map('strip_tags', $_POST);
?>
I used this header on all my pages and they are fine.
array_map function applies strip_tags() to every element of an array - but the most possible reason of this is that your $POST looks like this ['test1',['test2','test3]], $POST[1] == ['test2','test3] is an array and strip tags cannot be applied. You can do it using loop and checking if item is not an array to be stripped, or use recursion to go all over you $POST array
Your POST superglobal contains arrays that is why you get a warning with array_map. Try replacing it with array_walk_recursive http://php.net/manual/en/function.array-walk-recursive.php

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

form with 2 buttons need to call different functions based on value

I have a page which has lot of post data in the url.
For example,
www.test.com/test.php?userid='tester'&name=test&so on
The above page has a form that has something like this:
<?
$set=get_value_set;
if($set ==1) {
$set_value="SET";
} else {
$set_value="UNSET";
}
?>
<form name="test">
<input type="text" readonly="READONLY" value="<? echo $user_id; ?>">
<input type="submit" value="Email" name="submit_user">
<input type="submit" value="<? echo $set_value; ?>" name="submit_user">
<?
function setuser()
{
//sets the value
}
function email_user()
{
//sets the value
}
?>
there are two buttons above, when I click on email, i want the value of email button to be passed to the email_user function and do some proceesing there. Similar thing when I click on the set button.
NOTE:But in both cases above, I want the form to remain in the same page with the same post data in the url, but I also want the page to be refreshed so that the set button can have a value of Set or Unset depending on the database update.
Is this possible?
I would start to remove the submit action of each button and change them to
<input type="button" class="btn-Email" value="Email" name="submit_user" />
<input type="button" class="btn-Other" value="<? echo $set_value; ?>" name="submit_user" />
and then, using jQuery, you can easily process each click and submit the form
$(function() {
$(".btn-Email").click(function() {
// append anything you want
var but_email_value = $(this).val(), // or $(".btn-Email").val()
btn_other_value = $(".btn-Other").val();
$("form").submit();
});
$(".btn-Other").click(function() {
// append anything you want
var but_other_value = $(this).val(), // or $(".btn-Other").val();
btn_email_value = $(".btn-Email").val();
$("form").submit();
});
});
change your HTML
<form id="test" name="test">
...
<button onclick="email_user();">Email</button>
<button onclick="setuser();"><? echo $set_value; ?></button>
</form>
your functions should submit the form for you:
document.getElementById("test").submit();

Categories

Resources