How to add new content when a checkbox is clicked? - php

I made a design with ajax, jquery, mysql and checkbox in php. It is like that :
There is box with checkboxes. And there is another box which is empty. When you checked a checkbox in first box, information about that checkbox will be displayed in empty box. I did it and work good.But when you clicked another checkbox, information about first you clicked dissappear and only current selection is displayed. That is to say, I want to add new selection on old ones. Also how can I delete information in second box when I unchecked a checkbox. Thank you.
Here is HTML code :
<div id="first_box">
<label class='checkbox'>
<input type='checkbox' id=1>
First checkbox
</label>
<label class='checkbox'>
<input type='checkbox' id=2>
Second checkbox
</label>
<label class='checkbox'>
<input type='checkbox' id=3>
Third checkbox
</label>
</div>
<div id="second_box"> </div>
Here is jquery code :
$(document).ready(function() {
$("#first_box input:checkbox").change(function() {
if($(this).is(":checked")) {
$.post("/here/is/url", { strID:$(this).attr("id"), strState:"1" },
function(data) {
$("#second_box").html(data);
});
} else {
$.ajax({
url: 'here/is/url/',
type: 'POST',
data: { strID:$(this).attr("id"), strState:"0" }
});
}
});
});
Here is the php code for ajax request :
$strID = $_POST['strID'];
$strState = $_POST['strState'];
if ($strState) { //if checkbox is clicked
//I fetch data about checkbox which is clicked
$infos = $this->info_model->get_info_from_checkbox_id($strID);
foreach ($infos as $info) {
echo "<label class='checkbox'>
<input type='checkbox'>".$info->information .
"</label>";
}
} else { // if it is unchecked
// I do not know how to delete
}

I want to add new selection on old ones.
you can use append() instead of html() which replaces the content:
$("#second_box").append(data);
how can I delete information in second box when I unchecked a checkbox.
you can use empty() which removes the contents of the selected element:
$("#second_box").empty();

Alternatively, you could do more on the client-side. See here for a demo.
<div id="first_box">
<label class='checkbox'>
<input data-url="url1" data-id="1" type="checkbox"> First checkbox
</label>
<label class='checkbox'>
<input data-url="url2" data-id="2" type="checkbox" > Second checkbox
</label>
<label class='checkbox'>
<input data-url="url3" data-id="3" type="checkbox"> Third checkbox
</label>
</div>
<div id="second_box"></div>​
JavaScript:
$(document).ready(function() {
$("#first_box input:checkbox").change(function(e) {
var $this = $(this);
if (already_loaded()) {
update_visibility();
} else {
load();
}
// END -- Functions
function already_loaded() {
return $this.data("loaded");
}
function is_loading() {
return $this.data("loading");
}
function load() {
if (!is_loading()) {
$this.data("loading", true);
var id = $this.data("id");
$.post("url", { // or use $this.data("url") if you want individual URLs
strId: id
}, function(data) {
$this.data("loaded", true);
$this.data("is_loading", false);
$("#second_box").append(data);
update_visibility();
});
}
}
function is_checked() {
return $this.is(":checked");
}
function update_visibility() {
var $info = $("#info-" + $this.data("id"));
if (is_checked()) {
$info.show();
}
else {
$info.hide();
}
}
});
$("#first_box input:checkbox").data("loaded", false);
$("#first_box input:checkbox").data("loading", false);
});​

Related

how to check if a checkbox is checked when sending data via ajax to php

I have a foreach loop which creates tr's with inside a checkbox and some input fields.
Each row has a checkbox with the id as value.
Each row has also a hidden input field with the id as value.
I want to distinguish whether a request is send via the own delete button in each row, or via the checkbox what is checked for (these) rows. (when multiple checkboxes are checked, i can delete them all at once)
<tr>
<input type="hidden" name="file_id" value="<?php echo $file_id; ?>" /> <!-- file id which belongs to each row -->
<td><input type="checkbox" class="checkbox" value="<?php echo $file_id; ?>" /></td>
...
<button class="btn btn-sm btn-danger submit" type="submit" name="delete_file">Delete</button>
</tr>
i send the data via jquery ajax to the php file:
// checkboxes value
$(document).on('click' , '.submit' , function() {
var checkbox_value = [];
var file_id = $(this).closest("tr").find("input[name='file_id']").val();
$('.checkbox').each(function() {
if ($(this).is(":checked")) {
checkbox_value.push($(this).val());
}
});
checkbox_value = checkbox_value.toString();
$.ajax({
url: "admin.php",
method: "POST",
data: {
checkbox_value: checkbox_value,
file_id : file_id
},
success: function(data) {
$('.result').html(data);
}
});
});
The php:
if(isset($_POST["checkbox_value"])) {
$checkboxfiles[] = $_POST["checkbox_value"];
$category = $_POST["category"];
// checkbox loop
foreach ($checkboxfiles as $checkboxfile) {
foreach(explode(',', $checkboxfile) as $id) {
echo $id.'<br />';
echo 'delete via checkbox is choosen';
}
}
exit;
}
if(isset($_POST["file_id"])) {
...
echo 'delete via single row is choosen';
}
Problem:
When i choose to delete via single row (no checkbox is checked), it still sends the echo delete via checkbox is choosen
try this code
if (this.checked) {
checkbox_value.push($(this).val());
}

