I have this form in the view:
<form method="POST" action="<?php echo Yii::$app->request->baseUrl;?>/telephone/addnow/" role="form" enctype="multipart/form-data">
<label>Upload your photo:</label><input type="file" name="image" ><br>
<input type="name" name="name" id="name" placeholder="Name" required><br><br>
<input type="text" name="address" placeholder="Address"><br><br>
<input type="text" name="telephone" placeholder="Telephone number" required>
<br><br>
<div id="dynamicInput">
<br><input type="text" name="myinputs[]" placeholder="Secondary Phone #1">
<span class="glyphicon glyphicon-plus" onClick="addInput('dynamicInput');"></span>
<br><br>
</div>
<input type="text" name="mobile" placeholder="Mobile number" > <br><br>
<input type="email" name="email" placeholder="Email">
<input type="email" name="altemail" placeholder="Alternative Email"><br><BR>
<input type="text" name="company_name" placeholder="Company Name"><br><BR>
<input type="text" name="company_address" placeholder="Company Address"><br><br>
<input type="text" name="company_phone_primary" placeholder="Company Telephone">
<input type="text" name="company_phone_secondary" placeholder="Telephone Secondary "><br><br>
<input type="text" name="company_email" placeholder="Company Email Address"><br><BR>
<button type="submit" class="btn btn-default">Submit</button><BR><BR>
</form>
allowing the user to insert any number of secondary phones i used this javascript code:
<script>
var counter = 1;
var limit = 10;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Seconday Phone # " + (counter + 1) + " <br><input type='text' name='myinputs[]' placeholder='Secondary Phone '>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
And I have this controller code:
public function actionAddnow()
{
$request = Yii::$app->request;
$add=new telephone();
$add->Name=$request->post('name');
$add->Email=$request->post('email');
$add->Mobile=$request->post('mobile');
$add->Address=$request->post('address');
$add->Telephone=$request->post('telephone');
$add->altemail=$request->post('altemail');
$add->company_name=$request->post('company_name');
$add->company_address=$request->post('company_address');
$add->company_phone_primary=$request->post('company_phone_primary');
$add->company_phone_secondary=$request->post('company_phone_secondary');
$add->company_email=$request->post('company_email');
$add->save();
$getlast=Yii::$app->db->getLastInsertId();
$myinputs=$request->post('myinputs');
$totalinputs=sizeof('$myinputs');
for ($i=0; $i<=$totalinputs; $i++) {
$inputs=$myinputs[$i];
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
return $this->redirect(Yii::$app->request->baseUrl.'/telephone/index');
}
but only the first two values of $myinputs are inserted in the database.
Putting variable $myinputs between single quotation marks ('$myinputs') you will convert your variable to string. sizeof is alias for count function, but as you give argument as string you allways get result as 1. After you will loop with condition ($i=0; $i<=$totalinputs; $i++) meaning that cycle will run 2 times when $i is 0 and when $i is 1.
Instead of:
$totalinputs=sizeof('$myinputs');
You should use
$totalinputs=sizeof($myinputs);
Another error is in your cycle condition.
for ($i=0; $i<=$totalinputs; $i++)
Should be
for ($i=0; $i<$totalinputs; $i++)
Or you could replace for cycle with foreach
foreach($myinputs as $inputs)
{
$phones=new phone();
$phones->secondary_phones=$inputs;
$phones->id=$getlast;
$phones->save();
}
On Yii side of improvements
1.For form you could use ActiveForm widget
$form = \yii\widgets\ActiveForm::begin([
'options' => [
"role" => "form",
"enctype"=> "multipart/form-data",
], ]);
echo $form->field($add, 'Name');
//etc
$form->end();
2.If you would use ActiveField for creating input fields in view or adding manually field names in format like ModelClassName[ModelFieldName], then you would be able to use Model load for assaign'ing values
Example:
$add=new telephone();
if ($add->load(Yii::$app->request->post()))
{
if ($add->save())
{//saved
}
else
{//error
}
}
else
{//no post data
}
3.For urls its probably not needed to add request baseUrl property. Example in redirect you can simply use
$this->redirect('/telephone/index');
4.Using method getLastInsertId() may lead to errors when there are some triggers in database that will create additional rows. So it may be wiser to use:
$getlast=$add->id;//assuming model autoincrement field name is "id"
Related
i have a form with texfeilds added dynamically by javascript.am using an array to extract the textfeild values in a php file. all seems to be well. but am havin trouble saving the data into the database. please help. below is my code.
form values here
<form method="POST" id="theForm" action="invpdf.php"><div id="fields">
<input type="text" name="fields[barcode][]"/>
<input type="text" name="fields[description][]"/>
<input type="text" id="unity"name="fields[unitprice][]" />
<input type="text" id="qty"name="fields[qty][]"/>
<input type="text" id="total"name="fields[total][]"/>
<br/>
</div>
<input type="button" id="addField" value="Add Field"/></form>
javascript to add textfeilds
<script>
$(document).ready(function() {
$('#addField').click(function() {
$('#fields').append(
$('<input type="text" name="fields[barcode][]"/>'),
$('<input type="text" name="fields[description][]"/>'),
$('<input type="text" name="fields[unitprice][]"/>'),
$('<input type="text" name="fields[qty][]"/>'),
$('<input type="text" name="fields[total][]"/>'),
$('<br/>')
);
})
});
</script>
my php processing as this code below
$numemma = count($_POST['fields']['barcode']);
for ($i = 0; $i < $numemma; $i++) {
$field = array(
'barcode' => $_POST['fields']['barcode'][$i],
'description' => $_POST['fields']['description'][$i],
'unitprice' => $_POST['fields']['unitprice'][$i],
'qty' => $_POST['fields']['qty'][$i],
'total' => $_POST['fields']['total'][$i]
);
$feeilds = '`'.implode('`,`', $field).'`';
$data = '\''.implode('\',\'',$field).'\'';
mysqli_query($conn,"INSERT INTO `sales`($feeilds)VALUES($data)");
}
I am creating an order page in Jquery Mobile where user fill data and quantity .
Creating Dynamic Fields
Whenever user fills the data in quantity, say use entered 1, then only one dynamic field will generate. code below
HTML
<label for="textarea2b">Quantity</label>
<input type="number" name="name2" id="quantitypickup" onkeyup="showdimension()" value="" data-clear-btn="true" placeholder="">
<div id="dimshow" class="row">
JS to show dynamic field
function showdimension() {
var q = $("#quantitypickup").val();
var r = $("#dimshow");
if (q == "0" || q == "" || q == null) {
r.hide();
r.html('');
} else {
r.show();
r.html('');
for (var i = 0; i < q; i++) {
r.append(' <div class="col-xs-6"><label>Item Name ' + (i + 1) + '</label><input type="text" name="name2" id="itemname" onkeyup="" value="" data-clear-btn="true" placeholder=""></div><div class="col-xs-6"><div class="row"><div class="col-xs-4"><label>Length</label><input type="number" id="length" name="name2" onkeyup="" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div><div class="col-xs-4"><label>Width</label><input type="number" name="name2" id="width" onkeyup="" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div><div class="col-xs-4"><label>Height</label><input type="number" id="height" name="name2" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div></div> </div></div>');
}
}
}
I want to insert this into database using mysql and php how can I do so.
Below is the fiddle
https://jsfiddle.net/ankit10594/5suemmyk/
Please help
In js: update id & name field
for (var i = 0; i < q; i++) {
r.append(' <div class="col-xs-6"><label>Item Name ' + (i + 1) + '</label><input type="text" name="itemname_'+(i+1)+'" id="itemname_'+(i+1)+'" onkeyup="" value="" data-clear-btn="true" placeholder=""></div><div class="col-xs-6"><div class="row"><div class="col-xs-4"><label>Length</label><input type="number" id="length_'+(i+1)+'" name="length_'+(i+1)+'" onkeyup="" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div><div class="col-xs-4"><label>Width</label><input type="number" name="width_'+(i+1)+'" id="width_'+(i+1)+'" onkeyup="" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div><div class="col-xs-4"><label>Height</label><input type="number" id="height_'+(i+1)+'" name="height_'+(i+1)+'" value="" data-clear-btn="true" placeholder=""><label style="text-align:center">inches</label></div></div> </div></div>');
}
Now put all this div & Html inside a <form method='POST' action='<your_page name.php'> tag. & create a submit button. Inside your .php page you can get the value of Quantity from $_POST["name2"].Now useing for() insert the data into database.
I have this assignment in my class where we are to make a simple form with three required fields (out of five). I am having problems with getting my code to work.
This is via my professor...with what he wants
{
On submitting the form, the browser should check that :
Values for the required fields have been entered
Use regular expressions to check that the form of the entered input is proper for the email, telephone, and website fields. The forms to check for are:
Email: [alphanumeric string including . and _ ]# [alphanumeric string including . and _ ]. [alpha string]
Telephone: Either (ddd)ddd-dddd or ddd-ddd-dddd etc
Website: www.[alphanumeric string including . _ -].[com or net etc]
If any error is found, the form should not be submitted and appropriate error messages should be generated.
}
All validation must be "client side" i.e. on the browser using Javascript (not on any server and no Jquery or any programming other than Javascript and the required HTML). Use of any authoring tools is strictly and expressly forbidden.
This what I have now. Please help. Below is the code. What am I doing wrong?
<script language = "JavaScript">
<!--
function validateForm(){
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
-->
</script>
<body>
<form name="contact" action="" method="post" onSubmit = "return validateForm();">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
Try this out:- https://jsfiddle.net/vduwxjmv/
This can be done without JavaScript also using required attribute at each html control for which value is mandatory. And for clear you can use input type as reset.
HTML:-
<form name="contact" action="" method="post">
Name: <input type="textbox" name="Name" value="" required> <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value=""> <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" required> <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" required><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear" />
You can do a check by using the following JavaScript code
var result = $("#form")[0].checkValidity();
or you may change input button
<input type="submit" value="Submit Contact Details">
<!DOCTYPE html>
<html>
<body>
<form name="contact" method="post">
Name: <input type="text" class="form-control" name="Name" placeholder="Name" required="required" /> <font color = red>*Required </font><br>
Company: <input type="text" class="form-control" name="Company" placeholder="Company" /> <font color = red>Optional </font><br>
Email: <input type="email" class="form-control" name="Email" placeholder="Email" required="required" /> <font color = red>*Required </font><br>
Telephone: <input type="text" class="form-control" name="Telephone" placeholder="Telephone"/> <font color = red>Optional </font><br>
Website: <input type="text" class="form-control" name="Website" placeholder="Website" required="required" /><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details">
<input type="reset" value="Clear"><br>
</form>
</body>
</html>
change the type from button to submit.
on giving the type as reset ,it will clear the contents.
on giving required="required", that field will be considered as a mandatory one.
<html>
<head>
<script language = "JavaScript">
function validateForm(thisVar){ alert('method Called From: ');alert(thisVar.value);alert(thisVar.name);
//This is to check that required fields are filled
var x = document.contact.Name.value;
var y = document.contact.Email.value;
var z = document.contact.Website.value;
var p = document.contact.Phone.value;
if(x==null || x ==""){
alert('Name must be filled out');
return false;
}
if (y ==null || y == ""){
alert('Email must be filled out');
return false;
}
if (z == null || z == ""){
alert('Website must be filled out');
return false;
}
if(!isEmail()){
alert('This is not a correct Email format');
}
if (!isTelephone()){
var errorText = document.createTextNode(
"This is not a correct Phone number format");
}
if(!isWeb()){
errorText = document.createTextNode(
"This is not the correct Website format");
}
}
function isTelephone(){
//This checks that the phone number is in the required format
return document.contact.Phone.value.match(
/^\(\d\d\d-d\d\d\-\d\d\d\d$/);
}
function isEmail(){
//This is for checking email format
return document.contact.Email.value.match(
/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/);
}
function isWeb(){
return document.contact.Website.value.match(
/^([wW]{3}\.)?[a-zA-Z0-9\-.]{3,}\[a-zA-Z]{2,}(\.[a-zA-Z]{2,})?$/);
}
</script>
</head>
<body>
<form name="contactForm" action="" method="post" onSubmit = "return validateForm(this);">
Name: <input type="textbox" name="Name" value="" > <font color = red>*Required </font><br>
Company: <input type="textbox" name="Company" value="" > <font color = red>Optional </font><br>
Email: <input type="textbox" name="Email" value="" > <font color = red>*Required </font><br>
Telephone: <input type="textbox" name="Telephone" value="" > <font color = red>Optional </font><br>
Website: <input type="textbox" name="Website" value="" ><font color = red>*Required </font><br>
<input type="submit" value="Submit Contact Details" onclick="validateForm(this);">
<input type="reset" value="Clear"
ONCLICK="
alert('This will clear the form.');
Name.value=' '
Company.value=' '
Email.value=' '
Telephone.value=' '
Website.value=' '"><br>
</form>
</body>
</html>
You can validate it by two ways ---
use Submit type button
call validationForm on button click
Like --
<input type="submit" value="Submit Contact Details">
or
<input type="button" onclick="return validationForm();" value="Submit Contact Details">
you can check method call from to times 1st from onclick 2nd from onsubmit
Dont forget to appreciate (vote up).
I have a script that calculates the values in each and shows the calulated values. At the end it also calculates the already calculated values from all div's
Here is the html code:
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
<td>
<div>
<input name="r" class="rate" type="text" maxlength="255" size="5" value />
<input name="p" class="pack" type="text" maxlength="255" size="5" value />
<span class="amount"></span>
</div>
</td>
The problem is that I want to put all fields in a form and then submit them to a database.
However, all divs contain two input fields with name "r" and "p".
So, I am kind of stuck here because I cannot figure out how to make the names unique or how to have them passed to the DB using POST.
This is what the calculating script looks like:
<script type="text/javascript">//<![CDATA[
//any time the amount changes
$(document).ready(function() {
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack);
//update the row total
$row.find('.amount').text(total);
var total_amount = 0;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
});
$('.total_amount').text(total_amount);
});
});
//isNumeric function Stolen from:
//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
//]]>
</script>
HTML:
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
<hr>
<input type="text" name="r[]">
<input type="text" name="p[]">
PHP:
for ($i = 0; $i < count($_POST['p']); $i++) {
$rate = $_POST['r'][$i];
$pack = $_POST['p'][$i];
// do something with $rate and $pack
}
Since the browser submits all inputs (even if no value has been entered) and by specification it submits them in the order they are defined in the HTML code, you can rely that the elements in the two $_POST arrays will line up and the corresponding rate and pack will be received at the same index in the respective array.
<pre>
<script>
// here i want to check form validation
//if i use for loop txtbox2 is not exist in my form so i am getting Js error
//Don't write individual validation
//check element is exist or not if exist check for validation
//I need know how to check an element is exist or not
</script>
<form
<input type="text" id="txtbox1" name="txtbox1" />*
<input type="text" id="txtbox3" name="txtbox3" />*
<input type="text" id="txtbox4" name="txtbox4" />*
<input type="text" id="txtbox5" name="txtbox5" />*
<input type="text" id="txtbox15" name="txtbox15" />*
<input type="text" id="txtbox28" name="txtbox28" />*
</pre>
Apply a class to them:
<input type="text" id="txtbox1" name="txtbox1" class="txt" />
<input type="text" id="txtbox3" name="txtbox3" class="txt" />
<input type="text" id="txtbox4" name="txtbox4" class="txt" />
<input type="text" id="txtbox5" name="txtbox5" class="txt" />
<input type="text" id="txtbox15" name="txtbox15" class="txt" />
<input type="text" id="txtbox28" name="txtbox28" class="txt" />
and go about like this:
function validate(){
var elms = document.getElementsByTagName('input');
for (var i = 0; i < elms.length; i++){
if (elms[i].className === 'txt'){
if (elms[i].value === ''){
alert('Make sure to fill in all required fields');
// now focus it
elms[i].focus();
return false;
}
}
}
return true;
}
And then call the above function like this:
<form ............ onsubmit="return validate();">
Post your code.
Easiest way to validate is by using jquery validate plugin.(Why write your own code when somebody else has done the same?).
An example
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.1.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#feedbackform").validate();
});
</script>
<body>
<form id = "feedbackform" method = "POST" action = "">
<h3><span>Contact Us</span></h3>
<fieldset>
<legend>Contact form</legend>
<label for="id_name">Name *</label>
<input id="id_name" class="required" type="text" name="name" />
<label for="id_email">Email</label>
<input id="id_email" type="email" name="email" class="email"/>
<label for="id_comments">Message *</label>
<textarea id="id_comments" class="required" name="comments"></textarea>
<button type="submit">Send</button>
</fieldset>
</form>
The elements that you want to validate add class="required". I hope the example provided is self-explainatory
You can get a reference to the element and check if the reference is null or not:
for (var i=1; i<=100; i++) {
var elem = document.getElementById('txtbox' + i);
if (elem != null) {
...
}
}
Another approach is to look at the elements in the form, but then you need a way to access the form of course:
var elems = document.getElementById('IdOfTheForm').elements;
for (var i=0; i<elems.length; i++) {
var elem = elems[i];
if (elem.tagName == 'INPUT' && elem.type == 'text' && elem.id.length > 6 && elemt.id.substr(0,6) == 'txtbox') {
...
}
}