Multiple checkboxes with unique ID's through ajax - javascript

I'm working on a website which should be done any time now, but I've got a new task to complete where I need to check check-boxes to simply archive news items. Or "blog posts" if you like.
The idea is to have a check-box on every blog post and if you check that check-box, the post should be archived. (This is in admin mode only).
I need ajax to do the job, but I haven't learned that yet. The PHP part is no problem.
Well the problem really is that I don't know how to pass the unique ID of every check-box, to the JavaScriptfunction and then to the PHP function.
OK, I have a set of blog posts, witch check-boxes, like so:
<div class="news_item">
<input name="checkbox_blog" id="checkbox1" value="1" type="checkbox" />
</div>
<div class="news_item">
<input name="checkbox_blog" id="checkbox2" value="1" type="checkbox" />
</div>
and so on. The Id's are populated from the ID from MySQL.
I have some kind of plugin for ajax checkboxes, but it will only work for one checkbox.
It's basically like this:
$("#checkbox").change(function() {
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST'
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST'
});
}
});
Works great on one check-box, but I have no idea how to proceed.
Any tips?
I think it's OK that it uses two different php-scripts for checking and un-checking the blog-posts, it doesn't really matter, I only want it to start working with different check-boxes.
Thanks!
Solution:
I changed the id's to classes, and used Arun P Johny's code:
$('.checkbox_blog').change(function () {
$.ajax({
url: this.checked ? 'admin/archive_it' : 'admin/dont_archive_it',
type: 'POST',
data: {
id: this.value
}
});
});
And because I'm using CodeIgniter, and have the CSRF-security option turned on, I had to add this to the data:
<?=$this->security->get_csrf_token_name()?> : '<?=$this->security->get_csrf_hash()?>',
And now it works perfectly! Thanks all!

There is no need for an ID here, use a class attribute to group the check boxes and give the database id as the value of the checkbox
<div class="news_item">
<input name="checkbox_blog" class="checkbox_blog" value="1" type="checkbox" />
</div>
<div class="news_item">
<input name="checkbox_blog" class="checkbox_blog" value="2" type="checkbox" />
</div>
then in the write change handlers for the .checkbox_blog elements, and pass the id of the database item to to archived or not as a parameter to the server side PHP
$('.checkbox_blog').change(function () {
$.ajax({
url: this.checked ? 'admin/archive_it' : 'admin/dont_archive_it',
type: 'POST',
data: {
id: this.value
}
});
});

