Retrieveing the values from database selecting or deselecting the checkboxes JQuery - javascript

There is a problem in my jQuery. I want to retrieve the data from the database using AJAX.How I select and pass to the php file these values and get the multiple values.
For Example- when I select the checkbox the ajax will return the value of the selected checkbox. If I unselect the same checkbox then the value will be removed.
here the checkboxes are:
checkboxes.php
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="deep cleaning"/>Deep Cleaning</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="dishes"/>Dishes</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="move in/out"/>Move in/out</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside cabinets"/>Inside Cabinets</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside fridge" />Inside Fridge</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="inside oven" />Inside Oven</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="interior windows" />Interior windows</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="laundry + folding" />Laundry + Folding</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="green cleaning" />Green Cleaning</label>
</div>
<div class="block1">
<label><input type="checkbox" name="checkbox[]" id="extra" value="organization" />Organization</label>
<label><input type="checkbox" name="checkbox[]" id="extra" value="wipe window blinds" />Wipe Window Blinds</label>
</div>
</div>
<span id="cost"></span>
</div>
here the jQuery:
$(document).ready(function() {
var check=[];
$('input[type=checkbox]').on('change', function() {
var check=$(this).val();
console.log($(this).val());
$.ajax({
type:'POST',
data:{ "extra" : check},
dataType : "JSON",
url : "login.php",
success:function(response){
if(response){
totalCost=10+response;
$('#cost').text(totalCost);
}
}
});
});
});
here the php code-
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select price from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row['price'],JSON_NUMERIC_CHECK);
}
}
database image-
I want to check the multiples and recieve multiple values through ajax and when i unselect the checkboxes then the value will remove from the span total. if there is any mistake then i m sorry. i am a bigner. i hope you all will support me do better thnku in advance.

HTML
<label>Total amount : </label>
<span id="totalCost">0</span>
JS
$(document).ready(function () {
var check = [];
$('input[type=checkbox]').on('change', function () {
var checked = 0; // assigning ZERO for unchecked
if ($(this).prop('checked') == true) { // checking checkbox status
checked = 1; // ONE for checked
}
var totalCost = $("#totalCost").text(); // getting previous totalcost
var check = $(this).val();
// two parameters
// data json object
// callback function
getData({"extra": check}, function (response) {
var content = '';
if (response) { //response is json object
if (checked) { // if checkbox is checked
content = '<div id="' + response['id'] + '">' + response['price'] + '</div>';
//create another variable which have div with price and id
totalCost = parseInt(totalCost) + response['price'];
// add new price in previous price
} else {
$('#' + response['id']).remove();
// remove price div targeting with id
totalCost = parseInt(totalCost) - response['price'];
// subtract price from previous price
}
$("#cost").prepend(content); // prepend new content
$("#totalCost").html(totalCost);
}
});
});
function getData(data, callback) {
$.ajax({
type: 'POST',
data: data,
dataType: "JSON",
url: "login.php",
success: callback
});
}
});
Changes in php code
if (isset($_POST['extra'])) {
$query=mysqli_query($con,"select * from extras where name_of_extra ='$_POST[extra]'");
while ($row = mysqli_fetch_array($query)) {
echo json_encode($row,JSON_NUMERIC_CHECK);
}
}

Related

Get the values of column if checkbox/radio box is checked

