Generate <div> section dynamically with a button in PHP/Javascript? - javascript

Hi guys I have a code that I want is inside a div and that I would like to generate 1 by 1 when the button 'Add Section' is clicked. Here's my code
surveycontent.php with javascript code
<div id="sform" class="tab-pane fade">
<br>
<div class="col-md-12">
<div class="col-md-10" id="sections">
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">Section 1</div>
<div class="panel-body">
<b>Number of Questions: </b>
<span id="ctr_num"> <input id="q_num" class="form-control" style="width:50px;" name="q_num" size="2" placeholder="#"/></span>
<br>
<b>Select Category</b>
<select class="form-control" style="width: 150px;" id="categorydd" name="catdd" onChange="change_category()">
<option>-Please Select One-</option>
<?php
$query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID IS NULL");
while($row=mysqli_fetch_array($query)) {
?>
<option value="<?php echo $row["category_id"]; ?>"><?php echo $row["categoryname"]; ?></option>
<?php
}
?>
</select><br>
<b>Select Subcategory</b>
<div id="subcategory">
<select class="form-control" style="width: 150px;">
<option>-Please Select One-</option>
</select><br/>
</div>
<p hidden>Select Questions</p>
</br>
<div id="question">
</div> <br/>
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class="col-md-2">
<input type="submit" name="addsection" class="btn btn-default" value="Add Section" id="addsection" />
</div>
</div>
<script>
function change_category()
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?category="+document.getElementById("categorydd").value,false);
xmlhttp.send(null);
document.getElementById("subcategory").innerHTML=xmlhttp.responseText;
if(document.getElementById("categorydd").value=="Select")
{
document.getElementById("question").innerHTML="<select><option>Select</option></select>";
}
//alert(document.getElementById("categorydd").value);
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php?main=1&subcategory="+document.getElementById("categorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
function load_questions(){
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","ajax.php??main=1&subcategory="+document.getElementById("subcategorydd").value +"&cnt="+document.getElementById("q_num").value,false);
xmlhttp.send(null);
document.getElementById("question").innerHTML=xmlhttp.responseText;
}
javascript code for add section button
<script>
$(document).ready(function(){
var ctr = 0;
$("#addsection").click(function(){
var section = document.getElementById("sections").innerHTML;
$("#sections").append(section);
ctr++;
});
});
</script>
I assume this is wrong, because this code i have atm will just make it bug like if I generate 1 section, and choose a data on the dropdowns for the added section, it will do the same thing to the first section, like it copies what you move for one section. This is a creation survey system and this is the part of adding sections.
The code behind those category, subcategory, question dropdowns.
ajax.php
if($category!=""){
$query=mysqli_query($con, "SELECT category_id, categoryname FROM category WHERE ParentCategoryID =$category ");
echo "<select id='subcategorydd' class='form-control' style='width:150px;' name='subcatdd' onchange='load_questions()' >";
echo "<option selected>"; echo "Select"; echo "</option>";
while($row=mysqli_fetch_array($query))
{
echo "<option value='$row[category_id]'>"; echo $row["categoryname"]; echo "</option>";
}
echo "</select>";
}
// for loading ques under Category already
if($question !="" && $cnt!="" && $addQues!="yes" && $main == 1){
$i = 0;
for( $i = 1; $i <= $cnt; $i++ ){
$query=mysqli_query($con, "SELECT question.* FROM question LEFT JOIN category AS subcategory on subcategory.category_id = question.question_subcat WHERE question.question_category = $question AND (question.question_subcat IS NULL OR subcategory.category_id IS NOT NULL)");
echo "<form>
<b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query)){
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
echo "<div id='insertQuesHere".$i."'></div>";
echo "<a href='#add_question' onclick='return addQues_Cat();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}
// for loading ques under SUBCATEGORY
if($question !="" && $cnt!="" && $addQues!="yes" && $main != 1){
$i = 0;
for ($i = 1; $i <= $cnt; $i++)
{
$query=mysqli_query($con, "SELECT * FROM question WHERE question_subcat = $question ");
echo "
<form>
<b id='labelquestion_dropdown{$i}'>Question #{$i}</b>
<select id='question_dropdown{$i}' class='form-control' onchange=\"showUser( this.value, 'txtHint{$i}' )\" style='width: 300px;' name='question_dropdowns{$i}'>
<option selected>Select";
while($row=mysqli_fetch_array($query))
{
echo "<option value='{$row['question_id']}'>" . $row["questiontitle"];
}
echo "
</select>
</form>
<div id='txtHint{$i}'><b>Person info will be listed here...</b></div>
<br />";
}
echo "<div id='insertQuesHere".$i."'></div> ";
echo "<a href='#add_question' onclick='return addQues();'>Add Question</a> | ";
echo "<a href='#del_question' onclick='return delQues();'>Delete Question</a>";
}

I think the HTML markup should perhaps be more like this. If you indent your code correctly as you go you will often find it is much easier to find issues.
There are several sites on the interwebs that could help with the code indentation - for example and you can validate your pages using other services, such as the W3C Markup Validator
<div id='sform' class='tab-pane fade'>
<br />
<div class='col-md-12'>
<div class='col-md-10' id='sections'>
<div class='panel-group'>
<div class='panel panel-default'>
<div class='panel-heading'>Section 1</div>
<div class='panel-body'>
<b>Number of Questions: </b>
<span id='ctr_num'> <input id='q_num' class='form-control' style='width:50px;' name='q_num' size='2' placeholder='#'/></span>
<br />
<b>Select Category</b>
<select class='form-control' style='width: 150px;' id='categorydd' name='catdd' onChange='change_category()'>
<option>-Please Select One-</option>
<?php
$query=mysqli_query($con, 'SELECT `category_id`, `categoryname` FROM `category` WHERE `ParentCategoryID` IS NULL');
while( $row=mysqli_fetch_array($query) ) {
?>
<option value='<?php echo $row['category_id']; ?>'><?php echo $row['categoryname']; ?></option>
<?php
}
?>
</select>
<br />
<b>Select Subcategory</b>
<div id='subcategory'>
<select class='form-control' style='width: 150px;'>
<option>-Please Select One-</option>
</select>
<br />
</div>
<p hidden>Select Questions</p>
<br />
<div id='question'>
</div>
<br />
</div>
</div>
</div>
</div>
</div>
</div>
<hr>
<div class='col-md-2'>
<input type='submit' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
</div>
I don't know if this will help or not or indeed whether I have understood the problem correctly ( that of effectively cloning the contents of the section when the button is clicked? )
The following clones the entire section ( there are no ID attributes to worry about but there will be duplicate names ) so a little more work would be invloved to make the new clone unique in the DOM and to change the section title / section number.
Copy and run the code - as posted - and see if it does more or less what you were trying to do. The ajax code does not perform all the tasks in the original code - like setting the contents of the question
<?php
session_start();
/* to emulate the ajax request that is sent by change_category() */
if( $_SERVER['REQUEST_METHOD']=='POST' ){
if( !empty( $_POST['action'] ) && $_POST['action']=='changecat' ){
ob_clean();
for( $i=0; $i < 10; $i++ )echo "<option value='$i'>Choice - $i";
exit();
}
}
?>
<!doctype html>
<html>
<head>
<title>Cloning a section of the HTML page</title>
<style></style>
<script>
function ajax(m,u,p,c,o){
/*
m=Method,
u=Url,
p=Params,
c=Callback,
o=Options
*/
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 ){
/*
The callback takes 3 arguments
------------------------------
r=xhr.response
o=options ( as supplied to ajax function )
h=response headers
*/
c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
}
};
var params=[];
for( var n in p )params.push(n+'='+p[n]);
switch( m.toLowerCase() ){
case 'post': p=params.join('&'); break;
case 'get': u+='?'+params.join('&'); p=null; break;
}
xhr.open( m.toUpperCase(), u, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function change_category(evt){
var el=evt.target;
console.log('ajax function to get contents of dropdown - '+el.value+' & append returned data to subcategory?' );
var method='post';
var url=location.href;
var params={
action:'changecat'
};
var callback=function(r,o,h){
var col=el.parentNode.querySelectorAll('select.subcategory');
if( col.length==1 )col[0].innerHTML=r;
col=el.parentNode.querySelectorAll('div.question');
if( col.length==1 )col[0].innerHTML='Some question - relating to Select:'+el.tagName+', Name:'+el.name+', Option:'+el.value+', chose from the database, goes here I believe?';
}.bind( this );
var options={};
ajax.call( this, method, url, params, callback, options );
}
function clone_section(e){
e.preventDefault();
var parent=document.getElementById('clone-parent');
var col=parent.querySelectorAll('div.clone-section');
var section=col[ col.length-1 ];
var clone=section.cloneNode( true );
/* change the heading */
var heading=clone.querySelectorAll('div.panel-heading')[0];
var regex=/(\d+)/gi;
var matches=heading.innerHTML.match( regex );
var i=parseInt( matches[0] );
heading.innerHTML=heading.innerHTML.replace( i, i + 1 );
/* make changes to the various cloned elements */
var q_num=clone.querySelectorAll('input[name^="q_num_"]')[0];
var matches=q_num.name.match( regex );
var i=parseInt( matches[0] );
q_num.name = q_num.name.replace(i,i+1);
q_num.value='';
var cat=clone.querySelectorAll('select[name^="catdd_"]')[0];
var matches=cat.name.match( regex );
var i=parseInt( matches[0] );
cat.name=cat.name.replace(i,i+1);
cat.value='';
var subcat=clone.querySelectorAll('select[name^="subcategory_"]')[0];
var matches=subcat.name.match( regex );
var i=parseInt( matches[0] );
subcat.name=subcat.name.replace(i,i+1);
subcat.value='';
parent.appendChild( clone );
}
function bindEvents(){
var bttn=document.getElementById('addsection');
bttn.addEventListener( 'click', clone_section.bind( bttn ), false );
}
document.addEventListener('DOMContentLoaded',bindEvents,false);
</script>
</head>
<body>
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && !isset( $_POST['action'] ) ){
print_r( $_POST );
}
?>
<form name='geronimo' method='post'>
<!--// markup from question //-->
<div id='sform' class='tab-pane fade'>
<br />
<div class='col-md-12' id='clone-parent'>
<!-- it is the following portion of HTML that is to be replicated? -->
<div class='col-md-10 clone-section'><!-- removed ID, added new class -->
<div class='panel-group'>
<div class='panel panel-default'>
<div class='panel-heading'>Section 1</div><!-- this needs to change progammatically or via CSS-->
<div class='panel-body'>
<b>Number of Questions: </b>
<span class='ctr_num'> <input class='form-control' style='width:50px;' name='q_num_1' size='2' placeholder='#' /></span>
<br />
<b>Select Category</b>
<select class='form-control' style='width: 150px;' name='catdd_1' onchange='change_category( event )'>
<!-- PHP removed for example - replaced with dummy data -->
<option>-Please Select One-
<option value='a'>A
<option value='b'>B
<option value='c'>C
<option value='d'>D
<option value='e'>E
</select>
<br />
<b>Select Subcategory</b>
<div class='subcategory'>
<select name='subcategory_1' class='form-control subcategory' style='width: 150px;'>
<option>-Please Select One-</option>
</select>
<br />
</div>
<p>Select Questions</p>
<br />
<div class='question'></div><!-- assigned as a class rather than id - can be targeted using querySelectorAll etc -->
<br />
</div>
</div>
</div>
</div>
<!-- end replicated code -->
</div>
</div>
<hr>
<div class='col-md-2'><!-- add new section button - uses javascript:onclick -->
<input type='button' name='addsection' class='btn btn-default' value='Add Section' id='addsection' />
</div>
<input type='submit' /><!-- to actually submit the form -->
<!--// end markup from question //-->
</form>
</body>
</html>

