checkbox unchecked var value 0 checkbox checked var value 1 - javascript

In the last part of the code, i have more than one checkbox. I have an input textbox named livello that must store its value to mysql database.
The checkboxes are not fixed in number but can vary if the admin add some to the data base. So based on this code
<!--Add Utente Modal -->
<div id="aggiungi" class="modal fade" role="dialog">
<div class="modal-dialog modal-lg">
<!-- Modal content-->
<div class="modal-content">
<form method="post" class="form-horizontal" role="form">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Aggiungi UTENTE</h4>
</div>
<div class="modal-body">
<input type="hidden" name="edit_id" value="<?php echo $id; ?>">
<div class="form-group">
<label class="control-label col-sm-2" for="username">Username:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="username" name="username" required autofocus> </div>
<label class="control-label col-sm-2" for="password">Password:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="password" name="password" required> </div>
</div>
<br>
<br>
<div class="form-group">
<label class="control-label col-sm-2" for="nome">Nome:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="nome" name="nome" required> </div>
<label class="control-label col-sm-2" for="cognome">Cognome:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="cognome" name="cognome" required> </div>
</div>
<br>
<br>
<div class="form-group">
<label class="control-label col-sm-2" for="sesso">Sesso:</label>
<div class="col-sm-4">
<select id="sesso" name="sesso" >
<option value=" "> </option>
<option value="m">Maschio</option>
<option value="f">Femmina</option>
</select>
</div>
<label class="control-label col-sm-2" for="posizione">Posizione:</label>
<div class="col-sm-4">
<select id="posizione" name="posizione" >
<option value=" "> </option>
<option value="Staff">Staff</option>
<option value="Operatore">Operatore</option>
</select>
</div>
</div>
<br>
<br>
<div class='form-group'>
<?php
$sql = "SELECT id, posizione, nome
FROM user_livelli";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$posizione = $row['posizione'];
$nome = $row['nome'];
?>
<input type='checkbox' name='nome_posiz[]'/> <?php echo $nome; ?>
<div id='show' class='col-sm-4'></div>
<?php
}
}
?>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="livello">Livello:</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="livello" name="livello"> </div>
</div>
<script>
let oShow=document.getElementById('show');
let oInput=document.getElementById('livello');
let oCol=Array.from( document.querySelectorAll('.form-group > input[type="checkbox"]') );
let livello=new Array( oCol.length ).fill( '0', 0, oCol.length );
oInput.value=livello.join('');
oCol.forEach( (chk,index)=>{
chk.addEventListener('change',function(e){
livello.splice(index,1,this.checked ? '1':'0' );
oShow.innerHTML=livello.join('');
oInput.value=livello.join('');
});
})
</script>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" name="add_utente"><span class="glyphicon glyphicon-plus"></span> Aggiungi</button>
<button type="button" class="btn btn-warning" data-dismiss="modal"><span class="glyphicon glyphicon-remove-circle"></span> Annulla</button>
</div>
</form>
</div>
</div>
</div>
When i add a new UTENTE (user), i would like to have Livello at 000000 because the 6 checkboxes are unchecked. When i check one or more checkboxes, Livello immediately change value to for example 100011.
PS in edit
The script works very well for add a new user where the admin check the necessary checkbox.
How can the script be changed for edit user data.
In this case the checkbox are checked or not (and this part already works), livello have a value like 0010011100
I would like livello value printed inside livello input box and that this value could also change if i check or uncheck checkboxes

ID attributes MUST be unique within the DOM. So, rather than assigning each with the same ID set that as the element's name - and use the array style syntax.
I'm not a user of jQuery but I'm sure it is feasible to do this in jQuery with probably only minor modifications to the following. The below uses document.querySelectorAll to find a reference to ALL the checkboxes and assigns a simple listener to each.
let oShow=document.getElementById('show');
let oInput=document.getElementById('livello');
let oCol=Array.from( document.querySelectorAll('.form-group > input[type="checkbox"]') );
let livello=new Array( oCol.length ).fill( '0', 0, oCol.length );
oCol.forEach( (chk,index)=>{
chk.addEventListener('change',function(e){
livello.splice(index,1,this.checked ? '1':'0' );
oShow.innerHTML=livello.join('');
oInput.value=livello.join('');
});
})
<div class='form-group'>
<input type='checkbox' name='check[]' value='1' />aaa
<input type='checkbox' name='check[]' value='1' />bbb
<input type='checkbox' name='check[]' value='1' />ccc
<input type='checkbox' name='check[]' value='1' />ddd
<input type='checkbox' name='check[]' value='1' />eee
<input type='checkbox' name='check[]' value='1' />fff
<div id='show' class='col-sm-4'></div>
</div>
<!-- as per comment, unclear where in the DOM this snippet lives however -->
<div class='form-group'>
<label class='control-label col-sm-2' for='livello'>Livello:</label>
<div class='col-sm-4'>
<input type='text' class='form-control' id='livello' name='livello'>
</div>
</div>

