how to select elements which their names are array in jquery? - javascript

How I can get the values of these elements and post them as array by ajax:
<input type="checkbox" name="Broadcast[m]"/> Members
<input type="checkbox" name="Broadcast[i]"/> IATA agencies
<input type="checkbox" name="Broadcast[n]"/> non-IATA agencies
<input type="checkbox" name="Broadcast[c]"/> Commitees

try this:
First change your input name to simply name="Broadcast[]"
<input type="checkbox" name="Broadcast[]" value="Members"/> Members
<input type="checkbox" name="Broadcast[]" value="IATA agencies"/> IATA agencies
<input type="checkbox" name="Broadcast[]" value="non-IATA agencies"/> non-IATA agencies
<input type="checkbox" name="Broadcast[]" value="Commitees"/> Commitees
and then in jquery to send the data in array via ajax, create a variable to mapping all the values to an array.
jquery:
var BroadCast = $("input[name='BroadCast\\[\\]']").map(function () { return $(this).val(); }).get();
and put the variable BroadCast into the ajax data.
$.ajax({
type:"post",
url:'your action url',
data: {BroadCast: BroadCast},
success:function(data){
//do what you want here
}
});
Hope this helps you.

var items = $("input[type=checkbox][name^=Broadcast]"), values = [];
items.each(function(){
values.push([$(this).attr("name"),$(this).is(":checked")]);
});
console.log(values);
sorry was wrong before, here is a fiddle for you
fiddle

you can use serialize method to do this.first in your html add value to checkboxes and remove whatever inside [] and make it name='Broadcast[]' for each checkbox.
$.ajax({
type:"post",
url:'your url',
data:$("form").serialize(),
success:function(data){
//do stuff here
}
});

Related

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}
});
};
});

Send value of element that changed through AJAX

I would like to catch the value of a checkbox when the value changes and then send it through Ajax.
There are several hundred of checkboxes displayed in my HTML page, so I cannot simply send all the values when one value changes. I only want to send the value of the checkbox that just changed.
Here is my HTML code :
<INPUT type="checkbox" name="cb_redir301" value="post_id_445">
<INPUT type="checkbox" name="cb_redir301" value="post_id_573">
<INPUT type="checkbox" name="cb_redir301" value="post_id_264">
<INPUT type="checkbox" name="cb_redir301" value="post_id_387">
<INPUT type="checkbox" name="cb_redir301" value="post_id_190">
(...)
<INPUT type="checkbox" name="cb_redir301" value="post_id_268">
I tried the following Javascript to catch and send the value, but it doesn't work, probably because the name of the checkbox ('cb_redir_301') is not unique.
$('#redir_selector').change(function(evt) {
$.post(ajaxurl, {
action: 'save_backend_assocs',
nonce: $('#ajax_admin_redir_selector_nonce').text(),
cb_redir301: $(this).is(':checked')
}, function(response) {
});
});
});
So, how can I told JS to only send the value of the checkbox that has been changed?
Faster:
var checkboxes = document.querySelectorAll("input[type='checkbox']");
for(var i = 0 ; i < checkboxes.length ; i++) {
checkboxes[i].addEventListener("change", updateData);
}
Just found a solution through:
$("input[type='checkbox']").on("change",function(){
console.log($(this).val());
It should work now.
Ken.

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>

How to get checked values of input tag which has array-name and send this values to server

I have a html-form:
<input name="arrayname[]" type="checkbox" value="1">
<input name="arrayname[]" type="checkbox" value="2">
<input name="arrayname[]" type="checkbox" value="3">
<input name="arrayname[]" type="checkbox" value="4">
Note the name attribute of input tag is set as arrayname[].
If I click some checkboxes and submit form then I get in $_POST global array:
["arrayname"]=>
array(2) {
[0]=>
string(1) "1"
[1]=>
string(1) "3"
}
I want to get checked values from input tag using jQuery for sending them to server via ajax. I have invented javascript function:
function myGetValue(fieldName)
{
var value;
value = $('input[name='+fieldName+']').val();
return value;
}
But this function works with simple names without square brackets like 'simplename'. For example:
<input name="simplename" type="text" value="my text">
<input name="arrayname[]" type="checkbox" value="1">
<input name="arrayname[]" type="checkbox" value="2">
<input name="arrayname[]" type="checkbox" value="3">
<input name="arrayname[]" type="checkbox" value="4">
If I do alert(myGetValue('simplename')) then it is ok and I get the value of input field. If I do alert(myGetValue('arrayname')) then it is NOT ok and I get 'undefined'.
What function must be in use? I want to get value of input tag with name 'arrayname' and send it to server via ajax. I can't use serialization or json. I want to get the same array like the $_POST even using ajax.
You can see my code in live example here
I want send checked values only.
My code to send data via ajax:
var fieldName = 'simplename';
var fieldValue = myGetValue(fieldName);
var formaData = new FormData();
formaData.append(fieldName, fieldValue);
$.ajax({
type: 'POST',
data: formaData,
processData: false,
contentType: false,
});
You can use .map() to get the values of the checked checkbox elements as below - it will return an array
function myGetValue(fieldName) {
var value = $('input[name="' + fieldName + '"]:checked, input[name="' + fieldName + '"]:not(:checkbox, :radio)').map(function () {
return this.value
}).get();
return value;
}
Demo: Fiddle
You cannot define name as a Javascript Array object. It's a regular string.
Try this:
var checked_boxes = [];
$('input[name^=arrayname]:checked').each(function(){
checked_boxes[checked_boxes.length] = $(this).val();
});
alert(checked_boxes);
I don't see it, so what i'm guessing is that you are looking for following behaviour:
check your console
function myGetValues(fieldName) {
return $('input[name=' + fieldName.replace(/(\[)|(\])/g, function (m) {
return "\\" + m;
}) + ']').map(function(){return this.value}).get();
}
console.log(myGetValues('arrayname[]'));
Try this
function myGetValue(fieldName)
{
var value;
value = $('input[name="'+fieldName+'[]"]').val();
//or
//value = $('input[name="'+fieldName+'[]:checked"]').val();
return value;
}
alert(myGetValue('arrayname'));
you field name is arrayname[] so u have to give [] along with the name and also selector should be $('input["name="arrayname[]"]')
Live Demo
Updated
$(document).ready(function() {
function myGetValue(fieldName)
{
var values = [];
$('input[name="'+fieldName+'[]"]:checked').each(function(i) {
values[i] = $(this).val();
});
return values.join(",");
}
alert(myGetValue('arrayname'));
});
Live Demo

Multiple checkboxes with unique ID's through ajax

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]
}
});
}
});

Categories