I was wondering how to get the values in a certain column if the checkbox or radio button on that particular row is checked. I've already started and came up with this:
<script>
var Step = <?php echo $_SESSION['Step'] ?>;
if(Step == 3 || Step == 4 ) { setInterval(ScriptUpdate, 1000); }
function ScriptUpdate()
{
if(Step == 3)
{
var checked = $("input:checkbox:checked").length;
var radioButtonSelectedCount = $(document.querySelectorAll('input[type=radio]:checked')).parent().filter(function() {return $(this).text().trim()=="Yes"}).length;
var Counter = checked + radioButtonSelectedCount;
$('#ES3I').text(Counter + ' Items');
var price = 0;
$("#TextBookTB tr:gt(0) td:nth-child(6)").each(function(td){
var content = $(this).text();
if($.isNumeric(content)) {
price = price + Number(content);
console.log(price);
}
});
$("#ES3P").text(price);
}
}
</script>
The goal is that: when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value. Apologies, I am really bad at jquery/javascript.
EDIT: html code as requested. The current output of the timer takes all of the values in all rows of that particular column.
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="'.$Result[$i]['ID'].'"> Yes
</label>
<label class="radio-inline">
<input form="ES3S" type="radio" name="Textbook'.$i.'" value="-1">No
</label>
<span class="d-inline-block" data-toggle="popover" title="Error" data-content="This book is required by the school. If you want to cancel this out, proceed to the principals office with the book for review." data-trigger="hover">
<input form="ES3S" required checked onclick="return false;" type="checkbox" value="'.$Result[$i]['ID'].'" name="Textbook'.$i.'">
</span>
try this if you are using table
var count = 0;
$('#TABLEID').find('tr').each(function () {
var tableRow = $(this);
if (tableRow.find('input[type="checkbox"]').is(':checked')) {
count += 1;
}
});
when user checks the check box or answered 'yes' in the radio button it is the only time it will count the value
$(function() {
var selector = 'input[name^="Textbook"]';
$(selector).on('click', function() {
var checked = $(selector + ':checked').map(function() {
return {
'type': this.type,
'value': this.value
};
}).get().filter(function(o) {
return '-1' !== o.value; // skip if value = -1(No)
});
console.log('checked inputs', checked);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<label><input type="radio" name="Textbook1" value="1"/>Yes</label>
<label><input type="radio" name="Textbook1" value="-1"/>No</label>
<input type="checkbox" name="Textbook1" value="1" />
</div>
<div>
<label><input type="radio" name="Textbook2" value="2"/>Yes</label>
<label><input type="radio" name="Textbook2" value="-1"/>No</label>
<input type="checkbox" name="Textbook2" value="2" />
</div>

use implode and ajax to insert checkbox values

i want to insert my checkbox values, i dont know how to take all the values using ajax and use implode to insert them in one row.
// this is my javascript where i take the data ,
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var modday = $('#modalday').val();
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: "subj=" + modsubj + "&sect=" + modsect + "&day=" + modday + "&start=" + modstart + "&end=" + modend + "&user=" + moduser
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" id="modalday[]" name="modalday[]" value="F">Friday
</label>
</div>
this is my php function, i used the implode function so that i can insert the data on one row.
$page = isset($_GET['p'])?$_GET['p']:'';
if($page=='add'){
foreach ($_POST['day'] as $key => $value) {
$subj = $_POST['subj'];
$sect = $_POST['sect'];
$day = implode("",$_POST['day']);
$strTime = $_POST['start'];
$endTime = $_POST['end'];
$user_id = $_POST['user'];
}
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
Here is how to send a list to the server
You can explode the day to get an array of days
To add more items, add a comma and more key values:
data: { day: modday.join(","),
subj:$('#modalsubject').val() // no comma on the last
}
$(function() {
$("#save").on("click", function() {
saveData();
});
});
function saveData() {
var modday = [];
$('.modalday:checked').each(function() {
modday.push(this.value);
});
console.log(modday);
$.ajax({
type: "POST",
url: "modal.funcs.php?p=add",
data: { day: modday.join(",") }
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="T">Tuesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="W">Wednesday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="Th">Thursday
</label>
</div>
<div class="checkbox">
<label class="checkbox-inline">
<input type="checkbox" class="modalday" name="modalday[]" value="F">Friday
</label>
</div>
<button id="save">Save</button>
I tried this myself, and I think most of the action can occur in your saveData function, not in PHP.
I'm assuming you will change your ids to a class instead, as id's should be unique:
<input type="checkbox" class="modalday" name="modalday[]" value="M">Monday
Check this out:
function saveData() {
var modsubj = $('#modalsubject').val();
var modsect = $('#modalsection').val();
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
var modstart = $('#modalstarttime').val();
var modend = $('#modalendtime').val();
var moduser = $('#userID').val();
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
};
I just used vanilla JavaScript to select all the modalday elements, then loop through them and add the values (M, T, W, etc...) of the ones that are checked to the modday array:
var moddayAll = document.getElementsByClassName('modalday');
var modday = [];
for (let i = 0; i < moddayAll.length; i++) {
if (moddayAll[i].checked) {
modday.push(moddayAll[i].value);
}
}
Then, since you are using the POST method anyway, I used JQuery's .post(), and passed the 'p' param along with the data, instead of in a query string. You'll notice this is where the modday array is turned to a string with the join() call as well:
var add = 'add';
$.post("modal.funcs.php", {p:add, subj:modsubj, sect:modsect, day:modday.join(","), start:modstart, end:modend, user:moduser},
function( data ) {
// do whatever you want with data returned from modal.funcs.php
}
);
Then, in modal.funcs.php, you can just get the values from the $_REQUEST variable and pass them to your functions:
<?php
$page = $_REQUEST['p'];
if ($page == 'add') {
$subj = $_REQUEST['subj'];
$sect = $_REQUEST['sect'];
$day = $_REQUEST['day'];
$strTime = $_REQUEST['start'];
$endTime = $_REQUEST['end'];
$user_id = $_REQUEST['user'];
$auth_user->createSchedule($subj,$sect,$day,$strTime,$endTime,$user_id);
$schedRow = $auth_user->readSchedule();
} else if ($page=='edit') {
}
$_REQUEST['day] will be a comma-separated string of the values of the checkboxes that were checked. If you need to do further processing of the array here, you can add another step to do so.

checkbox - Check uncheck functionality is not working

My situation :
I am working on an shopping cart application and it contains some filters:
Filter by color (checkboxes)
Filter by style (checkboxes)
on selecting some of the colors my url becomes like this:
http://example.com/women/try.php?color=10,11,12,13
My issue :
On unchecking some colors the related params are not getting cleared from the url.
Also when I select some styles , I want the url to be like this:
http://example.com/women/try.php?color=10,11,12,13&style=1,2,3
Please help me how to achieve this functionality.
My code :
<?php
$colors = $_GET['color'];
$sel_colors = explode(',', $colors);
foreach($sel_colors as $k=>$v) {
$c['check'][$v] = $v;
}
for($i=10;$i<=14;$i++) { ?>
<input type="checkbox" name="color[]" value="<?php echo $i; ?>" <?php echo $check_value = ($c['check'][$i]) ? 'checked' : '0'; ?> >
<label>Color #<?php echo $i.'--'.$check_value; ?></label><?php
}
?><br/><br/><br/>
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" >
<label>style #2</label>
<input type="checkbox" name="type" value="3" >
<label>style #3</label>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js" ></script>
<script type="text/javascript">
var baseUrl = 'http://website/women/try.php?color=';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
e.preventDefault();
if ($(this).is(':checked')) {
// read in value
var queryString = $(this).val();
// loop through siblings (customize selector to your needs)
var s = $(this).siblings();
$.each(s, function () {
// see if checked
if ($(this).is(':checked')) {
// append value
queryString += ',' + $(this).val();
}
});
// jump to url
window.location = baseUrl + queryString;
}
});
});
</script>
Here is a code snippet of working solution. Name of the color checkbox is changed from color[] to just color
var baseUrl = 'http://website/women/try.php?';
$(document).ready(function () {
// listen to change event (customize selector to your needs)
$('input[type=checkbox]').change(function (e) {
//Get all the selected color values
var queryString = "color="+$('[name="color"]:checked')
.map(function() {return this.value;}).get().join(',');
//Append all the selected styles
queryString += "&style="+$('[name="type"]:checked').map(function() {return this.value;}).get().join(',');
//reload page - commented for this snippet
//window.location = baseUrl + queryString;
alert(baseUrl + queryString);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Color filter -->
<input type="checkbox" name="color" value="1" checked >
<label>Color 1</label>
<input type="checkbox" name="color" value="2" checked >
<label>Color 2</label>
<input type="checkbox" name="color" value="3" checked >
<label>Color 3</label>
<input type="checkbox" name="color" value="4" checked >
<label>Color 4</label>
<BR><BR>
<!-- Style filter -->
<input type="checkbox" name="type" value="1" >
<label>style #1</label>
<input type="checkbox" name="type" value="2" checked>
<label>style #2</label>
<input type="checkbox" name="type" value="3" checked>
<label>style #3</label>
Use map() function to get all checked color and style checkbox values like following.
var baseUrl = 'http://website/women/try.php?color=';
$('input[name="color[]"], input[name="type"]').change(function () {
var colors = $('input[name="color[]"]:checked').map(function () { return this.value; }).get().join();
var styles = $('input[name="type"]:checked').map(function () { return this.value; }).get().join();
window.location = baseUrl + colors + '&style=' + styles;
});

array of checkbox value checked and unchecked

I have this function, when I checked one or more checkbox the function load the value of the checked checkbox...but when I unchecked one or more check box the function show an empty array.
this is the function:
$(document).ready(function () {
$('input[type="checkbox"]').change(function () {
var mycheck = new Array();
if ($(this).is(':checked')) {
$("#line-checkbox-1:checked").each(function () {
mycheck.push($(this).val());//aggiungo value del checked
});
alert(mycheck)
} else {
var itemtoRemove = $(this);
mycheck.splice($.inArray(itemtoRemove, mycheck), 1); //rimuovo il value del dechecked
alert(mycheck);
}
});
This is HTML of the checkbox:
<div class="col-lg-3">
<input tabindex="17" id="line-checkbox-1" type="checkbox" name="servizi" value="3">
</div>
Try This Simple Script, this works for you:
HTML
<input type="checkbox" name="options[]" value="1" />
<input type="checkbox" name="options[]" value="2" />
<input type="checkbox" name="options[]" value="3" />
<input type="checkbox" name="options[]" value="4" />
<input type="checkbox" name="options[]" value="5" />
JQUERY
$(document).ready(function ()
{
$('input[type="checkbox"]').change(function ()
{
var arr = $.map($('input:checkbox:checked'), function(e,i) {
return +e.value;
});
alert(arr);
});
});
Its probably because you are using id to reference the checkboxes and since you are creating the array from scratch everytime user changes a checkbox. you should recheck the list everytime a checkbox is changed. That means you dont need that if.( if($(this).is(":checked") )
$('.checkboxes input[type="checkbox"]').change(function () {
var mycheck = new Array();
$(".checkboxes input[type='checkbox']:checked").each(function () {
if ($(this).is(':checked')) {
mycheck.push($(this).attr("id") + ": is " + $(this).val()); //aggiungo value del checked
}
});
alert(mycheck);
});
here is a fiddle if i understand correctly what you are trying to do

How to pass values of selected checkboxes to the javascript function?

I need to pass values of selected check boxes to the javascript method but it does not detect the checkbox.
<form name="cat" method="POST" action="myaction">
<c:forEach items="${items}" var="item">
<input type="checkbox" id="pro" name="pro" value="${item.id}"/>
</c:forEach>
...
<input type="button" value="getItem" onclick="getItem(this.form)"/>
</form>
Javascript
function getItem(frm) {
alert("size:" + frm.pro.length); <<< it returns size:unidentified
var values = "";
for (var i = 0; i < frm.pro.length; i++)
{
if (frm.pro[i].checked)
{
values = frm.pro[i].value + ",";
}
}
alert(values); << it is empty
....
//pass values to the back-end
I think your approach is old fashioned. Here's a jQuery version.
NOTE: you are adding multiple id="pro" and this is just wrong remove it
First add id="form" to your form
Here you can find a fiddle. :D
http://jsfiddle.net/SXffG/3/
HTML:
<form id="form" name="cat" method="POST" action="myaction">
<input type="checkbox" name="pro" value="1"/>
<input type="checkbox" name="pro" value="2"/>
<input type="checkbox" name="pro" value="3"/>
<input type="checkbox" name="pro" value="4"/>
<input type="checkbox" name="pro" value="5"/>
<input type="checkbox" name="pro" value="6"/>
<input type="button" class="getItem" value="getItem"/>
</form>
<div id="info">Click the button</div>
JavaScript
var allVals = [];
$(function() {
$('#form .getItem').click(function() {
allVals = []
$('#form :checked').each(function() {
allVals.push($(this).val());
});
//alert("Values " + allVals);
$.ajax({
type: "POST",
url: "http://localhost:8080/example/ajaxSubmit.action",
data: "allVals=" + allVals,
success: function(response){
$('#info').html("OK! Data [" + allVals + "] Sent with Response:" + response);
},
error: function(e){
$('#info').html("OH NOES! Data[" + allVals +"] Not sent with Error:" + e);
}
});
});
});
var check = document.getElementsByName("pro");
var textArray = [];
for(var c = 0; c < check.length;c++){
if(check[c].checked){
textArray .push(check[c].value);
}
}
textArray = textArray .join("~");
you will get the data as tilde separated. Hope this helps you.

Categories