You could use something like
$livello = "";
if(isset($_POST['checkbox1']){
$livello .= "1";
} else {
$livello .= "0";
}
if(isset($_POST['checkbox2']){
$livello .= "1";
} else {
$livello .= "0";
}

Thanks to the jquery code provided by Swati, I understand that to see the string (all zeros that is all unchecked) inside livello as soon as the code start, just add oInput.value=livello.join(''); after string declaration in the javascript. Thanks so much

Related

Not able to fetch value for Update Data from database using jQuery Ajax Bootstrap Model - json data

My main problem is that my modal is showing but alert is showing [object Object]. I have four tables like stud,country_master_academic, master_city and master_state.When i click on edit, modal appears but data fetched from database is not showing in it.
jQuery in home.php page
$(document).ready(function(){
$(document).on('click', '.edit_data', function(event){
var stud_no = $(this).attr("id");
$.ajax({
url:"update.php",
method:"POST",
data:{stud_no:stud_no},
dataType:"json",
success:function(data){
console.log(data);
$('#name').val(data.name);
$('#mob_no').val(data.mob_no);
$('#dob').val(data.dob);
$('#add').val(data.add);
$('#photo').val(data.photo);
$('#gender').val(data.gender);
$('#country').val(data.country);
$('#state').val(data.state);
$('#city').val(data.city);
$('#stud_no').val(data.stud_no);
$('#update_data_modal').modal('show');
},
});
});
});
Modal for update in home.php page
<div class="container">
<div class="modal fade" id="update_data_modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-heading" style="margin-top:30px;text-align:center">
<button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
<h4 class="modal-title"><span class="glyphicon glyphicon-edit"></span>Update Student</h4>
</div>
<div class="modal-body">
<?php
$img = "images/".trim($vrow["photo"]);
echo '<img src='.$img.' class="image" style="margin-left:75%;margin-top:5%;width:120px;height:120px;border:2px solid #bbbbbb;border-radius:10px;">';
?>
<br/>
<input type="file" name="photo" style="margin-left:70%;">
<div class="form-group">
<form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label>
<input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
</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" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
</div>
<div class="form-group">
<label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label>
<input type="date" class="form-control" name="dob" id="dob" required />
</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="add" id="add" required></textarea>
</div>
<div class="form-group">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="gender" value="M" required="required">Male
<input type="radio" name="gender" id="gender" value="F" required="required">Female
</div>
<div class="form-group">
<label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label>
<select name="country" id="country" class="form-control">
<option value="0">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 name="state" id="state" class="form-control">
<option value="0">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 name="city" id="city" class="form-control">
<option value="0">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>
<div class="form-group">
<input type="hidden" name="stud_no" id="stud_no" />
<button type="submit" name="update" id="update" class="btn btn-info">Update</button>
</div>
</form>
</div>
<div class="modal-footer">
<button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
update.php page but still i am trying to fetch data, so only wrote code for selecting records from database.
My edit button which is kept in a loop
echo '<td><button name="edit" style="font-weight:bold;" type="submit" id='.$row["stud_no"].' class="btn btn-warning edit_data" data-target="#update_data_modal" data-toggle="modal"><span class="glyphicon glyphicon-edit"></span> Edit</button></td>';
Change in your html as below.
<div class="form-group">
<label for="gen"><b> Gender: </b></label>
<input type="radio" name="gender" id="genderMale" value="M" required="required">Male
<input type="radio" name="gender" id="genderFemale" value="F" required="required">Female
</div>
Add this code in your ajax success.
if(data[6] == 'M')
{
$("#genderMale").prop("checked", true);
} else if(data[6] == 'F') {
$("#genderFemale").prop("checked", true);
}
For image file you can use as below in your html
<div class="form-group">
<img id="resultedPhoto">
<label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label>
<input type="file" name="photo" id="photo" required />
</div>
Add below code in ajax success
$("#resultedPhoto").attr("src","/path-to-your-folder/" + data[5]);
As shown in the snapshot, your object has numeric indexes hence data.photo will not return anything as there is no index photo in your object.
You can access image name by using data[5].
Similarly you can get any index value.
Like for name instead of using data.name you need to use data[1]
So your code would be something like this:
$('#name').val(data[1]);
$('#mob_no').val(data[2]);
$('#dob').val(data[3]);
$('#add').val(data[4]);
$('#photo').val(data[5]);
Also you have given same ids for labels and inputs:
<label for="name" id="name">
You need to remove id from all labels:
<label for="name">
Now when i click on edit Modal is not opening and database value is getting empty
another 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:false,
success:function(data) {
alert(data);
location.reload();
},
cache:false,
contentType:false,
processData:false
});
});
});
upresult.php
<?php
include("connection.php");
if(!empty($_POST)){
$no=$_POST['stud_no'];
$name=trim($_POST['name']);
$mob=trim($_POST['mob_no']);
$dob=trim($_POST['dob']);
$add=trim($_POST['add']);
$photo=trim($_FILES['photo']['name']);
$gen=trim($_POST['gender']);
$cn=trim($_POST['country']);
$st=trim($_POST['state']);
$ct=trim($_POST['city']);
$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>';
}
if(!empty($_FILES['photo']['name'])){
$qry1= "update stud set photo='$photo' where stud_no='$no'";
$data1=mysqli_query($conn,$qry1);
if($data1){
$target_dir="images/";
$target_file=$target_dir.basename($_FILES["photo"]["name"]);
$imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
echo '<script language="javascript">';
echo 'alert("Image upload successfully")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Cannot Upload")';
echo '</script>';
}
}
}
}

