Check if checkbox is checked using next() in JQuery - javascript

I need to check if a checkbox next to a textbox is checked or not, but the result I'm getting from that condition in my code is always true, so that's wrong.
I've made some tests using the next() method from jQuery. I'm pointing to the next checkbox close to the textbox, which is working fine.
This code is always returning true, whether the checkbox is checked or not:
if ($(this).next('.isFileSelected:checkbox:checked')) {
//do some other stuff...
}
I tried these changes too, but I'm getting the same results:
if ($(this).next('input:checkbox:checked')) {
//do some other stuff...
}
How can I accomplish this using jQuery or pure JavaScript code?

You're looking for the prop() attribute checked:
if ($(this).next('.isFileSelected:checkbox').prop('checked')) {
// Checked
}
Or, alternatively, you can use .is() to check for the :checked pseudo-selector:
if ($(this).next('.isFileSelected:checkbox').is(":checked")) {
// Also Checked
}
Hope this helps! :)

Related

Select checkbox if not selected with Protractor

I try execute in protractor following scenario:
Find checkbox
Check if it is selected
If yes - go further
If not - select it and go further
For some reason isSelected() function is not working with my checkbox, but I've found some solution. Below code works correctly:
expect(checkbox.getAttribute('aria-checked')).toEqual('false')
It checks some checkbox attribute which is 'false' if not selected and 'true' if selected. (but as a string)
Now the main question. How to write an 'if / else' statement to make it works?
I tried something like that:
if (expect(checkbox.getAttribute('aria-checked')).toEqual('false')) {
checkbox.click();
}
But it always clicks on checkbox no mater if it was selected or not. I've tried also:
if (checkbox.getAttribute('aria-checked').toEqual('false')) {
checkbox.click();
}
But there is an error which says "It's not a function".
Could anybody help me with that?
You can use the below method to solve the problem.
Before clicking any any checkbox, check for the value of aria-checked attribute, if its true don't do anything. Otherwise click on it.
checkBoxElement.getAttribute("aria-checked").then(function(isChecked){
if(isChecked == "false") { //getAttribute will return the value as string.
checkBox.click();
}
})
You could try to make some helper function:
function setCheckBoxTo(locator, value){
var checkbox = element(locator);
checkbox.isChecked().then(function(selected){
if(selected !== value){
checkbox.click();
}
}
}
where [value is true/false]

how to loop through gridview using jquery and check if any checkbox is checked

I am developing jquery based application. I have one asp.net gridview with checkboxes in every row. I want to check if any of the checkboxes checked or not. I am looping through gridview rows and checking any checkbox is checked or not as below.
var ResultArrayFirst = [];
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').prop('checked', true))
{
ResultArrayFirst.push($(this).val());
}
});
alert(ResultArrayFirst);
My above code does not works. As soon as above code is executed, all checkboxes will check. I am not sure what i Am missing here. Any help would be appreciated. Thank you.
To check if a checkbox is checked, use this:
if (checkbox.is(':checked')) {
// Do your stuff
}
So, change your code like this:
if ($(this).closest('tr').find('input[type="checkbox"]').is(':checked'))
{
ResultArrayFirst.push($(this).val());
}
You can use :checked selector of jquery
$('#<%= gdvRegretletter.ClientID %> input[type="hidden"]').each(function () {
if ($(this).closest('tr').find('input[type="checkbox"]').is(":checked"))
{
ResultArrayFirst.push($(this).val());
}
});
Just give a class to checkbox as example chk and than use .map() instead of each loop it will get items in an array please find below single line of code to achieve
var selected = $(".chk:checked").map(function(i,el){return el.value;}).get();
As well as if you wants to just check if any check boxes is checked or not you can do as below it will return a bool value
$(".chk").is(":checked")

Form Value with jQuery and POST - Single Checkbox

This successfully returns a result, but the result is useless to me. In the php file, I have this simple code: var_dump($_POST['rememberMe']);
Whether the checkbox is marked or not, the result is string(2) "on". How do I get a result that changes based on whether the checkbox is marked?
Thanks.
Remember Me: <input type="checkbox"
id="remember">
<div id="result" style="margin-top:20px;">
<script>
$("#submit").click(function(){
submitLogin();
});
$("#password").keyup(function (f){
if (f.keyCode == 13) {
submitLogin();
}
});
function submitLogin(){
$.post("php/test.php", {
loginUsername:$('#username').val(),
loginPassword:$('#password').val(),
rememberMe:$('#remember').val()
}, function(data){
$("#result").text(data);
});
}
</script>
The value attribute is mandatory for checkboxes and defaults to on. This applies whether the checkbox is checked or not, the value is always the same. What you want is to check the state of the checkbox (not its value).
$('#remember').prop("checked")
Btw, this is way faster than .is(:checked), see http://jsperf.com/prop-vs-ischecked/5 for a comparison.
It's better if you serialized the form that you are sending via post $("form").serialize(); Then, in the target page, just check if $_POST['rememberMe'] exists. (If the checkbox isn't checked, isset for $_POST['rememberMe'] will be equal to false)
This:
rememberMe:$('#remember').val()
Needed to become:
rememberMe:$('#remember').is(':checked')

check is radio element checked in ajax response

I have ajax response containing two radio element.i want to check if radio element is checked in response.
I m using below code to check radio status but not working.
$('#input[type=radio]').each(function(){
alert($(this).attr('checked'));
});
as i know this is not working due to ajax response. but how to fire js code to check even in ajax resoponse.
any help would be much appreciate.
try this:
$(document).find('input[type="radio"]').each(function(){
if($(this).is(':checked')){
//your code
}
});
Try this
$('#input[type=radio]').each(function(){
if($(this).is(':checked')){
}
});
use prop
$('input[type=radio]').each(function(){
alert($(this).prop('checked'));
});
and #input only if your radio have id="input". if you want check all radio, could be only
input[type=radio]
as the example
Your issue is your selector which contains # for id:
$('#input[type=radio]')
//-^------------------------# is used to select an id not the tags
try this:
$('input[type="radio"]').each(function(){
alert(this.checked); // returns "true" if checked/ "false" if not checked
});

How to detect if a certain radio button is checked with jQuery?

I'm using the jQuery Validate plug-in and need to require a field if a certain radio button is checked. How can I determine if a certain country is selected?
For example, if the Canada radio button is checked, then require this field. This isn't right, but it's something along these lines:
depends: function(element) {
return $("input[name='country'],[value='ca'],:checked")
}
UPDATE:
I'm using #Tatu Ulmanen's code, however I'm receiving the following error after clicking outside of one of the fields that should be required when "Canada" is checked. Any ideas?
province: {
depends: function(element) {
return $("input[name='country'][value='ca']").is(':checked')
}
},
$.validator.methods[method] is
undefined [Break On This Error]
eval(function(p,a,c,k,e,d){e=function(...x5b|trigger|x21|x23'.split('|'),0,{}))
$("input[name='country'][value='ca']").is(':checked');
You can use the .is() method:
$("input[name='country'][value='ca']").is(':checked');
$("input[name='country'],[value='ca']").is(':checked');
here's a way:
if ($('#id').is(':checked')) {
alert('button is checked');
}
As well as using .is(), jQuery 1.6 introduced .prop(), see
http://api.jquery.com/prop/ for details.

Categories

Resources