<input type="checkbox" value="<?= $servicii_content[$j]['title'] ?>" name="check_list" id="check" />
i get multiple values from the table above if the checkboxes are checked with jQuery, like this.
var temp = $("input:checkbox[name=check_list]:checked").map(function(){
return $(this).val();
}).get();
alert(temp);
I get the alert with the correct checked values!
I post them later here:
url: "/servicii_email.php",
type: "POST",
data: {
families: temp,
How can I get the elements of "families" eg.:Family1, Family2, Family3, etc. - which are checked to post it to the php file? What is the correct way to do that?
For example, you can just make string with name of variable and it value. That will be something like this Family1=true,Family2=false
On server you just need to split string by , and after that split by =, you will get two dimensional array {{Family1, true}, {Family2, false}}
You can make use of serializeArray() method:
var temp = $("input:checkbox[name=check_list]:checked").serializeArray();
// outputs:
// [{name:"check_list", value:"theValue"},......n]
Related
I am building a form that passes a set of numbers in form of an array to a variable as seen below
var users=["1","2"];
the main purpose of this is to then make an Ajax request with these numbers and get their corresponding content in my database which I then pass to their respective divs, please see below
var users=["1","2"];
var async_request=[];
var responses=[];
for(i in users)
{
// you can push any aysnc method handler
async_request.push($.ajax({
url:'back.php', // your url
method:'post', // method GET or POST
data:{user_name: users[i]},
success: function(data){
console.log('success of ajax response')
responses.push(data);
}
}));
}
$.when.apply(null, async_request).done( function(){
// all done
console.log('all request completed')
console.log(responses);
$( '#responses' ).html(responses[1]);
$( '#responses1' ).html(responses[0]);
});
This works perfectly.
But now I want to make some adjustments to my solution specifically
Im looking to replace the method of passing the numbers to the variable users
from
var users=["1","2"]; // Im looking to replace the method
to this
var users = $('[name="tom[]"]').val(attachArray);
<input type="text" name="tom[]" value="1" /><br>
<input type="text" name="tom[]" value="2" /><br>
but I am unable to get the the ids from the two textfields and then pass to my database using my Ajax script as I did before with this
var users=["1","2"];
You mean
const arr = ["1", "2"]
$('[name^=tom]').val(function(i) {
return arr[i]
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="tom[]" value="" /><br>
<input type="text" name="tom[]" value="" /><br>
or
$('[name^=tom]').each(function() {
async_request.push($.ajax({
url:'back.php',
method:'post',
data:{user_name: this.value },
You forgot to use input key value :
var users = $('input[name="tom[]"]').val();
Well this is probably an easy question but I've been figure this one out. I would like to display the value of a checkbox in the console.log so I can use it to fire a AJAX call. But the values of every checkbox is the same (the first one).
I have spent some time on google and I for what I read there, I should put the checkbox in an array. But I can't seem to get it to work. Here is my code at the moment.
<!-- Custom taxonomy checkboxes -->
<?php
$taxonomy = 'locatie';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
foreach($terms as $term) {
$name = $term->name;
echo "<div class='col-xs-12 col-sm-12 col-md-2 col-lg-2'>
<form id='location'>
<input class='checkIt' type='checkbox' value='".$name."' name='location' id='".$name."_id'> ".$name."
</form>
</div>";
}
}
?>
<!-- /Custom taxonomy checkboxes -->
$('.checkIt').change(function(e) {
var value = $(this).val();
$.post('../wp-content/themes/mysite/includes/search-team-wp.php',{value:value}, function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value);
});
});
});
Everything works, even the AJAX call, except the console.log output so I can't sent different values trough the AJAX call. Any help would be really nice!
use
var value = $(this).val();
The issue is because you're selecting all .checkIt elements in the selector within the change event. When you call val() on a collection of elements jQuery will only return the value of the first one.
To fix this you only need to get the value of the element that raised the change event. To do that, use the this keyword within the handler:
var value = $(this).val();
Try ajax call as given below,
var value = $(this).val();
$.ajax({
type: "POST",
url:'../wp-content/themes/mysite/includes/search-team.php',
dataType: "json",
data: {
value:value
},
success:function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value)
}
})
You can use
$('.checkIt').is(':checked')
This will give you the checked box.
Jquery.val() for checkbox always return ... the value you defined, despite of the checked state.
If you want something like when check return value, else return undefined you should do: value = $('.checkIt:checked').val();
I need to pass two different values back as the result from one checkbox. I tried an object, but the result was undefined (the code works with one value).
' <input type="checkbox" id="cat" value="'+{value1: data.blue, value2: data.red} +'"/>'
result.value1 is always undefined, whereas result works for just a string.
What is the best way to do this using javascript/jquery.
You can use attr for add more values, for example:
<input type="checkbox" id="cat" data-value1="blue" data-value2="red" value=""/>
Get values using jQuery, use:
$("#cat").data("value1");//return 'blue'
$("#cat").data("value2");//return 'red'
Result: https://jsfiddle.net/cmedina/a0ya5bwp/
Why not create a string with a separator
Something like
value1 \t value2
And you just have to search for this separator and cut the string to get your 2 differents values?
You can stringify the object and put that value on the input as a data attribute, in the input change handler, parse the string to JSON.
HTML
<input type="checkbox" id="cat" name="cat">
<label for="cat">Cat</label>
Javascript
var input = document.getElementById('cat');
var testValue = {value1: 'blue', value2: 'red'};
input.setAttribute('data-value',JSON.stringify(testValue));
input.addEventListener('change', function(event) {
var inputValue = JSON.parse(event.target.getAttribute('data-value'));
console.log(inputValue);
});
Demo : JSFiddle
it looks like you have a spelling mistake : vaule1 should be value1
So my php needs 2 values, operation => string and data => array. The following is the form (dynamically generated inputs) :
<form method="post" action="/operations.php">
Title: <input type="text" value="valuehere" name="data[title]">
.
.
.
Description: <textarea name="data[description]"></textarea><br>
<button class="btn janitor_edit" type="submit">Edit Media</button>
<input type="hidden" value="operateMePls" name="operation">
<input type="hidden" value="254" name="data[id]">
</form>
And now I have to create an array from all data[xyz] in the form, but I'm having trouble finding a way to do so. The closest I've come to was doing like so: link
I must store the array as key/values, no other way, so I can ajax_request = { operation: operation_input, data : input_array_data };.
Oh, and the form works as expected when submiting "normaly" trought POST.
If the form works by itself, then let jQuery take care of it converting the data into a form suitable for XHR for you.
data: $('#your_form').serialize();
I've used an object instead of an array. When you json_decode in PHP, pass "true" as your second argument, and the data will come out as an array. I think this is what you wanted. Please comment if you were looking for something different.
$(".janitor_edit").click(function () {
var data = {};
data.operation = $("input[name='operation']").val();
data.data.id = $("input[name='data\\[id\\]']").val();
data.data.title = $("input[name='data\\[title\\]']").val();
data.data.description = $("input[name='data\\[description\\]']").val();
});
How to pass multiple checkboxes using jQuery ajax post
this is the ajax function
function submit_form(){
$.post("ajax.php", {
selectedcheckboxes:user_ids,
confirm:"true"
},
function(data){
$("#lightbox").html(data);
});
}
and this is my form
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
From the jquery docs for POST (3rd example):
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just came across this trying to find a solution for the same problem. Implementing Paul's solution I've made a few tweaks to make this function properly.
var data = { 'venue[]' : []};
$("input:checked").each(function() {
data['venue[]'].push($(this).val());
});
In short the addition of input:checked as opposed to :checked limits the fields input into the array to just the checkboxes on the form. Paul is indeed correct with this needing to be enclosed as $(this)
Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.
var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
data.push($(this).val());
});
Here's a more flexible way.
let's say this is your form.
<form>
<input type='checkbox' name='user_ids[]' value='1'id='checkbox_1' />
<input type='checkbox' name='user_ids[]' value='2'id='checkbox_2' />
<input type='checkbox' name='user_ids[]' value='3'id='checkbox_3' />
<input name="confirm" type="button" value="confirm" onclick="submit_form();" />
</form>
And this is your jquery ajax below...
// Don't get confused at this portion right here
// cuz "var data" will get all the values that the form
// has submitted in the $_POST. It doesn't matter if you
// try to pass a text or password or select form element.
// Remember that the "form" is not a name attribute
// of the form, but the "form element" itself that submitted
// the current post method
var data = $("form").serialize();
$.ajax({
url: "link/of/your/ajax.php", // link of your "whatever" php
type: "POST",
async: true,
cache: false,
data: data, // all data will be passed here
success: function(data){
alert(data) // The data that is echoed from the ajax.php
}
});
And in your ajax.php, you try echoing or print_r your post to see what's happening inside it. This should look like this. Only checkboxes that you checked will be returned. If you didn't checked any, it will return an error.
<?php
print_r($_POST); // this will be echoed back to you upon success.
echo "This one too, will be echoed back to you";
Hope that is clear enough.
This would be better and easy
var arr = $('input[name="user_ids[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The following from Paul Tarjan worked for me,
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
but I had multiple forms on my page and it pulled checked boxes from all forms, so I made the following modification so it only pulled from one form,
var data = { 'user_ids[]' : []};
$('#name_of_your_form input[name="user_ids[]"]:checked').each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
Just change name_of_your_form to the name of your form.
I'll also mention that if a user doesn't check any boxes then no array isset in PHP. I needed to know if a user unchecked all the boxes, so I added the following to the form,
<input style="display:none;" type="checkbox" name="user_ids[]" value="none" checked="checked"></input>
This way if no boxes are checked, it will still set the array with a value of "none".
function hbsval(arg) {
// $.each($("input[name='Hobbies']:checked"), function (cobj) {
var hbs = new Array();
$('input[name="Hobbies"]:checked').each(function () {
debugger
hbs.push($(this).val())
});
alert("No. of selected hbs: " + hbs.length + "\n" + "And, they are: " + hbs[0] + hbs[1]);
}