JSON : Select Radio button base on response

How I could populate the checked state of radio buttons depending on data loaded from the database?
I want to get data radio button for this form
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1"> Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0"> Disable
</label>
this my array result
{"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
and I am pass that result through ajax like this
$.ajax({
url : "<?php echo site_url('cpanel/form_c/data_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="menu_id"]').val(data.id);
$('[name="parent_id"]').val(data.parent_id);
$('[name="menu_name"]').val(data.menu_name);
$('[name="menu_title"]').val(data.menu_title);
$('[name="url"]').val(data.url);
$('[name="order"]').val(data.position_menu);
$('[name="parent_status"]').val(data.parent_status);
//$('[name="menu_status"]').val(data.menu_status);
$('[name="fa_icon"]').val(data.fa_icon);
$('[name="type_form"]').val(data.type);
$.each (data, function (i, obj) {
$(':radio[name="menu_status"][value=' + obj.menu_status + ']').prop('checked', true);
});
/*if (data.parent_status===1) {
$('[name="menu_status"]').val("1").prop('checked',true);
} else {
$('[name="menu_status"]').val("0").prop('checked',true);
}*/
$('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Menu'); // Set title to Bootstrap modal title
},
Can someone help me to take the json data to select the appropriate choices?
var data = {"menu_id":"00001","parent_id":"0 ","menu_name":"Dashboard","menu_title":"Dashboard","url":"dashboard_c","position_menu":"1","parent_status":"0","menu_status":"1","fa_icon":"fa-dashboard","type":"1"}
console.log(data.menu_status)
$('input[name=menu_status][value='+data.menu_status+']').prop('checked', true)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-4">
<label>
<input type="radio" name="menu_status" class="flat-red" value="1">Enable
</label>
<label>
<input type="radio" name="menu_status" class="flat-red" value="0">Disable
</label>
</div>
try this way, the check radio button will be equal to what data.menu_status value is
Looks like the radio button class is flat-red. You could simply use this one instead of going with complex selectors.
You could use a condition instead.
if (data.parent_status == 1) {
$('.flat-red').checked = true;
}

Custom php form validation

I have a PHP form with different types of input fields (textbox, radio, checkbox,..) for which I used jQuery. It works fine for all input types except one of the question in my form for which the selected items(movies) by user are stored in an array. I think the image can explain better than me:
As can be seen in the image, selected movies by user are moved to the selected list(an array), while in jQuery validation, input names are "required" and therefore in this case only the value inserted in the textbox (in this case:"frozen") will be stored in database.
This is the code:
<form id="form2" action="page3.php" method="post">
<fieldset id = "q27"> <legend class="Q27"></legend>
<label class="question"> What are your favourite movies?<span>*</span></label>
<div class="fieldset content">
<p>
<div class="movienames">
<div class="field">
<Input type = 'radio' id="selectType" Name ='source' value= 'byTitle'>By title
<Input type = 'radio' id="selectType" Name ='source' value= 'byActor'>By actor
<Input type = 'radio' id="selectType" Name ='source' value= 'byDirector'>By director
</div>
<div id="m_scents" class="field">
<label style="margin-bottom:10px;" for="m_scnts"></label>
<p>
<input class="autofill4" type="textbox" name= "q27[]" id="q" placeholder="Enter movie, actor or director name here" />
<input type="button" value="search" id="btnSearch" />
</p>
<div>
</div>
<div id="basket">
<div id="basket_left">
<h4>Selected Movies</h4>
<img id="basket_img" src="http://brettrutecky.com/wp-content/uploads/2014/08/11.png" />
</div>
<div id="basket_right">
<div id="basket_content">
<span style="font-style:italic">Your list is empty</span>
</div>
</div>
</div>
</p>
</div>
</fieldset>
<script type="text/javascript">
var master_basket = new Array();
selectedMovies = {};
var selected;
var selectedVal;
var selectedDir;
$(document).ready(function () {
$("input[id='selectType']").change(function(){
$("#q").val('');
if ($(this).val() == "byTitle") {
//SOME LINES OF CODE....
.....
} else
if ($(this).val() == "byActor"){
// SOME LINES OF CODE
} else
if ($(this).val() == "byDirector"){
//SOME LINES OF CODE
}
});
$('#btnSearch').on('click', function (e) {
window.textbox = $('#q').val();
window.searchType = $('input:radio[name=source]:checked').val();
popupCenter("movielist.php","_blank","400","400");
});
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k,v) {
var name_and_year = v.movie_name;
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
});
}
</script>
// CODE RELATED TO OTHER QUESTIONS IN THE FORM....
//.........
<input class="mainForm" type="submit" name="continue" value="Save and Continue" />
</form>
<script src="http://jqueryvalidation.org/files/dist/jquery.validate.min.js"></script>
<script src="http://jqueryvalidation.org/files/dist/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$('#form2').validate({
rules: {
"q27[]": {
required: true,
},
//OTHER REQUIRED QUESTIONS....
},
errorPlacement: function(error, element) {
if (element.attr("type") == "radio" || element.attr("type") == "checkbox" || element.attr("name") == "q12[]") {
error.insertAfter($(element).parents('div').prev($('question')));
} else {
error.insertAfter(element);
}
}
});
});
</script>
QUESTION:
I have two problems with my code:
When I click on "Save and continue" button to submit this page of
the form, for the mentioned question (the one you could see in the
image), only the value inserted in the textbox will be stored in
database while I need all selected movies in the list will be stored
in separate rows in DB.
The textbox for this question is a hidden field that will be
appeared only if user select one of the radio button values. So, if
user just ignore this question and doesn't select one of radio
button values, then he can simply submit this page and continue
without any error message.
I would like to know if there is a way to customize jQuery validation so that I don't let users to submit this page until they didn't answer the mentioned question?? and then, how could I store the selected items by user in Database instead of textbox value?
All ideas would be highly appreciated,
To submit the basket movie items you can add a hidden input field. You would get something like this:
$("#basket_content").append("<div class='item_list'>" + v.movie_name + "<a class='remove_link' href='" + name_and_year + "'><img width='20' src='http://i61.tinypic.com/4n9tt.png'></a></div>");
$("#basket_content").append("<div type='hidden' name='basket_movie[]' value='"+v.movie_name+"' />");
Using this, there will be an array like $_POST['basket_movie'] which contains the movie names of the movies in the basket.
If you want to prevent submitting, when the input box isn't filled you just add an action listener on form submit and count the item_list items. If it's 0 then don't submit. Add something like this to prevent form submitting when there are no items added to the basket:
$(document).on('submit', '#form2',function(e)
{
if($('.item_list').length == 0)
{
e.preventDefault();
}
});