you are almost there, except that there were few things which you may need to take care ,like
add a generic class for all the checkboxes, so that the below event handler will work fine for all checkboxes.
there is no need to keep multiple ajax call references, although url is the only differentiator,so i have refined your code and even corrected few things which i noticed .
JS CODE:
$(".checkbox").on('change',function() {
var chkBit=$(this).is(":checked");
var url;
if(chkBit)
tarUrl='admin/archive_it';
else
tarUrl='admin/dont_archive_it';
$.ajax({
url: tarUrl,
type: 'POST',
success:function(){
//when the call is successful do something
}
});
});`

Give all your checkboxes same class and then on change of any checkbox pass the ids of the checkboxes that are selected using the data attribute(probably by iterating over all the checkboxes with the class and collecting the ids of the ones that are checked)

<input name="checkbox_blog" id="checkbox1" value="1" type="checkbox" onClick="YourFunction()" />
<input name="checkbox_blog" id="checkbox2" value="1" type="checkbox" onClick="YourFunction()" />
function YourFunction(){
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST'
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST'
});
}
}

if you are dead-set on using id from checkbox, you can pass data like so: (note the change to selector $("input[id^=checkbox]")
$("input[id^=checkbox]").change(function() {
if($(this).is(":checked")) {
$.ajax({
url: 'admin/archive_it',
type: 'POST',
data: {
id: $(this).attr('id').split('checkbox')[1]
}
});
} else {
$.ajax({
url: 'admin/dont_archive_it',
type: 'POST',
data: {
id: $(this).attr('id').split('checkbox')[1]
}
});
}
});

Related

how can without refreshing pull data with ajax in django

I can post with ajax, but when I want to pull data without refreshing the page, I can only do it 2 times, then the button loses its function.
<div>
<input type="hidden" name="producecode" class="pcode" value="{{per.produceCode}}" />
<input type="hidden" name="useremail" class="uponequantity" value="{{user.username}}" />
<button class="btn btn-sm btn-primary upoq"><i class="fa fa-plus"></i></button></div>
and jquery
$.ajax({
type: "POST",
url: "/uponequantity/",
headers: { "X-CSRFToken": '{{csrf_token}}' },
data: {
"producecode":$(this).parent().find(".pcode").val(),
"useremail":$(".uponequantity").val(),
},
success: function() {
window.location.assign('/basket/'+"?b="+$(".uponequantity").val());
}
});
/*$.ajax({
url:'/baskett/'+"?b="+$(".uponequantity").val(),
headers: { "X-CSRFToken": '{{csrf_token}}' },
type:'POST',
success:function(result){
$('.basket').html(result);
}
});
*/
})
Just add another line to reference your second input same as the first.
$(".up").click(function(){
$(".prdtd").find("input:first- child").attr("value");
$(".pcode").val()
$(".uponequantity").val()//<-- new line for the second hidden value
}
-----------------------------------------
Update:
-----------------------------------------
OP has multiple buttons with the same class each in it's own div and wants to access the values within each div.
So, first off you need to change "pcode" from an id to class in order to get all instances. (id is for unique instances)
After that you need to be able to get the "pcode" & "uponequantity" that are associated with that button and one way of doing that is:
$(".up").click(function(){
$(this).parent().find(".pcode").val()
$(this).parent().find(".uponequantity").val()
}
Simply put, the this keyword references the clicked button.
You then get the direct parent element which would have the button and the hidden values as children.
Finally you get each specific child through the find command and do whatever you want with them.
If I understand your question correctly, you would like to get the value of both inputs in your callback.
It seems like you misspelt pdcode in your JavaScript.
Does the below code snippet help?
$(".up").click(function() {
const value1 = $(".pdcode").val();
const value2 = $(".uponequantity").val();
}

AJAX request to database

There are many checkbox pages in my Rails application.
When clicking on one checkbox, its id should immediately be written to database (I use postgresql)
Сheckbox id should be written to the table as an array.
How to implement this with ajax?
An example of my checkbox:
<input name="skill_list[127]" type="hidden" value="0">
<input class="m-enabled" id="skill_list_127" name="skill_list[127]" type="checkbox" value="1">
<label for="skill_list_127">Zoomerang</label>
UserSkillList controller:
def create
skill_id = params[:skill_id].gsub(/\D/, '').to_i if params[:skill_id].present?
#skill_record = UserSkillList.where(user_id: current_user.id).first
#skill_record.skill_id += [skill_id]
#skill_record.save
end
app.js:
$('input[type=checkbox]').click(function(){
if ($(this).is(':checked')) {
checkbox_id = $(this).attr('id');
$.ajax({
type: "POST",
url: "/user_skill_list",
data: {skill_id: checkbox_id}
});
};
});

Get checkbox value with jQuery in .ajax data

I'm trying to pass a boolean (checked/unchecked) value with .ajax, and I can't make it work. I have read a bunch about how to get the value of a checkbox using .is(':checked'), vs .prop('checked') but I can't seem to make anything work.
Here is my HTML:
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
And here is my JavaScript
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('checkbox#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
I can make the script work for the select boxes, and those continue to work after I add the checkbox, but the value of the checkbox is not being passed.
All I am interested in is passing 'checked' vs 'unchecked'.
Any help would be appreciated. Thanks.
You are using invalid selector. Use input instead.
Your HTML have input element,
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
function send() {
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $('input#typeOfSearch').prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
You can't select a checkbox as no such tag exists. Try input or even giving it a unique id without caring about the tag e.g. $('#typeOfSearch'):
function send() {
$cb = $('input#typeOfSearch');
console.log($cb.prop('checked'));
$.ajax({
url: 'partsTable.php',
type: 'post',
dataType: 'html',
data: {
major: $('select#dropdownMajor').val(),
minor: $('select#dropdownMinor').val(),
typeOfSearch: $cb.prop('checked')
},
success: function(data) {
var result = data
$('#fromPartsTable').html(result);
}
});
}
$('#submit').click(function() {
send();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" value="TRUE">
<label for="typeOfSearch">Exact Search?</label>
<button id="submit">Send</button>
Hope this helps :)
$(document).ready(function() {
//set initial state.
$('#typeOfSearch').change(function() {
$('#typeSelected').html(($(this).is(':checked') ? "TRUE" : "FALSE"));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="typeOfSearch" /> This Type
<br>
Type Selected:
<span id="typeSelected">FALSE</span>
Your selector is wrong
$('checkbox#typeOfSearch')
You are looking for this:
<checkbox id="typeOfSearch">
If you just select by the id, it would work
$('#typeOfSearch')
The below are some of the ways you can see if the checkbox is checked. If the checkbox is checked the value is true or else it is false.
if ($('#typeOfSearch:checked').length > 0) {
/* Do something */
}
if($('#typeOfSearch').prop('checked') == true) {
/* Do something */
}
if ($('#typeOfSearch').filter(':checked')) {
/* Do something */
}
Hope this helps.
Please search better when asking Stack Overflow questions. This was the top hit on Google for "jquery get checked or unchecked":
https://stackoverflow.com/a/27265333/5129424
Your selector will only attach event to element which are selected in the beginning. You need to determine check unchecked state when value is changed:
$("#countries input:checkbox").change(function() {
var ischecked= $(this).is(':checked');
if(!ischecked)
alert('uncheckd ' + $(this).val());
});
Working Demo

Newbie to Javascript: how to avoid sending data that have not changed?

I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481

Categories