show dynamic checkbox when its parentcheckbox clicked (ajax,jquery) - php

i have two kinds of checkbox -> parent_checkbox and child_checkbox
when parent_checkbox checked then it should show its child_chekbox.
when i check last parent_checkbox first-> then i get its child_chekbox. and then check other parent_checkbox i get its parent_checkbox respectively.
but the problem is when i check first parent_checkbox for the first time ->i get its respective child_chekbox. but again i click other(2,3,4) parent_checkbox i still get
child_chekbox of first parent_checkbox and it for the rest of parent_checkbox getting same result.
HTML Part
<h5><p> parent</p></h5>
<?php foreach ($parentcheckbox as $parentcheckbox) { ?>
<input type='checkbox' name='name2[]' value="<?php echo $parentcheckbox["id"]; ?>" class="parentcheckbox" class="form-control" >
<?php echo $parentcheckbox['name']; ?>
<?php } ?>
<h5>child<h5>
<div class="hidden show_childcheckbox" style="margin-top: 14px;">
</div>
</div>
and the script
<script>
$('.parentcheckbox').click(function () {
var array = $("input[name2]").val();
var childcheckbox_html = "";
$.ajax({
type: "POST",
dataType: "json",
url: "http://localhost/...",
data: $('#tab4 :input').serializeArray(),
success: function (response) {
$(response.childcheckbox).each(function (i, v) {
childcheckbox_html += "<input type='checkbox' name='name3[]' value='" + v.id + "' class='childcheckbox' class='form-control' >";
childcheckbox_html += "label ='" + v.name + "' "
});
$('.show_childcheckbox').append(childcheckbox_html)
$('.childcheckbox_html').show()
console.log("44")
}
});
});
<script>

Related

Adding values to tables with JQuery. Table created with PHP loop

I am trying to make a form which let you see boarding times per day.
The table is created with PHP. Having a row for every day of the week, except Saturday and Sunday:
<?php
for ($i = 1; $i < 8; $i++){
$d=strtotime("+".$i." Day");
if (date("l", $d) !== "Saturday" && date("l", $d) !== "Sunday" ){
$daydate = $dayOfWeek[date("l",$d)] . date(" d ", $d) . $month[date("F",$d)];
echo "<tr>";
echo "<td>". $daydate . "</td>";
echo "<td></td>";
echo "<td></td>";
echo "<td></td>";
echo "</tr>";
echo '<tr class="BoardingTimeMorning">';
echo '<td style="padding-left: 30px">
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input> <div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
<td>
<input class="form-check-input" type="radio" name="'.$dayOfWeek[date("l",$d)].'-to" class="BoardingMorning" value=""></input><div class="time">0:00</div>
</td>
</tr>';
}
}
?>
When someone selects their destination, the corresponding times need to show in the table above. Selection is done with AJAX request and returns the times in an array. No more than 4 boarding times are possible.
I am trying to get it working with JQuery, but nothing happens.
JQuery:
$('#boardingplace').change(function() {
$.ajax({
type: 'POST',
url: 'reservePage.php',
dataType: 'JSON',
data: {
'station': this.value
},
success: function(response){
var len = response.length;
console.log("length: "+len);
$( ".BoardingTimeMorning" ).each(function() {
for (var j=0; j<4; j++){
//visibitly off
var tdContent = $(this).find('.BoardingMorning'+j);
console.log (tdContent);
tdContent.css("display", "none");
tdContent.next().html("");
//reset value
tdContent.attr('value', "");
if(j - len <= 0){
//show content according to amount of times
tdContent.css('display', "block");
tdContent.attr('value', response[j].slice(0,5));
tdContent.next().html(response[j].slice(0,5));
}
}
});
}
});
});
What is the best way to get it to work?
EDIT:
Turns out I use 2 class definition on the input element. The bootstrap class and another for selecting it. I put them together and all works..
Thanks for all you help people! Really love this community!
There is an easy solution:
you can create a response.php file like this:
url used for example:
response.php?station=162
<?php
//response.php
$station=$_GET['station'];
$data_from_database=// your sql Request...
?>
<html>
<div class="datas">
<?php
foreach ($data_from_database as $data) {
echo "<span>".$data['time']."</span>";echo "<br>";
echo "<span>".$data['name']."</span>";echo "<br>";
}
?>
</html>
in your javascript you can load data from response.php file like this:
<script type="text/javascript">
$('#boardingplace').change(function() {
var station= this.value;
$.ajax({
type: 'GET',
url: 'response.php?station'+station,
success: function(response){
$(".BoardingTimeMorning").html(response);
}
});
});
</script>
and data will be loaded in div with class="BoardingTimeMorning"
I hope this could help you.

Autocomplete existing textbox when selection clicked