how can i validate the checkbox?

<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>
i have added my html code also..
$('.save').on('click', function() {
var chk = $(this).parent().parent().parent().parent().parent().find('input [name="ch"]').attr('class');
if ($("." + chk).attr('checked', false)) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
i have tried with this code and getting the alert "please check the checkbox" for both conditions if and else.
i just want to validate the checkbox whether it is checked or not .. if checked means it should display the relevant message if not checked also should display the message.
There are two things i am noticing:
Instead use .closest() against .parent() multiple times.
Do not set the attribute in the if condition, instead of .attr() use .prop().
You can change to this
var chk = $(this).closest('form').find('input[name="ch"]');// use form if you have one.
if (!$(chk).prop('checked')) {
$('.save').on('click', function() {
var chk = $(this).closest('form').find('input[name="ch"]');
if (!$(chk).prop('checked')) {
alert("please check the checkbox");
} else {
alert("you have checked the checkbox");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form target="_self" id="immunization_info_form" class="form-validation save_immune25 update_immune25" role="form" method="POST" enctype="multipart/form-data">
<div class="form-group row" style="margin-top:10px;height:50px;">
<div class="checkbox checkbox-styled col-md-offset-1 col-md-4">
<label style="font-size:15px;"><input type="checkbox" id="checkbox25" name="ch" class="checkbx" value="25">
<span>Hepatitis A vaccine</span></label>
</div>
<div class="form-group col-md-4">
<!-- Date input -->
<input class="form-control edit25" id="date25" name="date" placeholder="Enter Date" value="<?php echo $date[25]; ?>" type="text" required>
</div>
</div>
<div class="row" style="padding:15px;">
<div class="col-md-3 col-md-offset-1">
<div class="form-group">
<h3 style="color:orange;">Clinic Name</h3><br>
<input name="clinic_name" id="clinic" class="form-control edit25" type="text" value="<?php echo $clinic_name[25]; ?>" required>
<label for="clinic_name"></label>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<h3 style="color:orange;">Name of the Health practitioner</h3><br>
<input name="hp_name" id="hp" class="form-control edit25" type="text" value="<?php echo $practitioner[25]; ?>" required>
<label for="hp_name"></label>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<h3 style="color:orange;">Lot no. of Vaccine</h3><br>
<input name="lotno" id="lot" class="form-control edit25" type="text" value="<?php echo $lotno[25]; ?>" required>
<label for="lotno"></label>
</div>
</div>
<div class="row col-md-offset-1">
<div class="col-md-6 text-right">
<input type="button" name="submit" value="SAVE" class="save btn btn-lg btn-primary ink-reaction justify" id="save_immune25">
</div>
</div>
</div>
</form>

Bootstrap Codeigniter 3 Form Click on edit

<legend data-target="#basic_information" data-toggle="collapse">Basic Information</legend>
<fieldset id="basic_information" class="collapse">
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Screen Name</label>
<div class="col-sm-10">
<input type="text" name="screen_name" placeholder="Screen Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">First Name</label>
<div class="col-sm-10">
<input type="text" name="first_name" placeholder="First Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Middle Name</label>
<div class="col-sm-10">
<input type="text" name="middle_name" placeholder="Middle Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Last Name</label>
<div class="col-sm-10">
<input type="text" name="last_name" placeholder="Last Name" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Birthdate</label>
<div class="col-sm-2">
<select name="birthdate-month" id="birthdate-month">
<option value="">month</option>
<?php foreach($month as $month_number => $month_name) { ?>
<option value="<?php echo $month_number; ?>" <?php echo set_select('birthdate-month', $month_number); ?>><?php echo $month_name; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2">
<select name="birthdate-day" id="birthdate-day">
<option value="">day</option>
<?php for($i=1; $i<=31; $i++){ ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-day', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2">
<select name="birthdate-year" id="birthdate-year">
<option value="">year</option>
<?php for($i=(date("Y")-10); $i>=1930; $i--) { ?>
<option value="<?php echo $i; ?>" <?php echo set_select('birthdate-month', $i); ?>><?php echo $i; ?></option>
<?php } ?>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Gender</label>
<div class="col-sm-10">
<select name="gender" id="gender">
<option value=""></option>
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Occupation</label>
<div class="col-sm-10">
<input type="text" name="job" placeholder="Occupation" class="form-control">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<label class="col-sm-2 control-label" for="textinput">Address</label>
<div class="col-sm-10">
<input type="text" name="address" placeholder="Address" class="form-control">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<div class="pull-right">
<button type="submit" class="btn btn-default">Cancel</button>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</fieldset>
I've added the collapse feature of Bootstrap on the above code. Whenever i click on the BASIC INFORMATION text, it would show the details, as it is hidden by default.
What i want to do is the same as the collapse feature.
I want the above code to be read only, i'm pretty sure i can do that with html.
What i want to do is to make it so that i only have to click on the input and it will be available for me to edit one by one or clicking a button and everything will be editable.
solely using bootstrap, like with what i did with collapse.
Is it possible? or do i need to use jquery.
You can do this using bootstrap and with jquery code like this :-
<script>
$(document).ready(function() {
$('#basic_information').on('hidden.bs.collapse', function () {
$('#basic_information .form-control').attr('readonly', true);/*It will add the readonly attribute in all input on collapse*/
});
$('#basic_information').on('shown.bs.collapse', function () {
$('#basic_information .form-control').attr('readonly', false);/*It will remove as soon as your basic information get expanded*/
});
});
</script>
Put a <span> adjacent to each form control with a common class like currentvalue, each one holding the text of the current value for that field. Add a single button at the top that uses JS/jQuery to toggle visibility between those spans, and the inputs (including the submit button). Then you have one file but its functionality is switchable. If you're using ajax to submit the form, then you'll also have to update the <span>s' contents on successful submit.

Populating input forms with json data on another page

I am trying to populate a form on a button click, so for example a user clicks a button and then it populates the inputs with the button id's information from a json page. I have added what I need in the jquery belo
Here's my javascript, which doesn't have an onclick, which I need it to, but need it t
jquery script
(i need an on click perform this action)
$.get('<?php echo Config::get('URL'); ?>dashboard/employment_json/(i need this to be the value of the button)',function(d){
$("input[name='json_name']").val(d.name);
$("input[name='json_country']").val(d.country);
$("input[name='json_start']").val(d.date_start);
$("input[name='json_end']").val(d.date_end);
$("input[name='json_duration']").val(d.duration);
$("input[name='json_description']").val(d.description);
},'json');
Here's sample data of the inputs:
<div class="col-md-6">
<div class="form-group">
<label for="field-1" class="control-label">
<?php echo System::translate("Employment name"); ?>
</label>
<input type="text" disabled name="json_name" class="form-control" id="field-1">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Employment Country"); ?>
</label>
<input type="text" disabled name="json_country" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Start Date"); ?>
</label>
<input type="text" disabled name="json_start" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("End date"); ?>
</label>
<input type="text" disabled name="json_end" class="form-control" id="field-2">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="field-2" class="control-label">
<?php echo System::translate("Employment Duration"); ?>
</label>
<input type="text" disabled name="json_duration" class="form-control" id="field-2">
</div>
</div>
And lastly, but not least,
Json sample
{"employment":{"name":"test","duration":"12","date_end":"2015-07-01","date_start":"2014-07-07","country":"America","description":"This is just a test description of no important value. Have a nice day."}}
Maybe something like this ?
$('.myButtonClass').on('click', function(e){
var url = '<?php echo Config::get('URL'); ?>dashboard/employment_json/' + e.target.id;
$.get(url,function(d){
$("input[name='json_name']").val(d.name);
$("input[name='json_country']").val(d.country);
$("input[name='json_start']").val(d.date_start);
$("input[name='json_end']").val(d.date_end);
$("input[name='json_duration']").val(d.duration);
$("input[name='json_description']").val(d.description);
},'json');
});
Obviously you have to change
$('.myButtonClass')
here you have to use the class or id of the button you want to bind the action to.

How to display multiple form fields of the same type using jquery and fetch their values in php

I have a table named order_master which stores the order_id column. I also have another table order_details having the columns order_id (FK), vendor, purchase_date, delivery_date, and person_name which stores the details of the order corresponding to the order_id from the order_master table.
I want to display a form wherein a button add new item will be displayed. On clicking this button each time, a new block of fields (like vendor, purchase_date, delivery_date, person_name) will be displayed. The user can click the above button and enter as many items as he wants on the same order_id. And when he submits the form, the items on this form must be entered in the database.
How to achieve this?
actually i am using codeigniter framework (MVC architecture). Here i am attaching the view and js file.
<?php echo form_open(); ?>
<div id="emp"></div>
<div class="box">
<div>
</div>
<div class="col-lg-12" style="padding-top: 2%;margin-bottom: 3%" id="form-box">
<div class="col-lg-6 form-group">
<select name="item[]" id="item" class="form-control">
<option value="">--Select Item--</option>
<?php foreach ($items as $item) { ?>
<option value="<?php echo $item["id"]; ?>"><?php echo $item["name"]; ?></option>
<?php } ?>
</select>
</div>
<div class="col-lg-6 form-group">
<select name="vendor[]" id="vendor" class="form-control">
<option value="">--Select Vendor--</option>
<?php foreach ($vendors as $vendor) { ?>
<option value="<?php echo $vendor["id"]; ?>"><?php echo $vendor["name"]; ?></option>
<?php } ?>
</select>
</div>
<div class="col-lg-4 form-group">
<input type="text" name="po_date[]" id="po_date" class="form-control date" placeholder="Purchase Date">
</div>
<div class="col-lg-4 form-group">
<input type="text" name="quantity[]" id="quantity" class="form-control number" placeholder="Item Quantity Individual">
</div>
<div class="col-lg-4 form-group">
<input type="text" name="unit_price[]" id="unit_price" class="form-control number" placeholder="Unit Price" style="text-align: left;">
</div>
<div class="col-lg-4 form-group">
</div>
<div class="col-lg-12 col-md-12 col-sm-12 form-group">
<textarea name="description[]" id="description" class="form-control"></textarea>
</div>
<div class="col-lg-12 col-md-12 col-sm-12" style="height: 3px;background-color: grey"></div>
<div class="col-lg-12 col-md-12 col-sm-12 form-group" id="messageBox">
</div>
</div>
</div>
<a id="add_item" class="col-lg-12" href="">Add new item</a>
<div class="col-lg-12 col-md-12 col-sm-12 text-center form-group">
<input type="button" value="Add Purchase Order" id="addpurchaseOrderBtn" class="btn btn-primary">
</div>
<?php echo form_close(); ?>
**JS File**
$("#main_content").css('minHeight', '400px');
$(document).ready(function() {
$('#add_item').click(function() {
var def_ht = $("#main_content").height() + 300;
$("#main_content").css('minHeight', def_ht);
$("#form-box").clone(true).appendTo("#form-box");
return false;
});
$("#addpurchaseOrderBtn").click(function() {
focusId = null;
var isvalid = false;
if(validateDropDown('item')){
isvalid = true;
}
if(validateDropDown('vendor')){
isvalid = true;
}
if(validatDate('po_date')){
isvalid = true;
}
if(validateTextbox('quantity')){
isvalid = true;
}
if(validateTextbox('unit_price')){
isvalid = true;
}
if(validateTextbox('description')){
isvalid = true;
}
if(isvalid){
focusId.focus();
$("#messageBox").html('<div class="alert alert-danger">There are some error in your submission. Please try again.</div>');
}else{
$("#addPurchaseFrm").submit();
}
});
});
This code works but i am unable to validate all the elements(items) in the form.
You can try the following structure-
<form name="addItem" method="post" action="addItem.php" class="insertItem">
<div class="itemAdd">
<input type="text" name="vendor" >
<input type="text" name="purchase_date" >
<input type="text" name="delivery_date" >
<input type="text" name="person_name" >
</div>
<input type="submit" name="submit" value="Add Item" class="btn btn-primary additem">
$("document").ready(function(){
$(".additem").click(function(){
$(".insertItem").append($(".itemAdd").html);
});
});
Then on addItem.php, you can execute the insert query to insert this data into your database

Categories

Resources