I have got this checkbox which has value 1.
<input type="checkbox" name="option_1" id="checkbox_1" value="1">
Also I use this method to make checked/unchecked it.
$('input[id^="checkbox_"]').not('#checkbox_all').click(function () {
$('#checkbox_all').prop('checked', false);
// Get 'VALUE' of the checkbox here
});
What I need is somehow get 'VALUE' of the clicked checkbox. So In that case it should be 1.
Any clue how do it could be done?
Thank you!
In your click method use this to get the value
$(this).attr("value");
$(this) is referencing to the object that has been clicked.
EDIT:
you could also use $(this).val(); but sometimes I had problems with elder versions of IE so I did recommend $(this).attr("value") in the first place.
<html>
<head>
</head>
<body>
<input type="checkbox" name="option_1" id="checkbox_1" value="1">
</body>
</html>
$('input[id^="checkbox_"]').not('#checkbox_all').click(function () {
$('#checkbox_all').prop('checked', false);
alert($(this).val());
});
http://jsfiddle.net/heten/
Working :)
I think you just need $(this).val(); in your click event.
Also, if you need to work with that value as an int later, use
var x = parseInt($(this).val(),10);
The val jQuery method should see you right.
$('#checkbox_all').val();
http://api.jquery.com/val/
Related
I have 'chain' of checkboxes (parent checkbox and childs), and problem is:
When first clicking on 'parent' checkbox it is working well, but after that when clicking on 'childs', the 'parent' checkbox then isn't doing what is supposed. Parent is checking/unchecking childs except the child which was pressed before.
Here is code:
JavaScript
checks_bind();
function checks_bind(){
$("#x_main").off('click');
$("#x_main").on('click',function(){
var obj = $(this);
var val = obj.is(':checked');
$("#checks").find("input[type='checkbox']").attr('checked',val);
});
}
HTML
<input id='x_main' type='checkbox'/>Main<br>
<p>--------------------------------</p>
<div id='checks'>
<input type='checkbox'/>1<br>
<input type='checkbox'/>2<br>
</div>
<p>--------------------------------</p>
<i>1 - Click on 1 or 2 <br>2 - Try <b>Main</b> checkbox. <br>
3 - Main checkbox isn't working</i>
jsfiddle example
And one more question:
Is it good to use .on('click.namespace') on checkboxes since it's working well? I can use .change() method, but I want to call .off('click.namespace') (or something to unbind) before .on() each time when calling the function.
As checked is a property, You need to use .prop() instead of .attr()
$("#checks").find("input[type='checkbox']").prop('checked', val);
Updated Fiddle, A good read .prop() vs .attr()
If you want to use .off() then its advisable to use namespaced event.
Try this: user 'prop' instead of attribute and you can check all or uncheck all as per checked condition of main check box.
Also, you can check the count of all checkbox to check /uncheck main checkbox. see below
Note: bind click handler when DOM is ready hence user $(document).ready or $(function(){})
$(function(){
$("#x_main").on("change", function(){
$("#checks").find("input[type='checkbox']").prop("checked",$(this).is(":checked"));
});
$("#checks input[type='checkbox']").on("change", function(){
var total = $("#checks").find("input[type='checkbox']").length;
var checked = $("#checks").find("input[type='checkbox']:checked").length;
$("#x_main").prop("checked",total==checked);
});
});
JSFiddle Demo
I am appending input fields to a div on a action. When i try to access the value inside the input field using $(this).val() i am just getting empty values.
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+value.response_code+' placeholder="Rs."></td>');
Depending upon the action there can be any number of input field appended to the div. I want to get the values entered on each field. when i tried to to get the value using this approach below, it didn't work out. But when i got the dynamically created id value and used in the place of $(this) it worked
$(document).keyup('.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
but this one works
$(document).keyup('#100520',function(){
console.log($('#100520').val());//works
console.log($('#100520').val());//works
});
Is there anything wrong with my approach ?
$(document).on('key-up','.custom-amount',function(){
console.log($(this).val()); //just logging empty
console.log($(this).attr('id')); //Logged undefined
})
Have you tried this?
$(document).on('keyup', '.custom-amount', function(){
console.log($(this).val());
console.log($(this).attr('id'))
});
Try the following code
$('#div').append('<td class = "fund-amount"><input type="number" class="custom-amount" id='+100520+' placeholder="Rs."></td>');
$('.custom-amount').keyup(function() {
console.log($(this).val()); // value
console.log($(this).attr('id')); // id
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id= "div">
</div>
Here is the working jsfiddle:https://jsfiddle.net/cm4rLvq1/
Calling $(this) in your handler is working as expected. Because you are handling events like this $(document).keyup your handler is invoked on the document element and not on the element itself, and therefor this refers to the document.
But when you supply event arg object to your handler function, you can use its property target which will refer to the element which triggered the event, like this:
$(function() {
$(document).on("keyup", ".custom-amount",function(e){
console.log($(e.target).val());
console.log($(e.target).attr('id'));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="custom-amount" id="some-id" />
I have some checkboxes like the following which are dynamically created.
<input type="checkbox" name="feature[]" value="9">
As you can see there is no id or class with it. And name property is of the type array. Now I can't detect the check event on these checkboxes. I need to detect the events and at the same time their values in which events have occurred.
I've checked several examples regarding this, but usually they all used class or id or name.But name is not in array type in those examples. I've tried with the name property to use, but couldn't manage. Please help.......
You can try this
$("input[name^='feature']").click(function(){
alert($(this).val());
});
use the attribute equals selector
$(document).on('change', 'input[name="feature[]"]', function(){
//do something
})
<input type="text" name="feature" value="123" />
$("input").click(function(){
var txt = $(this).val();
alert(txt);
alert($(this).attr("name"));
});
Try this once
I want to retrieve the text of a button that is clicked. I've read up on other suggestions for similar questions, but cant seem to get it to work. Here is the fiddle: http://jsfiddle.net/z3PKm/63/
Which currently isn't working. What am I doing wrong, or what should I do which is right?
Thanks!
I've tried to copy the following solution
alert($(this).attr("value"));
But it still doesn't work for me.
Use this:-
.text() will give you the text of the button as per your example. You are using button and not input type="button" If it was input type="button" then .val() would work.
function test(name) {
alert($(name).text());
}
Since you are using jquery you can use the click event
$('button').on('click',function(){
alert($(this).text());
});
The type of button that you are using are not using value, they are text.
Write this:
$(name).text()
This is how I would do it jQuery style.
This also show you how to use inputs and buttons and text() or val() as appropriate
$('.choose').on('click', function(){
var $this = $(this);
alert('text: '+$this.text()+'\nval: '+$this.val());
}); // end on click
You need to use alert($(name).text()); I have updated the jsfiddle with the same:
jsfiddle
I'm using this code:
$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked','checked')){
var switches = $(this).parent().find('.switch');
$(switches).attr('state','on')
$(switches).css({'left':"52px"});
$(switches).parent().css({'background-position': "147px -37px"});
}})
But somehow it sets all my checkboxes to checked="checked" Am I just stupid or is something else in the code interfering?
Thanks for your help :)
EDIT:
here is the HTML
<fieldset>
<input checked="checked" />
<label></label>
<div class="toggle_box">
<div class="switch" state="on"></div>
</div>
</fieldset>
<fieldset>
<input/>
<label></label>
<div class="toggle_box">
<div class="switch"></div>
</div>
</fieldset>
This piece of code is doing it...
$(this).attr('checked','checked')
...which returns the set in order for the cascade to work. An Object is always truthy in JavaScript.
Try...
this.checked
...which returns whether the checkbox is checked or not. If you wanted to do it the jQuery way, use $(this).is(':checked'). I wouldn't though, it's more verbose and less performant.
You're passing the checked value to attr() as the second argument. That causes it to be set. What's then returned is the jQuery object with that input, which is always a truthy value.
Your if condition should look like this (use the :checked pseudo-class instead):
if ($(this).is(':checked')) {
On a side note, your inner code can be refactored to this:
$(this).parent().find('.switch')
.attr('state', 'on')
.css({ 'left': "52px" })
.parent()
.css({ 'background-position': "147px -37px" });
If you have to use a cached variable (i.e. switches), you can, but don't wrap it in the jQuery function. It's a jQuery object itself, so needs not be wrapped.
The statement in the if statement is setting your checkboxes to checked. Particularly, this statement: $(this).attr('checked','checked').
Instead you can do if($(this).prop('checked'))
Read more about the jQuery Prop method.
Alternatively, you can do, this.checked which will access the DOM directly or with jQuery, $(this).is(':checked').
if($(this).attr('checked','checked')) would be your problem. You're assigning checked to each checkbox instead of checking if it's checked.
At first glance I see you're using .is('checked') when I beleive you want .is(':checked') The preceding colon being the difference.
UPDATE: I see you updated the code. The line
if ($(this).attr('checked', 'checked'))
is actually setting all 'input:checkbox' elements to checked. It should be:
if ($(this).is(':checked'))
$('fieldset input[type=checkbox]').each(function () {if($(this).attr('checked') == 'checked')){
var switches = $(this).parent().find('.switch');
$(switches).attr('state','on')
$(switches).css({'left':"52px"});
$(switches).parent().css({'background-position': "147px -37px"});
}})
There is actually a selector specifically for the checked boxes.
$('fieldset input[type=checkbox]:checked').each(function(){
var switches = $(this).parent().find('.switch');
$(switches).attr('state','on')
$(switches).css({'left':'52px'});
$(switches).parent().css({'background-position':'147px -37px'});
});
If you use that you won't have to do any of that logic by yourself.