I have a form where there are select option and a textbox. All I want to do is when I select specific option, it will pass the id to query the same table to get another column's value based on ID of selected option and then display the value in a textbox before insert/update the table.
This code will works if both field in my form using select field. So in my opinion, maybe my script for storing value in input text field is totally wrong. Please correct me if I do wrong.
My form code :
<form name="inserform" method="POST">
<label>Existing Customer Name : </label>
<select name="existCustName" id="existCustName">
<option value="">None</option>
<?php
$custName = $conn->query("SELECT * FROM customers");
while ($row = $custName->fetch_assoc())
{
?><option id="<?php echo $row['customerID']; ?>" value="<?php echo $row['customerID']; ?>"><?php echo $row['customerName']; ?></option><?php
}
?>
</select>br>
<label>Current Bottle Balance : </label>
<input type="int" id="currentBal" name="currentBal"></input><br>
<input name="insert" type="submit" value="INSERT"></input>
</form>
My script code :
<script type="text/javascript">
$(document).on("change", 'select#existCustName', function(e) {
var existCustID = $(this).children(":selected").attr("id");
$.ajax({
type: "POST",
data: {existCustID: existCustID},
url: 'existingcustomerlist.php',
dataType: 'json',
success: function(json) {
var $el = $("input#currentBal");
$el.empty();
$.each(json, function(k, v) {
$el.append("'input[value='" + v.currentBal + "']").val();
});
}
});
});
</script>
existingcustomerlist.php code:
<?php
include 'config/config.php';
$result = $conn->query("SELECT * FROM customers WHERE customerID = '" .$_POST['existCustID'] . "'");
$results = [];
while ($row = $result->fetch_assoc()) {
$results[] = $row;
}
header('Content-Type: application/json');
echo json_encode($results);
?>
I need help to solve this.
I assume you are trying to show the results as input text element next to the #currentBal element. Try by changing the script tag inside the success callback as shown below.
$.each(json, function (k, v) {
$el.after("<input type='text' class="currentBalTemp" value='" + v.currentBal + "' />");
});
Make sure to remove the .currentBalTemp elements on change event of select otherwise duplication will be shown. Add the below code on change event.
$('.currentBalTemp').remove();

AJAX Submit Button Got Disabled

