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 + "§=" + 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.
Related
This question already has answers here:
How to get value of selected radio button?
(30 answers)
Closed 6 months ago.
I have a purchase order in which I would like to be able to retrieve the value of the button so that I can send it by POST
But it doesn't work I get this error when I validate the data with the command button
Uncaught TypeError: document.getElementByName is not a function
here is the radio button syntax and processing in ajax
<fieldset>
<div>
<input type="radio" id="huey" Name="promotion" class="promotion" value="huey"checked
>
<label for="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" Name="promotion" class="promotion" value="dewey">
<label for="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" Name="promotion" class="promotion" value="louie">
<label for="louie">Louie</label>
</div>
</fieldset>
function commander(nom, prenom, adresse,detail_livraison,promotion) {
$.ajax({
url: 'mail.php',
type: 'POST',
data: 'nom=' + nom + '&prenom=' + prenom + '&adresse=' + adresse + '&detail_livraison=' + detail_livraison + '&promotion=' + promotion ,
dataType: 'html',
success: function(reponse) {
if(reponse == "1") {
//MonPanier.clearpanier();
afficherpanier();
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
$('#mymodal').modal('show');
}
if(reponse == "0-1") {
$('#mymodal_erreur_1').modal('show');
}
if(reponse == "0-2") {
$('#mymodal_erreur_2').modal('show');
}
if(reponse == "0-3") {
$('#mymodal_erreur_3').modal('show');
}
if(reponse == "0-4") {
$('#mymodal_erreur_4').modal('show');
}
if(reponse == "0-5") {
$('#mymodal_erreur_5').modal('show');
}
}
});
}
$('#commander').click(function() {
var nom = document.getElementById("nom").value;
var prenom = document.getElementById("prenom").value;
var adresse = document.getElementById("adresse").value;
var detail_livraison = document.getElementById("livraison-detail").innerHTML;
var promotion = document.getElementByName("promotion").innerHTML;
commander(nom, prenom, adresse,detail_livraison,promotion,);
});
As I see you are already using jQuery, then why not do something like this -
let promotion = $('input[name="promotion"]:checked').val()
You can read more about it here in the doc
const log = data => console.log(JSON.stringify(data));
let $promo = $('.promotion').val();
const all = document.forms.main.elements;
let promo = all.promotion.value;
log($promo);
log(promo);
<form id='main'>
<fieldset>
<div>
<input type="radio" id="huey" name="promotion" class="promotion" value="huey" checked>
<label for="huey">Huey</label>
</div>
<div>
<input type="radio" id="dewey" name="promotion" class="promotion" value="dewey">
<label for="dewey">Dewey</label>
</div>
<div>
<input type="radio" id="louie" name="promotion" class="promotion" value="louie">
<label for="louie">Louie</label>
</div>
</fieldset>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I saw lots of similar question where you can extract the values of Checkboxes based on the check uncheck and add them to URL, but if we have different categories of checkbox group, separate them with &.
Example:
$(document).ready(function() {
var swapRelation = "";
$("input[type=checkbox]").click(function(e) {
var seasoning = "",
parentRelation = "",
tempArray = [];
$("input:checked").each(function() {
tempArray.push($(this).attr("name").replace(/\s/g, ''));
parentRelation = $(this).closest(".wrapper").find('.catName').text().trim();
parentRelation = parentRelation.replace(/\s/g, '');
});
if (tempArray.length !== 0) {
seasoning += `${parentRelation}=` + tempArray.toString();
// if (swapRelation == parentRelation) {
// // seasoning+=`&${parentRelation}=`+tempArray.toString();
// seasoning += `${parentRelation}=` + tempArray.toString();
// }else {
// }
//tempArray = [];
swapRelation = parentRelation;
}
console.log("example.com?" + seasoning);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div class="catName">Fruits</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="apple" id="input-5">
<input class="input__field" type="checkbox" name="banana" id="input-6">
<input class="input__field" type="checkbox" name="mango" id="input-7">
</div>
</div>
<div class="wrapper">
<div class="catName">Vaegs</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Okra" id="input-8">
<input class="input__field" type="checkbox" name="Patato" id="input-9">
<input class="input__field" type="checkbox" name="Tamato" id="input-10">
</div>
</div>
<div class="wrapper">
<div class="catName">Rivers</div>
<div class="checkBoxWrap">
<input class="input__field" type="checkbox" name="Ganga" id="input-11">
<input class="input__field" type="checkbox" name="yamuna" id="input-12">
<input class="input__field" type="checkbox" name="thames" id="input-13">
</div>
</div>
Expected Result on multiple Selections:
URL?Fruits=banana,mango&Vegs=okra,patato&Rivers=ganga,whateverSelected
You can use URLSearchParams to build your query string.
var usp = new URLSearchParams();
document.querySelectorAll('.wrapper').forEach((wrapperDiv)=> {
var category = wrapperDiv.querySelector('.catName').textContent;
var checkedBoxes = wrapperDiv.querySelectorAll('input[type="checkbox"]:checked');
var values = Array.from(checkedBoxes, cb=>cb.name).join('');
usp.append(category,values);
});
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);
}
}
I am developing an eCommerce system.
Let say if user has total of 1200 right.
If he chooses fast delivery options
40 should be added to total that means at the end amount should be changed from 1200 to 1240.
I have a developed a kind of application for that.
I don't know what but the value is not increment. Don't know what but I need a solution,
Here is my code:
<label><input type="radio" name="optradio" id="target">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="savevalue" style="visibility:hidden"></div>
<label><input type="radio" name="optradio" id="target2">
<span class="label label-success">Regular Delivery</span></label>
My Javascript code:
$('#target').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (savevalue==null || savevalue=="")
{
output = output*1 + 40;
savevalue = output;
$('#output').html(function(i, val) { return output});
$('#savevalue').html(function(i, val) { return savevalue});
}
});
$('#target2').click(function() {
var savevalue = $('#savevalue').text();
var output = $('#output').text();
if (output==savevalue)
{
output = output*1 - 40;
$('#output').html(function(i, val) { return output });
}
});
Try this :
HTML :
<p id="price">100</p>
<input type="radio" name="delivery" id="delivery1" value="normal" checked> Normal <br>
<input type="radio" name="delivery" id="delivery2" value="fast"> Fast
Js:
$(document).ready(function(){
$('#delivery1,#delivery2').change(function(){
price = $('#price').text();
if($('#delivery2').is(':checked')) {
price = parseInt(price) + 40;
} else {
price = parseInt(price) - 40;
}
$('#price').text(price);
});
});
can you check on my fiddle https://jsfiddle.net/3422ntLh/.
In my solution, check the html code.
<label>
<input type="radio" name="delivery" id="target" speed="fast">
<span class="label label-success">Fast Delivery</span></label>
<div id="output">10</div>
<div id="original" value="10" style="visibility:hidden"></div>
<label>
<input type="radio" name="delivery" id="target2" speed="normal">
<span class="label label-success">Regular Delivery</span></label>
I saved the value of the good in $('#original).
This is my JS code:
$('input:radio[name="delivery"]').change(function() {
alert($('#original').attr('value'));
$('#output').html($('#original_cost').attr('value'));
if ($(this).attr('speed') == 'fast') {
var extra_shipping_fee = 40;
var current_price = parseInt($('#original').attr('value'));
var new_price = current_price + extra_shipping_fee;
$('#output').html(new_price);
} else {
$('#output').html($('#original').attr('value'));
}
})
The code is not refine, but it will give you some insights on how to continue
I tried some jquery to append my check box checked values to the url as query string the code is working nice but when I check more than one checkbox the url will like this.....
Localhost:355/searchdatabase/?manufacturer=LG&manufacturer=Samsung&manufacturer=Test
But I need the url Like
Localhost:355/searchdatabase/?manufacturer=LG,Samsung,Test
here is my code
$(document).ready(function () {
$('input[type="checkbox"]').on('change', function (e) {
var data = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
data.push(this.name + '=' + this.value);
}
});
data = data.join('&');
$.post('/ajax-post-url/', data);
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + data);
}
});
});
My checkbox list groups code here
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>LG</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Samsung</label>
</div>
<div class="rowElem">
<input type="checkbox" name="manufacturer" id="">
<label>Test</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>iron</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>steel</label>
</div>
<div class="rowElem">
<input type="checkbox" name="material" id="">
<label>copper</label>
</div>
I need Manufacturer as a group and material as another..
You can add all manufacturers to separated array and then add as one field.
var manufacturers = [];
if (this.checked) {
if (this.name === 'manufacturers') {
manufacturers.push(this.value);
} else {
data.push(this.name + '=' + this.value);
}
}
And before data = data.join('&'); add data.push('manufacturers=' + manufacturers.join(','));.