Related

adding multiple inputfield using javascript in php not working

i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />

How to auto populate textbox when dropdown is selected

i'm trying to auto populate text-box when drop-down is selected. I've tried some code but nothing happen i already included the jquery file in my code.
I have a database table called services and the column are service_id, service_name, service_price.
Here's My view
<div class="form-group-inner">
<div class="row">
<div class="col-lg-1">
<label class="login2 pull-right pull-right-pro">Service</label>
</div>
<div class="col-lg-4">
<div class="form-select-list">
<select class="form-control custom-select-value" id="service_name" name="service_name">
<option>Select Service</option>
<?php foreach ($service as $services): ?>
<option value="<?php echo $services->service_id; ?>"><?php echo $services->service_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
</div>
<div class="form-group-inner">
<div class="row">
<div class="col-lg-1">
<label class="login2 pull-right pull-right-pro">Price</label>
</div>
<div class="col-lg-4">
<input type="text" id="price" name="price" class="form-control" />
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#service_name').on('change', function() {
var service_id=$("service_name").val();
$.post("<?php echo base_url();?>/records/getprice/" + service_id,
function(data){
$('#price').val(data.service_price);
});
}
<script>
Controller
function add_form($patient_id){
$data['service']=$this->services_model->get_all_services();
$data['value'] = $this->patient_model->get_selected_patient($patient_id);
$this->load->view('header/header');
$this->load->view('Records/add_records',$data);
$this->load->view('footer/footer');
}
function getprice($service_id){
$laiza=$this->db->get_where("services",array("service_id"=>$service_id));
foreach ($laiza->result() as $row){
$arr = array('service_price' => $row->service_price);
header('Content-Type: application/json');
echo json_encode($arr);
}
}
I expect that when i select a data from dropdown the textbox will populate the price base on the selected item dropdown
ID selector # missing when your getting the Service_Name value
Change the same to
var service_id=$("#service_name").val();
or
var service_id= this.value;
<script>
$(document).ready(function () {
$('#service_name').on('change', function() {
var service_id=$("#service_name").val();
$.post("<?php echo base_url();?>/records/getprice/" + service_id,
function(data){
$('#price').val(data.service_price);
});
}
<script>

How to get value of select-option tag from database

i made this form of adding data in the database. I have exam table that contains exam_code(PK), exam_title and subject_code(FK). Here is the design
<div style="width:800px;height:auto;margin-left:auto;margin-right:auto;margin-top:50px;">
<form action="" method="POST" class="form-horizontal" role="form">
<div class="form-group">
<div class="col-xs-6 col-sm-3 ">
<input name="code" type="text" class="form-control" id="excode" placeholder="Enter Exam Code">
</div>
<div class="col-xs-6 col-sm-3 ">
<input name="title" type="text" class="form-control" id="extitle" placeholder="Enter Exam Title">
</div>
<div class="col-xs-6 col-sm-3 ">
<select name="subjcode" class="form-control">
<option selected="selected">Choose subject</option>
<option disabled="disabled">---------------------------------</option>
<?php
include('db.php');
$subj = $connect->query("SELECT subject_code FROM subject");
while($row1 = mysqli_fetch_array($subj)){
echo "<option value = $row1[subject_code]>$row1[subject_code]</option>";
}
?>
</select>
</div>
<div class="col-xs-6 col-sm-3 ">
<input type="submit" name="add" class="btn btn-default" value="Add" />
</div>
</div>
</form>
</div>
Is my query here correct? I can't think of anyway to insert the data. Here..
<?php
include('db.php');
if(isset($_POST['add'])){
$excode = $_POST['code'];
$extitle = $_POST['title'];
$subcode = $_POST['subjcode'];
$examinsert = $connect->query("INSERT INTO exam (exam_code, exam_title, subject_code) VALUES ('$excode', '$extitle', '$subcode')");
if(!$examinsert){
die("<script>
alert('Error encountered, Reloading page');
window.location.href='teacher.php';
</script>");
}else{
die("<script>
alert('Your exam title has been added. You will see your titles in the Examination title section below!');
window.location.href='teacher.php';
</script>");
}
}
?>
Change Your PHP CODE
FROM This
<?php
include('db.php');
$subj = $connect->query("SELECT subject_code FROM subject");
while($row1 = mysqli_fetch_array($subj)){
echo "<option value = $row1[subject_code]>$row1[subject_code]</option>";
}
?>
To This
<?php
include('db.php');
$subj = $connect->query("SELECT subject_code FROM subject");
while($row1 = mysqli_fetch_array($subj)){
echo "<option value = ".$row1[subject_code].">".$row1[subject_code]."</option>";
}
?>
store value in Variable and than put it.
<?php
include('db.php');
$subj = $connect->query("SELECT subject_code FROM subject");
while($row1 = mysqli_fetch_array($subj)){
$subjectCode = $row1[subject_code];
echo "<option value = $subjectCode>$subjectCode</option>";
}
?>
Its Works.
I fixed it by adding a query that disables the foreign keys.
$set = $connect->query('SET foreign_key_checks = 0');
/*insert query*/
$set1 = $connect->query('SET foreign_key_checks = 1');

How to show check box text if it is not next to check box using jQuery

I am trying to achieve checked value text should visible like shown in the image:
Without refresh or any click can anyone help me out?
This is my php dynamic from :
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input multiple="multiple" type="checkbox" id="<?php echo $tiffen['tiffen_image']; ?>" name="tifeen" hidden>
<label for="<?php echo $tiffen['tiffen_image'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3 class="FoodName"><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
This is my script to show the text:
<script type="text/javascript" language="JavaScript">
$( document ).ready(function() {
var FoodMenu = $('input[type=checkbox]:checked').map(function(){
return $(this).next('.FoodName').text();
}).get().join("<br>");
$("#selectedfood").html(FoodMenu);
});
</script>
Out put id: <a id="selectedfood"></a></li>
You could try to get all checked options’ text on checkbox change event and append selected values to “selectedfood”. The following sample code is for your reference.
<script>
$(function () {
$(".foodmenuform [type='checkbox']").change(function () {
var FoodMenu = "";
var ischecked = $(".foodmenuform [type='checkbox']:checked").each(function () {
FoodMenu += $(this).siblings(".FoodName").text() + "<br/>";
})
$("#selectedfood").html(FoodMenu);
})
})
</script>
Its easier thank i thought:
var checkedFood = $('input[type=checkbox]:checked').map(function(){
//console.log($('input[type=checkbox]:checked').serialize());
return $(this).val();
}).get().join("<br>");
$("#selectedfood").html(checkedFood);
Form:
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $tiffen['id_tiffen'];?>" class="Foodmenu" value="<?php echo $tiffen['tiffen_name'];?>" name="tifeen[]" hidden>
<label for="<?php echo $tiffen['id_tiffen'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>

hide or remove checkbox which is on colorbox popup after selected in dropdown

I have dropdown list and checkbox popup(colorbox popup) list in which data comes from complaint.csv file.
complaint.csv File
1,complaint type 1
2,complaint type 2
3,complaint type 3
etc...
I want to hide/remove checkbox from the popup checkbox list when item is selected from dropdown. e.g. if 'complaint type 1' is selected from dropdown then 'complaint type 1' from checkbox list should be removed/hide.
Here is some code.
PHP code:
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Chief Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<select name="Language.PrimarySpoken" ng-hide="showAddAnswer"
ng-model="question.response.value"
ng-options="a.text as a.getText() for a in question.answers.items"
id="Language.PrimarySpoken" ng-value="a.text" class="input-wide"
ng-class="{error:hasError()}" onchange="changeEventHandler(event);">
<option class="hidden" disabled="disabled" value=""></option>
<?php
$file_handle = fopen("../complaint.csv", "r");
while (!feof($file_handle)) {
$lines_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
foreach ( $lines_of_text as $line_of_text):
?>
<option value="<?php print $line_of_text[1]; ?>">
<?php print $line_of_text[1]; ?></option>
<?php endforeach; ?>
</select>
<br/> <br/>
<label class="question-name" ng-class="{error:hasError()}">
<span class="ng-binding" ng-hide="question.nameHiddenOnMobile">
Additional Complaint
</span>
<span class="icon-required" ng-show="question.required"></span>
</label>
<div class="form-row added ng-binding" ng-bind-html="question.getText()" id="text" ></div>
<div class="form-row addlink ng-binding"
ng-bind-html="question.getText()">
<em><a class='inline' href="#inline_content">+ Add/Edit</a></em>
</div>
<div style='display:none'>
<div id='inline_content' style='padding:25px; background:#fff; font-size: 17px;'>
<form action="" id="popup_form">
<?php
// Setup ---------------------------------------------------------------
define('numcols',4); // set the number of columns here
$csv = array_map('str_getcsv', file('../complaint.csv'));
$numcsv = count($csv);
$linespercol = floor($numcsv / numcols);
$remainder = ($numcsv % numcols);
// Setup ---------------------------------------------------------------
// The n-column table --------------------------------------------------
echo '<div class="table">'.PHP_EOL;
echo ' <div class="column">'.PHP_EOL;
$lines = 0;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
foreach($csv as $item) {
$lines++;
if ($lines>$lpc) {
echo ' </div>' . PHP_EOL . '<div class="column">'.PHP_EOL;
$lines = 1;
$lpc = $linespercol;
if ($remainder>0) { $lpc++; $remainder--; }
}
echo ' <label class="checkbox" for="checkbox'.$item[0].'" style="font-size:20px;">
<input type="checkbox" name="complaint" value="'.$item[1].'" id="checkbox'.$item[0].'" data-toggle="checkbox">'
.$item[1].
'</label><br />';
}
echo ' </div>'.PHP_EOL;
echo '</div>'.PHP_EOL;
// The n-column table --------------------------------------------------
?>
<br/>
<input type="submit" name="submit" id="update"
class="button button-orange"
style="width: 90px; margin-top: 450px; margin-left:-1062px;"
value="Update">
<input type="submit" name="cancel" id="cancel"
class="button button-orange"
style="width: 90px; background-color:#36606e;"
value="Cancel">
</form>
</div>
</div>
JS code
<script type="text/javascript">
function changeEventHandler(event) {
$('.inline').colorbox({onLoad: function() {
// alert('You have ' + event.target.value + ' complaint.');
$('input[type=checkbox][value=' + event.target.value + ']').parent().hide();
}});
}
</script>
In above JS code I am getting alert of selected value from dropdown (the line of alert which is commented) but the checkbox item having that selected value is not removing somehow.(for this line $('input[type=checkbox][value=' + event.target.value + ']').parent().hide(); , I am getting just loading icon on popup)
Can anyone please tell me how should I do that?
Note: I am reading data from complaint.csv file for both dropdown list and checkbox popup list in php as shown in above code.
make following changes and check
$('input[type=checkbox][value="' + event.target.value+ '"]').parent().hide();

Categories