Display value from checkbox in console.log - javascript

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

Related

Jquery changevalue or arraypush when checkbox are checked

I have input like this(Looping input form) :
<input id="check_<?php echo $value->id; ?>" value="<?php echo $value->id; ?>" type="checkbox" checked class="check_table get-report-filter">
and hidden input like this :
<input class="hiddenakun" type="hidden" name="hiddenakun" />
this my jquery :
var akun = [];
$('.get-report-filter').each(function() {
$('.get-report-filter').on('click', function() {
akun.push($(this).val());
}
});
my point is, I want to push each array data checked to .hiddenakun, but my code not working, I know it cause every time I write wrong code, datepicker wont work.
You can use .map() along with .get() to create an array of :checked checkboxes values
var akun = $('.get-report-filter:checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
If you want to set the value of checked event, then bind an event handler
var elems = $('.get-report-filter');
elems.on('change', function() {
var akun = elems.filter(':checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
});
Note, datepicker wont work. it's due to syntax error.
Try this:
$('.get-report-filter').each(function(){
if($(this).is(':checked'))
{
akun.push($(this).val());
}
});
// It will push the checked checkbox values to akun
You need more strict checker finder. Not all checkbox, but checked checboxes. For this purpose you can use pseudo class finder
$('.get-report-filter:checked').each
Find info here
https://api.jquery.com/checked-selector/

passing primary key instead of attribute on submit

I have an input tag that takes a users input that calls an AJAX dynamically outputs suggestions from my database. The issue is I want to store the primary key associated with that attribute.
I have figured out a way set it to the primary key when the user selects a value; however I would rather only have the attribute displayed on the front end. Essentially what I was thinking about doing was using the option tag and setting the value to the primary key, but after reading the documentation for it, that doesnt look like it would work.
HTML:
<input type="text" id = "zip_id" class="tftextinput2" autocomplete = "off" name="zip" placeholder="Zip Code" onkeyup = "autocompleter()">
<ul id = "zip_codes_list_id"></ul>
JS:
function autocompleter()
{
var min_length = 1; // min caracters to display the autocomplete
var keyword = $('#zip_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#zip_codes_list_id').show();
$('#zip_codes_list_id').html(data);
}
});
} else {
$('#zip_codes_list_id').hide();
}
}
// set_item : this function will be executed when we select an item
function set_item(item)
{
// change input value
$('#zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
PHP:
<?php
//connect to db here
$keyword = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM zip_codes WHERE zip LIKE (:keyword) ORDER BY zip_codes_id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs)
{
// put in bold the written text
$zip = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['zip']);
// add new option
// echo '<li onclick="set_item(\''.str_replace("'", "\'", $rs['zip']).'\')">'.$zip.'</li>'; (this one only passes the attribute)
echo '<li " onclick="set_item(\''.str_replace("'", "\'", $rs['zip_codes_id']).'\')">'.$zip.'</li>';
//this one passes the attribute but changes the displayed value to the primary key.
}
?>
As you can see from the PHP file, what I am trying to do is pass in the primary key value but keep the displayed value the attribute. I am not sure how to do that. Should I be using the UL tag?
The issue in your code is that you try to the zip_id value for the input, but this input contains the zip field value - I assume it's the textual representation. There are a few ways how you could save the zip_id on the frontend - either store it in the model (if you're using some MVC framework, but I gues it's not the case) or simply add a hidden input field:
<input type="hidden" id="actual_zip_id" name="zip_id">
And
function set_item(item)
{
// change input value
$('#actual_zip_id').val(item);
// hide proposition list
$('#zip_codes_list_id').hide();
}
UPD
Speakng about the entire idea of autocompleting zip codes, it looks pretty nasty, as pointed by Darren Gourley (check the comments).
So you'd rather validate it with regex first, and then do your db-related logic like that:
$('#zip_id').on('change', function(){
// your stuff
})
Best regards, Alexander

Javascript populates input, but not span?

I am using Select2 dropdown menu to get data from database threw ajax and json/php.
The option i make will then populate some input fileds for editing the database.
I use (This field get´s populated ok):
<input type="text" class="form-control" name="valt_element_id" id="valt_element_id" placeholder="Objekt ID" />
But on some field i just want to show the data, not to be edited.
I figured to use:
<span id="valt_element_id"></span>
But this span code won´t work!
Why?
JS:
$(document).ready(function(){
var valtObjektElement = $('#valj_objekt_element');
$('#valj_objekt_element').select2({
ajax: {
url: "valj_objekt_element.php",
dataType: 'json',
data: function (term, page) {
return {
q: term
};
},
results: function (data, page) {
return { results: data };
}
} // Ajax Call
}); // Select2
// Start Change
$(valtObjektElement).change(function() {
var ElementId = $(valtObjektElement).select2('data').id;
var ObjektNummer = $(valtObjektElement).select2('data').text;
$('#valt_element_id').val(ElementId);
$('#valt_objekt_nummer').val(ObjektNummer);
}); //Change
}); //Domument Ready
There is no value attribute for span. You should either use text or html.
Replace
$('#valt_element_id').val(ElementId);
with
$('#valt_element_id').text(ElementId);
Using javascript:
document.getElementById("valt_element_id").innerHTML = ElementId;
Or jQuery:
$('#valt_element_id').html(ElementId);
You mentioned:
But on some field i just want to show the data, not to be edited . Why not use readonly attribute in input rather than replacing it with a span ?

How to put alert value to element

in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.

How to pass multiple checkboxes using jQuery ajax post

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

Categories

Resources