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
Related
This question already has answers here:
Get checkbox value in jQuery
(21 answers)
Closed 5 years ago.
I have the following:
$('.checkbox').click(function () {
console.log(this);
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
Now where I do the console.log(this), it returns:
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
How do I get the input name (gender)? And whether the checkbox is checked out or not?
This answer here show you how to retrieve the element by name. However, the tricky part here is that your have brackets within the name itself. So, to get around this, you need to add quotes " around the name like in the following example below.
Once you have the element, you can simple do .prop('checked') to retrieve the current value.
$('.checkbox').click(function () {
console.log(this);
var theValue = $('input[name="gender[women]"]').prop('checked'); //<--HERE IS HOW YOU GET THE VALUE
console.log(theValue);
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
You can use the method find of jQuery to get the input object, then to check if the gender woman is checked you can use prop method of jQuery as well.
$('.checkbox').click(function () {
// to get the input
var $input = $(this).find('input');
// to check if the checkbox is checked or not
console.info($input.prop('checked'));
$.ajax({
type:'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
Use $(this).find(":checkbox") to get the checkbox. Then you can use .attr('name') to get the name, and .is(":checked") to get whether it's checked.
You shouldn't return false because that prevents clicking on the checkbox from actually changing the box's state.
$('.checkbox').click(function() {
console.log(this);
var checkbox = $(this).find(":checkbox");
var name = checkbox.attr("name");
var checked = checkbox.is(":checked");
console.log(name + "is " + (checked ? "" : "not ") + "checked");
$.ajax({
type: 'POST',
url: '/loadProducts',
data: {},
success: function(response) {
console.log(response);
$('.js-products').html(response);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ui checkbox checked">
<input type="checkbox" name="gender[Women]" tabindex="0" class="hidden">
<label>Women</label>
</div>
If I interpret the question correctly, you can pass an HTML string response to jQuery() to create a jQuery object from the HTML string, then call .attr("name") and .prop("checked"):
var input = $(response).find("input");
console.log(input.attr("name"), input.prop("checked"));
How do I get the input name (gender)? And whether the checkbox is
checked out not?
If you are trying to get the .name and .checked property values of clicked element you can call .querySelector() chained to this: .checkbox element, with selector "input[type=checkbox]"; .getAttribute() with "name" as parameter, .replace() with RegExp /^\w+\[|\]/g to get word within "[", "]"; and .checked property of the matched element returned by .querySelector()
$(".checkbox").click(function () {
var input = this.querySelector("input[type=checkbox]");
var _name = input.getAttribute("name").replace(/^\w+\[|\]/g, "");
var checked = input.checked;
console.log(_name, checked);
$.ajax(/* settings */);
});
What i have is a div with text inputs. What i want to do is send the div's HTML code to the server to be used on another page like so:
$.ajax({
url: 'process.php',
type: 'POST',
data: {
html: $("#form").html()
},
success: function (data) {
}
});
The thing is, if a user types in some data into the text inputs, that data is lost since its not part of the HTML. Is there a way i can force this data into the HTML? eg by using javascript to edit each input's value attribute?
Thanks in advance
Try the input event:
$(document).on('input', 'input.your_input', function() {
var that = $(this);
that.attr('value', that.val());
});
Inspect the input element and try type something:
$(document).on('input', '#textInp', function() {
var that = $(this);
that.attr('value', that.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="textInp" />
You can try sending the input values via parameters in the ajax function.
Try to run this snippet before making the call,
$("#form :text").attr("value",funcion(){
return $(this).val();
});
Instead of binding change event to all the input elements initially you can add the attribute before sending them to server.
You can try like this:
$("input").on('change', function() {
$(this).attr('value', $(this).val());
});
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
I'm using bootstrap typeahead and I'm wondering, how do I make it submit when clicking the enter button? In other words, if I typed "hello" into the typeahead input and pressed enter, how would I submit "hello"?
I've already made it so that the typeahead doesn't auto-select the first result.
This is my code:
<form method="POST" action="script.php">
<input name="typeahead_field" class="typeahead" data-provide="typeahead" autocomplete="off" type="text">
</form>
jQuery:
$('.typeahead').typeahead({
items: 10,
source: function (query, process) {
$.ajax({
url: 'typeahead.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
process(data);
}
});
},
highlighter: function(data) {
// code that returns each result
return html;
},
updater: function(data) {
// code that redirects the user if they click the selection
},
});
Please help!
Old question, but worth answering. Here is a possible solution:
$('.typeahead').on('keydown', function(e) {
if (e.keyCode == 13) {
var ta = $(this).data('typeahead');
var val = ta.$menu.find('.active').data('value');
if (!val)
$('#your-form').submit();
}
}
EDIT: First attempt was very naive :)
You need a submit button to enable submit on enter. You can hide the button with this CSS:
<input type="submit" style="position: absolute; left: -9999px">
(from https://stackoverflow.com/a/477699/759971)
works well, but doesn't highlight selection like mouse-over event does. Maybe this solution would work better as seems to encapsulate the gist of previous answer.
https://bwbecker.github.io/blog/2015/08/29/pain-with-twitter-typeahead-widget/
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]
}
});
}
});