I have a form which is a bunch of elements. Plus there is a Button that creates Input-Elements dynamically:
$(document).ready(function() {
var counter = 0;
$("#addNewItem").on("click", function() {
counter++;
// The PHP handle to create the elements
$.get('showItem.php?zahl=' + counter ,function(data) {
// Add Items:
$('#newItems').after(data);
//Button zum erzeugen Enablen:
$( "#btn_createItem" ).removeAttr( "disabled" );
})
});
});
The PHP-handle contains this:
<div class="row" style="margin-bottom: 1em;" id="item<? echo $zahl; ?>" >
<div class="col-md-6">
<div class="form-group">
<label for="taskForUser"> Product:</label>
<select class="form-control select2" style="width: 100%;" name="prItem<? echo $zahl; ?>" id="prItem<? echo $zahl; ?>">
<option selected>Please choose...</option>
<? //foreach($stmtPL as $rowPL) {
while($rowPRL = $stmtPRL->fetch(PDO::FETCH_NUM)) {
// Get List from Database: ?>
<option><? echo $rowPRL[1] . " * " . $rowPRL[2] . " * " . $rowPRL[4]; ?></option>
<? } ?>
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="name">Count:</label>
<input type="text" class="form-control" id="anzahl<? echo $zahl; ?>" name="anzahl<? echo $zahl; ?>" value="1" maxlength="5">
<div class="help-block with-errors"></div>
</div>
</div> <!-- /col -->
<div class="col-md-3">
<div class="form-group">
<label for="name"> </label><br />
</i>
</div>
</div><!-- /col -->
When I click on the button to submit the form, the dynamically generated fields are not present. I tested it with a simple: "print_r($_POST);"
Only the "hardcoded" fields are listet in the array. What can it be?
Related
When I click on update, a page is only getting refreshed, values are not updated. I have 4 tables in database, namely -> stud,country_master_academic,master_state, master_city. In a console, values are not showing when I click on update button.
my update.php page
<div class="container" style="width:700px;height:1100px;margin-top:10%;box-shadow:4px 3px 3px 3px grey;margin-left:25%;background-color:#eaf2fa;padding:3%;">
<h4 style="font-weight:bold;"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
<div class="form-group">
<label for="photo"></label>
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' id="resultedPhoto" class="image" style="margin-left:75%;margin-top:2%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?><br/>
<input type="file" name="upphoto" id="upphoto" style="margin-left:70%;" required />
</div>
<form class="form-horizontal" name="form1" id="form1" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-lock"></span><b> Student No: </b></label>
<input type="text" class="form-control" name="upno" id="upno" disabled value="<?php echo $vrow['stud_no'];?>" required />
</div>
<div class="form-group">
<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="upname" id="upname" value="<?php echo $vrow['stud_name'];?>" required pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters"/>
</div>
<div class="form-group">
<label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label>
<input type="text" class="form-control" value="<?php echo $vrow['mobile']; ?>" name="upmob_no" required id="upmob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits"/>
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" required class="form-control" value="<?php echo $vrow['dob'];?>" name="updob" id="updob" />
</div>
<div class="form-group">
<label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label>
<textarea rows="4" cols="33" class="form-control" name="upadd" id="upadd" required><?php echo $vrow['address'];?></textarea>
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M"<?php echo ($vrow['gender']=='M')?'checked':' ' ?> required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F"<?php echo ($vrow['gender']=='F')?'checked':' ' ?> required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select required name="upcountry" id="upcountry" class="form-control">
<option value="">Select</option>
<?php
$country="SELECT * from country_master_academic";
$res= $conn->query($country);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["country_name"]==$vcountry or $vrow['country'] == $row["country_code"] )
{
echo '<option value='.$row["country_code"].' selected>'.$row["country_name"].'</option>';
}
else
{
echo '<option value='.$row["country_code"].'>'.$row["country_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label>
<select required name="upstate" id="upstate" class="form-control">
<option value="">Select</option>
<?php
$state="SELECT * from master_state";
$res= $conn->query($state);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["state_name"]==$vstate or $vrow['state'] == $row["state_code"] )
{
echo '<option value='.$row["state_code"].' selected>'.$row["state_name"].'</option>';
}
else
{
echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
}
}
}
?>
</select>
</div>
<div class="form-group">
<label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label>
<select required name="upcity" id="upcity" class="form-control">
<option value="">Select</option>
<?php
$city="SELECT * from master_city";
$res= $conn->query($city);
if($res->num_rows>0){
while($row=$res->fetch_assoc()){
if($row["city_name"]==$vcity or $vrow['city'] == $row["city_code"] )
{
echo '<option value='.$row["city_code"].' selected>'.$row["city_name"].'</option>';
}
else
{
echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
}
}
}
?>
</select>
</div>
<br/>
<div class="form-group">
<button type="submit" name="update" id="update" style="font-weight:bold;" class="btn btn-primary">Update</button>
</div>
</form>
</div>
upresult.php page
<?php
include("connection.php");
$no=trim($_POST['upno']);
$name=trim($_POST['upname']);
$mob=trim($_POST['upmob_no']);
$dob=trim($_POST['updob']);
$add=trim($_POST['upadd']);
$photo=trim($_FILES['upphoto']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['upcountry']);
$st=trim($_POST['upstate']);
$ct=trim($_POST['upcity']);
$qry="update stud set stud_name='".$name."',mobile='".$mob."',dob='".$dob."',address='".$add."',gender='".$gen."',country='".$cn."',state='".$st."',city='".$ct."' where stud_no='".$no."'";
$data=mysqli_query($conn,$qry);
if($data)
{
echo '<script language="javascript">';
echo 'alert("Updated Successfully")';
echo '</script>';
}
else {
echo '<script language="javascript">';
echo 'alert("Cannot update record")';
echo '</script>';
}
?>
jquery
$(document).ready(function(){
$("#form1").submit(function(event){
event.preventDefault();
var formData = new FormData(this);
$.ajax({
url:"upresult.php",
type:"POST",
data:{formData:formData},
async:true,
success:function(data) {
alert(data);
},
cache:false,
contentType:false,
processData:false
});
});
});
Thank you in advance.
Don't use the same name
data:{stud_no:stud_no}, //here change the name of vbl or value
data:{
formData:formData, //here change the name of vbl or value
stud_no:stud_no, //here change the name of vbl or value
}
If i select Local Sales from dorpdown and enter DEF, GHI values then the sum of DEF,GHI should be displayed in total value or if i select Inter State,Stock Transfers from dropdown then if we enter ABC value that value should be displayed in total value or else if we select JOB WORK,EXEMPTED SALES from dropdown then the total value should be displayed as zero. The total value which ever we are getting that should be inserted into database.
Controller:
function addinvoice()
{
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<br /><span class="error"> ','</span>');
$this->form_validation->set_rules('user','User');
$this->form_validation->set_rules('freight_charges');
$this->form_validation->set_rules('abc');
$this->form_validation->set_rules('def');
$this->form_validation->set_rules('ghi');
$this->form_validation->set_rules('total');
if($this->form_validation->run()== FALSE)
{
$data['mainpage']='invoice';
$data['mode']='add';
$this->load->view('templates/template',$data);
}
else
{
$this -> invoice_model -> insert();
$this->flash->success('<h2> Details added Successfully!</h2>');
redirect('invoice');
}
}
Model:
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
View:
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") ||(cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="cgst">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control" name="total" >
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
Whatever values i have selected from dropdown only those values to be inserted into database and the rest of the values should be inserted as zero in the database.
Actually i am not getting how to do these can anyone check this.Thanks in Advance.
you should check for posted values in your php code as:
$total = 0;
if($this->input->post('this')){
$total = $this->input->post('this');//value in total
}
if($this->input->post('this2')){
$total += $this->input->post('this2');//value in total
}
and at the end send $total value in db as well.
in short php if else tags you can set variables like;
$this = ($this->input->post('this'))?$this->input->post('this'):0;
$this2 = ($this->input->post('this2'))?$this->input->post('this2'):0;
and then at the end you can make total of them and save them to database. OR as suggested above in comments that make your columns as DEFAULT 0 in your table.
------- IN YOUR CASE------
function insert()
{
$data['total']=0;
$data['user'] = $this->input->post('user');
$data['ghi'] = ($this->input->post('ghi'))?$this->input->post('ghi'):0;
$data['abc'] = ($this->input->post('abc'))?$this->input->post('abc'):0;
$data['def'] = ($this->input->post('def'))?$this->input->post('def'):0;
$data['total'] = $data['ghi'] + $data['abc'] + $data['def'];
$data['freight_charges'] = $this->input->post('freight_charges');
$this->db->insert('invoice',$data);
}
---------------IN JavaScript------------
on your event handler you can sum these by their IDs.
var total = parseInt($('#ghi').val())+parseInt($('#def').val());
and then show this total in your total div
$('#yourTotalDiv').text(total);
Displaying total amount on enter the details.
<script>
function showRequiredOption(cval)
{
if((cval=='interstate') || (cval == "stocktransfers"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').show();
}
else if ((cval=='exemptedsales') || (cval=="zeroratedsales") || (cval=="jobwork"))
{
$('#ghi').hide();
$('#def').hide();
$('#abc').hide();
}
else
{
$('#abc').hide();
$('#ghi').show();
$('#def').show();
}
}
</script>
<script>
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
<div class="col-md-9 col-md-offset-2">
<div id="legend">
<legend class="">Profile Information</legend>
</div>
<form role="form" action="<?php echo site_url();?>invoice/addinvoice" method="post" class="form-horizontal" id="location" method="post" accept-charset="utf-8">
<div class="form-group">
<label class="control-label col-sm-2 " for="user">User</label>
<div class="col-sm-4 col-sm-offset-1">
<select id="user" name="user" onchange="showRequiredOption(this.value)">
<option value="employee">Local Sales</option>
<option value="interstate">Inter state</option>
<option value="stocktransfers">Stock transfers</option>
<option value="exemptedsales">Exempted Sales</option>
<option value="zeroratedcompany">Zero Rated Sales</option>
<option value="jobwork">Job Work</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2 " for="freight_charges">Freight Charges</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="freight_charges" name="freight_charges" value="<?php echo set_value('freight_charges');?>" />
</div>
</div>
<div class="form-group" id="abc" style="display:none;">
<label class="control-label col-sm-2 " for="abc">ABC</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="abc" name="abc" value="<?php echo set_value('abc');?>"/ >
</div>
</div>
<div class="form-group" id="def">
<label class="control-label col-sm-2 " for="def">DEF </label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="def" name="def" value="<?php echo set_value('def');?>"/ >
</div>
</div>
<div class="form-group" id="ghi">
<label class="control-label col-sm-2 " for="ghi">GHI</label>
<div class="col-sm-4 col-sm-offset-1">
<input type="text" class="form-control txt" id="ghi" name="ghi" value="<?php echo set_value('ghi');?>"/ >
</div>
</div>
<div class="form-group" id="summation">
<label class="control-label col-sm-2 " for="total">Total</label>
<div class="col-sm-4 col-sm-offset-1">
<span id="sum" class="form-control" type="text" name="total">0</span>
</div>
</div>
<button id="submit" type="submit" class="btn" name="submit">Submit</button>
</form>
</div>
i have form in which there are 2 dropdowns which are select batch from first dropdown and according to that batch, students will appear in second dropdown , Right now i am getting dropdown of batch but, not getting dropdown of students using batch
This is my view
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use common\models\TblBetch;
use common\models\TblCompany;
use common\models\TblCourse;
use common\models\TblStudent;
use common\models\TblStudentExpence;
use kartik\widgets\DepDrop;
use yii\db\Query;?><link rel="shortcut icon" href="<?php echo Yii::$app->params['global_theme_path'];?>images/logo1.png" type="image/png"><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><script src="http://iamrohit.in/lab/js/location.js"></script><div class="pageheader"><h2><i class="fa fa-money"></i>Expense</h2>
<div class="breadcrumb-wrapper">
<span class="label">You are here:</span>
<ol class="breadcrumb">
<li>Westline Shipping</li>
<li class="active">Add Expense</li>
</ol></div></div><div class="contentpanel">
<?php
$session = Yii::$app->session;
if($session->hasFlash('success'))
{
echo $session->getFlash('success');
}
if($session->hasFlash('error'))
{
echo $session->getFlash('error');
}
$site = '';
?>
<div class="row">
<div class="col-md-12">
<div class="container-fluid-50">
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-btns">
−
</div>
<h4 class="panel-title">Add Expense</h4>
</div>
<form class="panel-body" action="dashboard" method="post">
<div class="row">
<?php $form = ActiveForm::begin(); ?>
<div class="col-sm-9">
<div class="form-group">
<label class="control-label"></label>
<?php
//$batch = new TblBetch();
//$quer = new Query();
//$getid = [''];
//$getid = $quer->select('b_sn')->from($batch->tableName())->all();
//echo $form->field($model,'se_b_id')->dropDownList($getid,['id'=>'se_b_id']);
?>
<?=
$form->field($model,'se_s_id')->dropDownList(
ArrayHelper::map(TblBetch::find()->all(),'b_id','b_sn'),
[
'prompt'=>'Select Batch',
'name'=>'s_b_id',
'id'=>'s_b_id',
'onchange'=>'$.post("student?id="+$(this).val(),function(data){$("select#tblstudentexpence-se_s_id").html(data);});'
]);
?>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-9">
<div class="form-group">
<label class="control-label"></label>
<?=
$form->field($model,'se_s_id')->dropDownList(
ArrayHelper::map(TblStudent::find()->all(),'s_id','s_fname'),
[
'prompt'=>'Select Student',
'name'=>'se_s_id',
'id'=>'se_s_id'
]);
?>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-9">
<div class="form-group">
<label class="control-label">Payment Mode</label>
<div class="radio"><label><input type="radio" name="num" value="cash" required> Cash </label></div>
<div class="radio"><label><input type="radio" name="num" value="check" required> Check </label></div>
<div class="radio"><label><input type="radio" name="num" value="dd" required> DD </label></div>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-9">
<div class="form-group">
<label class="control-label">Check / DD No</label>
<input type="text" name="num" id="num" class="form-control" placeholder="Enter your check or DD number" required/>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-9">
<div class="form-group">
<label class="control-label">Amount</label>
<input type="text" name="lastname" class="form-control" placeholder="Enter your Amount" required/>
</div>
</div><!-- col-sm-6 -->
<div class="col-sm-9">
<div class="form-group"> <br><br>
<input type="submit" value="Submit" class="btn btn-primary">
<input type="reset" value="Cancel" class="btn btn-primary">
</div></div>
</div><!-- row -->
</form>
</div><!-- panel-body -->
</div>
</div>
</div> <div class="col-md-12">
</div>
</div></div></div> <script>
$(function() {
window.invalidate_input = function() {
if ($('input[name=num]:checked').val() == "check" || $('input[name=num]:checked').val() == "dd")
$('#num').removeAttr('disabled');
else
$('#num').attr('disabled', 'disabled');
};
$("input[name=num]").change(invalidate_input);
invalidate_input();
});
This is my controller (sitecontroller.php)
public function actionStudent($id)
{
//p($id);
$student = new TblStudent();
$queryobj = new Query();
$data = [];
$data = $queryobj->select('*')->from($student->tableName())->where(['s_betch'=>$id])->count();
//p($data);
$queryobj1 = new Query();
$getid = [];
$getid = $queryobj->select('*')->from($student->tableName())->where(['s_betch'=>$id])->all();
//p($getid);
if($data > 0)
{
foreach($getid as $gid)
{
echo "<option value='".$gid->s_id."'>".$gid->s_fname."</option>";
}
}
else
{
echo "<option> - </option>";
}
}
I am getting this response in firebug after ajax call
You can implement dependent drop-down much simpler in yii 2 because there is a widget available which you can use.
use kartik widget here -> kartik dependent drop down
When the user picks either phone or email I want the form to then generate a box to enter the details of which they selected. How do I do this? Thanks.
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" value="<?= (isset($fields['phone']) ? $fields['phone'] : '' )?>"/>
</div>
<div class="field-container full clearfix">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" value="<?= (isset($fields['email']) ? $fields['email'] : '' )?>"/>
</div>
Here's a snippet that shows you how to do that with javascript:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
Please note that I added a Id to the select element and to the input elements.
EDIT | USAGE
Create a file, call it script.js or whatever you like and put this in it:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
Save the file to a folder on your server that is accesible. For example /public/js/script.js
In your html, add
<script src="/public/js/script.js"></script> <!-- or however your path is -->
to the very end of your file, directly before the closing </body> tag So that it looks like this
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
<script src="/public/js/script.js"></script> <!-- here is the script included -->
</body>
That's it.
This worked for me:
Add an id to your select: select name="fields[contact]" id="contact"
Set phone and email fields to hidden by using a class or inline style: div class="field-container full clearfix hide-this" id="phone-container"
--or just set style: display:none;
Javascript:
$('#contact').change(function(){
if(this.selectedOptions[0].text == 'phone') {
$('#phone-container').show().focus();
}else{$('#phone-container').hide();}
});
This should do the trick... let me know?
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
.field-hide{
display: none;
}
</style>
<script>
function valChange(ele){
var fields = document.getElementById("container").children;
for(var i=0; i < fields.length; i++){
fields[i].classList.add("field-hide");
}
switch(ele.value){
case "phone":
document.getElementById("phone").classList.remove("field-hide");
break;
case "email":
document.getElementById("email").classList.remove("field-hide");
break;
}
}
</script>
</head>
<body>
<div class="field-container full clearfix">
<label class="required">What is your preferred method of contact?</label>
<select type="text" name="fields[contact]" onchange="valChange(this)">
<option value="blank" selected disabled>Choose</option>
<option value="phone">Quoted</option>
<option value="email">Labour Only</option>
</select>
</div>
<div id="container">
<div class="field-container full clearfix field-hide" id="phone">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" placeholder="enter phone number">
</div>
<div class="field-container full clearfix field-hide" id="email">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" placeholder="enter email">
</div>
</div>
</body>
</html>
im having a problem populating form fields.
When choosing value from doropdown fields in first line input fields are populated , i have 5 fields that are populated from database. To get those values im using:
".select_ttl" is a dropdown name attribute.
$(".select_ttl").change(function(event){
var kit=$(".select_ttl").val();
$.getJSON('/getanimation.php?kit=' + kit, null,
function(data)
{
$("#kit").val(data.kit);
$("#animation").val(data.animation);
$("#prix").val(data.prix);
});
});
the php file is:
<?php
require_once("inc/init.php");
require_once("inc/session.php");
require_once('inc/sql.php');
require_once("inc/config.ui.php");
header('Content-Type: application/json');
$title = $_GET["kit"]; // we received this from the json call
$Mysql = new Mysql();
$array_action = $Mysql->TabResSQL("SELECT * FROM liste_animation inner join kit ON liste_animation.ID_LISTE_ANIMATION=kit.ID_LISTE_ANIMATION where kit.CODE='".$title."' ");
foreach($array_action as $key){
$data = array(
'kit' => $key->CODE,
'animation' => $key->NOM_ANIMATION,
'prix' => $key->PRIX_ANIMATEUR,
);
}
echo (json_encode($data));
?>
Using this code i get only values for one row, in form there is an option to add a new line of input fields. So mu problem is how to do the same for multiple lines? Thanks in advance.
This is form example:
<div class="form-inline col-xs-2">
<select class="select_ttl form-control" name="kit" id="kit">
<option class='select_ttl' value="" selected="selected" disabled="disabled">Kit</option>
<?php
$Mysql = new Mysql();
$ArraySelect = $Mysql->TabResSQL('SELECT distinct KIT from kit_voyage');
foreach($ArraySelect as $key){
echo "<option value=".$key->KIT.">".$key->KIT."</option>";
?>
<?php } ?>
</select> <!-- end .select_ttl -->
</div>
<!-- Text input-->
<div class="form-group col-xs-3">
<input id="animation" name="animation" type="text" placeholder="nom animation" class="input_fn form-control" required="" value=''>
</div>
<!-- Text input-->
<div class="form-group col-xs-2">
<input id="prix" name="prix" type="text" placeholder="PU_HT" class="input_ln form-control" value=''>
</div>
<!-- Text input-->
<div class="form-group col-xs-2">
<input value="1" id="quantity" name="quantity" type="text" placeholder="qtité" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="tva" name="tva" type="text" placeholder="TVA" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="rem" name="rem" type="text" placeholder="REM" class="input_email form-control">
</div>
<div class="form-group col-xs-2">
<input id="totaltt" name="totaltt" type="text" placeholder="Total TT" class="input_email form-control">
</div>
Use
$(".select_ttl").change(function(event){
var kit=$(this).val();
});
& insted of echo (json_encode($data)); use echo json_encode($data); remove outter ()