How to one change the value of the next input?

how can i one to one change the value of the next input?
this code doing check all or unchec all, but i want to check or uncheck one to one,
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).attr('checked')) {
jQuery('input:checkbox').attr('checked',true);
jQuery('input:text').attr('value','E');
} else {
jQuery('input:checkbox').attr('checked',false);
jQuery('input:text').attr('value','H');
}
});
});
Sample code:
<form>
<? for($i=1;$i<=5;$i++) { ?>
<input type="checkbox" id="pgun[]" name="pgun[]">
<input size="1" type="text" name="degerler[]" id="degerler[]" value="H">
<br />
<? } ?>
<label class="checkbox">
<input type="checkbox" value="E" name="topluekle" id="topluekle">
Check / Uncheck All *
</label>
</form>
Try
jQuery(function ($) {
$('#topluekle').click(function () {
$('input[name="pgun[]"]').prop('checked', this.checked);
$('input[name="degerler[]"]').val(this.checked ? 'E' : 'H');
});
});
Use val() like,
jQuery('input:text').val('H');
and use prop() in place of attr() like
jQuery(document).ready(function() {
jQuery('#topluekle').click(function() {
if(jQuery(this).prop('checked')) {
jQuery('input:checkbox').prop('checked',true);
jQuery('input:text').val('E');
} else {
jQuery('input:checkbox').prop('checked',false);
jQuery('input:text').val('H');
}
});
});
If you want to change value for each checkbox click then you can try,
jQuery(document).ready(function() {
jQuery('input[name="pgun[]"]').click(function() {
var newVal=$(this).next('input:text').val()=='E' ? 'H' : 'E';
$(this).next('input:text').val(newVal);
});
});
It will change corresponding text box's value of checkbox
jQuery(document).ready(function() {
var txtObj = $('input:text');
jQuery('input:checkbox').each(function(i){
jQuery(this).click(function(){
if(jQuery(this).attr('checked')) {
$(txtObj[i]).val("E");
} else {
$(txtObj[i]).val("H");
}
});
});
});

