Despite its age, jQuery is still a popular library for manipulating the DOM. In this article, we’ll look at some tips for working with jQuery.
Return the Response from an Ajax Call
Synchronous Ajax calls aren’t recommended since it blocks the other parts of the app from running.
This is because JavaScript is single-threaded.
To make a synchronous Ajax call with jQuery, we can set the async
option to false
.
For example, we can write:
const foo = () => {
const jqXHR = $.ajax({
//...
async: false
});
return jqXHR.responseText;
}
It’s better to make an async Ajax call with it instead.
For instance, we can write:
const login = () => {
return $.ajax({
url: '/login',
data: {
username: $('#username').val(),
password: $('#password').val()
},
type: 'POST',
dataType: 'json'
});
}
This returns a deferred object.
So we can run code after this is done by calling done
and passing a callback in it.
To handle errors, we can call fail
and pass a callback to that.
So we can write:
const login = () => {
return $.ajax({
url: '/login',
data: {
username: $('#username').val(),
password: $('#password').val()
},
type: 'POST',
dataType: 'json'
});
}
login()
.done((res) => {
//...
})
.fail((err) => {
//..
});
Check Whether a Checkbox is Checked in jQuery
We can use the is
method to check for the checked
pseudoelement.
For instance, we can write:
$("#isSelected").is(':checked')
We get the checkbox with the ID isSelected
and check for the checked
pseudoelement.
Also, we can use the prop
method to do the same thing:
$('#isSelected').prop('checked')
The attr
method also works:
$("#isSelected").attr("checked")
To watch for changes, we can write:
$("#checkbox").change(function() {
if($(this).prop('checked')) {
alert("checked");
} else {
alert("unchecked");
}
});
We watch for changes with the change
method.
Then we use the prop
method to check for the checked
attribute.
There’s also the toggle
method:
$("#checkbox").toggle(
$("#selected").prop("checked")
);
We watching for toggling of the checkbox with the toggle
and get the checked
property.
Setting the Checked State for a Checkbox with jQuery
There’re several ways to get toggle the checkbox.
For instance, we can use the prop
method:
$('#checkBox').prop('checked', true);
to toggle the checkbox to be checked.
And we can write:
$('#checkBox').prop('checked', false);
to make it unchecked.
We can also set the checked
property.
For instance, we can write:
$('.checkBox')[0].checked = true;
and:
$('.checkBox')[0].checked = false;
to make it checked and unchecked respectively.
There’s also the attr
method to make the checkbox checked or unchecked.
For instance, we can write:
$('.checkBox').attr('checked', true);
and:
$('.checkBox').attr('checked', false);
to make our checkbox with the class checkBox
checked or unchecked.
attr
is deprecated.
We can use the prop
method to set the checked
value:
$(".checkBox").prop('checked', true);
and:
$(".checkBox").prop('checked', false);
We can also uncheck a checkbox by calling removeAttr
:
$('.checkBox').removeAttr('checked')
Also, we can trigger a click event for the checkbox:
$("#checkBox").click();
And we can write:
$('.checkBox').attr('checked', 'checked');
to set the 'checked'
value to be checked.
event.preventDefault() vs. return false
jQuery event handlers can have e.preventDefauly
and return false
called.
For instance, we can write:
$('a').click(function (e) {
// ...
e.preventDefault();
});
or:
$('a').click(function () {
// ...
return false;
});
return false
inside a jQuery event handler does the same thing as e.preventDefault()
and e.stopPropagation
together.
e.preventDefault()
prevents the default behavior of the event from occurring.
e.stopPropagation()
prevents the event from bubbling up.
In non-jQuery event handlers, return false
doesn’t stop the event from bubbling up.
Upload Files Asynchronously
To upload a file with jQuery, we can set the data
property to the FormData
instance.
For instance, we can write:
$.ajax({
url: '/upload',
type: 'POST',
data: new FormData($('#formWithFiles')[0]),
processData: false,
contentType: false
})
.done(() => {
console.log("success");
})
.fail(() => {
console.log("error");
});
formWithFiles
is an ID of a form with a file input.
We just set it as the value of data
.
And we set the url
and type
of the request.
processData
set to false
prevents it from converting the form values to a query string.
contentType
set to false
tells it not to set the data type.
Conclusion
We can check for the checked value of a checkbox in various ways. Also, we can toggle it on and off in multiple ways. Uploading files can be done by setting the form data.