i want to create a dynamic search using php and ajax, and then choose the results that will be inserted in another tabke in database by using checkboxes..
here's the code to query the search in table
<?php
//include('../koneksi/koneksi.php');
mysql_connect('localhost','root',''); //ini untuk koneksi databasenya
mysql_select_db('aam'); // nama tabel
$key=$_GET['q'];
$query = mysql_query("select * from dokter where nama LIKE '%$key%'");
echo "
<table border='1'>
<tr>
<th>Kode Dokter</th>
<th>Nama</th>
<th>Spesialis</th>
<th>Alamat</th>
<th>Kota</th>
<th>Pilih</th>
</tr>
";
while($row = mysql_fetch_array($query))
{
//$array[] = $row['title'];
echo "<tr>";
echo "<th>" . $row['id_dokter'] . "</th>";
echo "<th>" . $row['nama'] . "</th>";
echo "<th>" . $row['spesialis'] . "</th>";
echo "<th>" . $row['alamat'] . "</th>";
echo "<th>" . $row['kota'] . "</th>";
echo"<th> <input name='chkbox[]' type='checkbox' value='". $row['id_dokter'] ."'> </th>";
echo "</tr>";
}
echo "</table>";
?>
the code above will generate a table in my page. after the results populated, i use this code to submit my choices to the database
function kirimJadwal(){
$(document).ready(function(e) {
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}
and this is the form that i use to put the results
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
</div>
<label> Atur Jadwal</label>
<a id="dt1" href="#" <span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
the problem is, when the results populated, the submit button will do nothing everytime i click it? is there any of my functions here that freezes the button???
Try to replace your javascript with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
});
return false;
});
});
And html with this:
$(document).ready(function() {
$("#formulir").on('submit', function(){
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
data: $("#formulir").serialize(),
success: function(data){
alert("123");
}
}).done(function(){
alert();
});
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form method='post' action='Planning-kirim.php' name="formulir" id="formulir">
<label> Atur Jadwal</label>
<a id="dt1" href="#" ><span class="glyphicon glyphicon-calendar" aria-hidden="true"></span></a>
<input type="date" name="date">
<input type="submit" id="kirim" value="Submit" />
</form>
Click on the submit button and look to the firebug. You'll find sent requests there. So the javascript works.
Document need to load before function.
$(document).ready(function(e) {
kirimJadwal();
function kirimJadwal(){
var checkboxdokter = new Array();
$("form#formulir").on('submit', function(e){
e.preventDefault();
/*$("input:checked").each(function() {
checkboxdokter.push($(this).val());
});*/
$.ajax({
type: "POST",
url: "Planning-kirim.php",
dataType:"html",
//data: {checkboxdokter:checkboxdokter},
data: $("form#formulir").serialize(),
success: function(data){
alert(checkboxdokter);
}
});
});
});
}

Dynamically add equal select form fields with data taken from php

I have a form with select fields dynamically generated and with the options taken from php (same for all the selects). But I need that every <select>...</select> must be shown in a different line. This can be done having every <select>...</select> inside a <div>...</div>.
This is the code that I have, it´s working but the select fields are not within a div:
<script type="text/javascript">
//<![CDATA[
$(function(){
var counter = 1;
$("#addButton").click(function () {
if(counter>10){
alert("Only 10 textboxes allow");
return false;
}
var select = $('<select>').attr({id:'select'+counter,name:'select'+counter});
$.ajax({
url: 'selects.php',
dataType: "html",
success: function(data) {
select.html(data);
}
});
select.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#select" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
//]]>
</script>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='text' id='textbox1' >
</div>
<div id="TextBoxDiv2">
<label>Textbox #2 : </label><input type='text' id='textbox2' >
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>
And this is the html code generated by select.php:
<option value="1">Uno</option>
<option value="2">Dos</option>
<option value="3">Tres</option>
<option value="4">Cuatro</option>
Use the wrap() function. :
Put this code just before the counter++;. :
$("#TextBoxesGroup > select").wrap ( function () {
return '<div id="wrap_' + this.id + '"></div>';
} );
See it in action at jsFiddle.

Return data from PHP back to a javascript file?

I have a comments section on my websites that uses jQuery to animate comments in without reloading the page, as well as deleting comments.
Right now, I have it so when you write a comment, it sends it to a external JS, then to a php file where it processes. If it was successful, it will append the comment into the comment section. My delete action: jQuery deletes my the comment ID in the mysql database.
So my issue is I want to add a delete button via jQuery and somehow call back to the javascript file and tell it the id so the delete button knows the ID to put in the form so the delete file knows what to delete?
Here's my add_comment script:
$(function() {
$(".commentbutton").click(function() {
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_addcomment.php",
data: $("#commentform").serialize(),
success: function() {
var theComment = $("#commentsss").val();
var theUserId = $("#user_id_two").val();
var thePhotoId = $("#photo_id").val();
var theProfilePicture = $("#user_profile_picture").val();
var theUsername = $("#user_username").val();
// Get new HTML data
var html = "<div class='comment_odd'><img src='" + theProfilePicture + "' class='comment_thumbnail'/><div class='comment_username'>" + theUsername + "</div><div class='comment_text'>" + theComment + "</div></div>";
// Append, then fade in
$(html).hide().appendTo(thecommentsdisplay).fadeIn(500);
}
});
return false;
});
});
Thanks in advance!Coulton
EDIT 1:
Here's my comments form (just to clarify):
user_id_two (the user's ID)
commentsss (comments field)
photo_id (the id of the photo being commented on)
user_profile_picture (profile to display on the user's profile picture in the banner)
user_username (username of the user commenting)
Here's also my delete button form:
<form method='post' action='' name='deleteform' id='deleteform'>
<input type='hidden' name='userid' value='<?php echo "$userid_session"; ?>' />
<input type='hidden' name='userpass' value='<?php echo "$password_session"; ?>' />
<input type='hidden' name='pictureid' id='pictureid' value='<?php echo "$picture_id"; ?>' />
<input type='hidden' name='profilepictureid' id='profilepictureid' value='<?php echo "$user_profile_picture_id"; ?>' />
</form>
And lastly my DELETE COMMENT jQuery:
$(function() {
$(".commentdeletebutton").click(function() {
var className = $(this).attr('class');
var theID = className.replace(/delete_button commentdeletebutton delete_(\d+)/, "$1");
commentDone = "#comment_" + theID;
formDone = "#commentdeleteform_" + theID;
$.ajax({
type: "POST",
url: "http://myflashpics.com/process_deletecomment.php",
data: $(formDone).serialize(),
success: function() {
$(commentDone).hide();
}
});
return false;
});
});
If you add an link for deleting, you can insert the complete url for deleting in the href, i.e. http://myflashpics.com/process_removecomment.php?id=xx.
So, you can bind a click event to that link and get the right url using $(this).attr('href') and doing the delete using ajax.
Edited for a more complete sample:
<? [[Loop your recordset]] { ?>
<div class="comment">
Delete
<div class="comment">
[[Comment content...]]
</div>
</div>
<? } ?>
<script>
$(function() {
$(".commentdeletebutton").click(function() {
$this = $(this);
$.ajax({
url: $this.attr('href'),
success: function(data) {
$this.parent().slideUp('fast', function() {
$this.parent().remove();
});
}
});
return false;
});
});
</script>

Categories