How to debug using firebug and show the value of radio button

I have radio buttons as shown below.
<div id="lensType">
<input type="radio" name="design" style="vertical-align: middle" value="1"/>
<label for="design">Single Vision</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="2" />
<label for="material" >Accommodative Support</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="3"/>
<label for="design">Bifocal</label> <br/>
<input type="radio" name="design" style="vertical-align: middle" value="4" />
<label for="material" >Varifocal (Intermediate/Near)</label><br/>
<input type="radio" name="design" style="vertical-align: middle" value="5"/>
<label for="material" >Varifocal (Distance/Near)</label>
</div>
I am making a dynamic select. I have my javascript code that post the value . It seems the supplier value is now posted. Below is the code for my script.
$(document).ready(function(){
function populate() {
fetch.doPost('getSupplier.php');
}
$('#lensType').change(populate);
var fetch = function() {
var counties = $('#county');
return {
doPost: function(src) {
$('#loading_county_drop_down').show(); // Show the Loading...
$('#county_drop_down').hide(); // Hide the drop down
$('#no_county_drop_down').hide(); // Hide the "no counties" message (if it's the case)
if (src) $.post(src, { supplier: $('#lensType').val() }, this.getSupplier);
else throw new Error('No source was passed !');
},
getSupplier: function(results) {
if (!results) return;
counties.html(results);
$('#loading_county_drop_down').hide(); // Hide the Loading...
$('#county_drop_down').show(); // Show the drop down
}
}
}();
populate();
});
Php code :
<?php
if(isSet($_POST['supplier'])) {
include 'db.php';
$stmt = $mysql->prepare("SELECT DISTINCT SupplierBrand FROM plastic WHERE HeadingNo='".$_POST['supplier']."'");
$stmt->execute();
$stmt->bind_result($supplierBrand);
while ($row = $stmt->fetch()) : ?>
<option value="<?php echo $supplierBrand; ?>" width="100px"><?php echo $supplierBrand; ?></option>
My problem is when I debug I notice there is no value passed to the php script and this makes the select empty. I have tried to trace or debug by having firebug output the console.log and failed in this regard.
Please assist with this code which is meant to show a dynamic list from a radio button selection.
for debugging:
$('input[name="design"]').change(function(){
console.log($('#lensType').find("input:radio[name ='design']:checked").val());
});
else:
$('#lensType').find("input:radio[name ='design']:checked").val();
instead of
$('#lensType').val()
and you probably want to wrap it witg a changed function, since onload no design is selected:
$(document).ready(function(){
$('input[name="design"]').change(function(){
var design = $('input[name="design"]:checked').val();
function populate() {
fetch.doPost('getSupplier.php');
}
$('#lensType').change(populate);
var fetch = function() {
var counties = $('#county');
return {
doPost: function(src) {
$('#loading_county_drop_down').show(); // Show the Loading...
$('#county_drop_down').hide(); // Hide the drop down
$('#no_county_drop_down').hide(); // Hide the "no counties" message (if it's the case)
if (src) $.post(src, { supplier: design }, this.getSupplier);
else throw new Error('No source was passed !');
},
getSupplier: function(results) {
if (!results) return;
counties.html(results);
$('#loading_county_drop_down').hide(); // Hide the Loading...
$('#county_drop_down').show(); // Show the drop down
}
}
}();
populate();
});
});
In your javascript you are getting the value of the div, not the radio button:
$('#lensType').val() <--- change that
To something like this:
$("#lensType input:radio[name='design']:checked").val()

Categories