jQuery's trigger method doesn't work properly on document ready - javascript

I have some functionality that changes an HTML element based on the choice of the radio input, and that's working fine. However, for the initial setup of the element, instead of duplicating the conditioning and the code again, it would be much shorter and clearer to just invoke the radio's trigger('change') method which then does all the work. This doesn't seem to work properly (in Firefox or Chrome). As much as I figure, it always treats the last radio in the document as the checked one.
A sample is here: http://jsfiddle.net/jydf5gby/
The initial color of the button should be red, but it comes up as blue. Why is that, and what is the solution?
HTML:
<p><input type="radio" name="radio" value="red" checked="checked"/> red</p>
<p><input type="radio" name="radio" value="blue"/> blue</p>
<button>button</button>
Javascript:
$(document).ready(function () {
$('input[name=radio]').change(function () {
if ($(this).val() == 'red') {
$('button').css('background', 'red');
} else {
$('button').css('background', 'blue');
}
}).trigger('change');
});

You're triggering the event on all the radio buttons, not just the selected one. Try:
$(document).ready(function () {
$('input[name=radio]').change(function () {
if ($(this).val() == 'red') {
$('button').css('background', 'red');
} else {
$('button').css('background', 'blue');
}
}).filter(":checked").trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="radio" name="radio" value="red" checked="checked"/> red</p>
<p><input type="radio" name="radio" value="blue"/> blue</p>
<button>button</button>

You can use it this way:
$(document).ready(function () {
$('input[name=radio]').change(function () {
$('button').css('background', $('input[name=radio]:checked').val());
}).trigger('change');
});
Fiddle
As you are triggering the event applied on the radio inputs so you can just apply the values of those radios directly as i put in the answer. This makes your code a bit smaller and you can save a bit of bytes.

You have incorrect selector to target checked radio button value after triggering change event. you need to use:
$('input[name=radio]').change(function () {
if ( $('input[name=radio]:checked').val() == 'red') {
$('button').css('background', 'red');
} else {
$('button').css('background', 'blue');
}
}).trigger('change');
Working Demo
Update - Optimized Answer by Rory McCrossan
$(document).ready(function () {
$('input[name=radio]').change(function () {
$('button').css('background', $('input[name=radio]:checked').val());
}).trigger('change');
});
Demo for optimized code

You are calling trigger for all the radio buttons. You just need to filter() them to the :checked one:
$(document).ready(function () {
$('input[name=radio]').change(function () {
if ($(this).val() == 'red') {
$('button').css('background', 'red');
} else {
$('button').css('background', 'blue');
}
}).filter(':checked').trigger('change');
});
See Fiddle here
You can also optimize your actual handler to just set the background-color to the current val():
$(document).ready(function () {
$('input[name=radio]').change(function () {
$('button').css('background', $(this).val());
}).filter(':checked').trigger('change');
});
Fiddle here

try this instead
$(document).ready(function () {
$('input[name=radio]').bind("change",function(){
if ($(this).val() == 'red') {
$('button').css('background', 'red');
} else {
$('button').css('background', 'blue');
}
});
$('input[name=radio]:first').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p><input type="radio" name="radio" value="red" /> red</p>
<p><input type="radio" name="radio" value="blue"/> blue</p>
<button>button</button>

Related

How to add / modify existing jquery functionality

I'm trying to disable/enable a button based on the checkbox, which I am unable to do. Here is the sample I worked on. For enabled and disabled, different buttons have to be used.
function toggleContinue() {
$(document).ready(function() {
$("#swpRequired").click(function() {
$("input,select").change(function() {
$("#disableContinue").attr("style", "display:inline-block");
$("#continueButton").attr("style", "display:none");
});
});
$("#swpRequired").click(function() {
$("input,select").change(function() {
$("#disableContinue").attr("style", "display:none");
$("#continueButton").attr("style", "display:inline-block;");
});
});
});
}
Try this. use prop method of jquery
function s()
{
if($("#a").prop('disabled')==false)
$("#a").prop('disabled','true')
else
$("#a").removeAttr('disabled')
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" onchange="s()" id="b"/>enable
<input type="button" value="click" id="a">
You could use attr() to disable/enable the button based on checkbox's value:
$(document).ready(function() {
$("#swpRequired").click(function() {
$("#continueButton").attr("disabled", this.checked);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="swpRequired" />
<button id="continueButton">continue</button>
You can use change event and take the help of disabled property of button.
Solution will be like:
$(document).on('change', "#checkbox", function()
{
if ($(this).prop("checked") == true)
{
$("#btn").prop('disabled',true)
}
else
{
$("#btn").prop('disabled',false)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox"/>enable
<input type="button" value="click" id="btn">

Checkbox check first time not working, after second time, it is OK

I am trying to create a checkbox with label. When user click the label, it will check if checkbox checked. The first time, I click the label, the box is checked, but no alert action. After I click the second time, it start to function, alert action happen. What did I do wrong. I have tried to use individual ID. Click not working either.
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name).click(function(){
if ($('#'+id_name +'_checkbox').prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
<script type="text/javascript">
$('label').click(function() {
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
});
</script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Also be sure, you have included jQuery library:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
And in new version of jQuery you can use insted of this:
if ($('#'+ $(this).attr('id') + '_checkbox').prop('checked') === false) {
alert('Checked');
}
else {
alert('Unchecked');
}
This piece of code:
// Just be careful, its inverted. Because, when you click label to check checkbox, the checkbox is still unchecked, and after alert will be checked...
if ($('#'+ $(this).attr('id') + '_checkbox').is(':checked') {
alert('Unchecked');
}
else {
alert('Checked');
}
Workind DEMO here in jsFiddle
Simplify things, you don't need each loop:
$('label').click(function() {
name=this.id;
if ($('#'+name+'_checkbox').prop('checked')) {
alert('Checked');
}
else{
alert('unchecked');
}
});
Demo: http://jsfiddle.net/fqvajvo1/2/
Script running correctly, script checks prop, but on label click -> checkbox is really unchecked, property changing comes later.
So, maybe in your case reverse logic could help (if you need alerts at all):
http://jsfiddle.net/fqvajvo1/4/ :)
I always use .is(':checked').I find it way more reliable
<script type="text/javascript">
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+id_name +'_checkbox').change(function(){
if ($(this).is(':checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
</script>
your click id is not complete name,so add complete name and call $(this) property will be ok...
var elements = { "emo_lol": "1", "emo_cool": "2", "emo_cute": "3" };
jQuery.each( elements, function( id_name, num ) {
$('#'+ id_name+'_checkbox').click(function(){
if ($(this).prop('checked')) {
alert('Checked');
}else{
alert('unchecked');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="emo_checkbox" id="emo_lol_checkbox">
<label id="emo_lol" for="emo_lol_checkbox" >LOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cool_checkbox">
<label id="emo_cool" for="emo_cool_checkbox" >COOL !</label>
<input type="checkbox" name="emo_checkbox" id="emo_cute_checkbox">
<label id="emo_cute" for="emo_cute_checkbox" >CUTE !</label>
Use .on to work for all events and all clicks on jQuery
Mainly used for dynamic creating elements
$(document).on('click','selector',function(){
});
Use class names for best options for grouped elements

checked radiobutton on checkbox change event

how we checked or unchecked all radiobutton on checkbox click.. if checkbox checked then all radiobutton also checked and vice versa.. it is not working properly
<input type="checkbox" id="Check" />SelectAll<br /><input type="radio"/>First<br />
<input type="radio"/>Second<br />
<input type="radio"/>Third<br />
<input type="radio"/>Fourth<br />
<input type="radio"/>Fifth</div>
<script>
var IsCheck = false;
$(document).ready(function () {
$("#Check").change(function () {
if (IsCheck == false) {
$("input[type=radio]").attr("checked", true);
IsCheck == true
}
else { $("input[type=radio]").attr("checked", false); IsCheck == false }
});
}); </script>
Take care you were just comparing operands instead of assigning to a variable in this statements:
IsCheck == true
^------ REMOVE ONE = so it's an assignment
Also, don't use .attr("checked", true); the correct form is:
$("input[type=radio]").attr("checked", 'checked'); //checking for jQuery < 1.6
And unchecking:
$("input[type=radio]").removeAttr("checked"); //unchecking for jQuery < 1.6
If you are using jQuery > 1.6 you can use the .prop() method with a boolean, which is similar to how you were trying to use it:
$("input[type=radio]").prop("checked", true); //checking for jQuery >= 1.6
$("input[type=radio]").prop("checked", false); //unchecking for jQuery >= 1.6
For jQuery 1.9 or higher use
$('input[type=radio]').prop("checked", true)
Otherwise try
$('input[type=radio]').attr('checked', 'checked');
Try this
$(document).ready(function () {
$("#Check").change(function () {
$("input[type=radio]").attr("checked", $("#Check").is(":checked"));
});
});
Demo
For your question, this could be the answer :
$("#Check").change(function () {
$("input:radio").prop("checked", this.checked);
});
Demo : http://jsfiddle.net/hungerpain/QSx29/
That said, radio buttons are not the best way of doing this. Its not semantically right. You can have only one radio button selected in a group. Try using checkboxes instead. Try to change you're markup to this :
<input type="checkbox" id="Check" />SelectAll
<br />
<input type="checkbox" />First
<br />
<input type="checkbox" />Second
<br />
<input type="checkbox" />Third
<br />
<input type="checkbox" />Fourth
<br />
<input type="checkbox" />Fifth</div>
And replace the JS code to this :
$("#Check").change(function () {
$("input:checkbox").prop("checked", this.checked);
});
Here's a demo : http://jsfiddle.net/hungerpain/QSx29/1/
You just need this
$("#Check").change(function () {
$("input[type=radio]").prop("checked", this.checked);
});
Demo ----> http://jsfiddle.net/kLnyD/
try this
http://jsfiddle.net/4u9sQ/
$("#Check").change(function () {
if ($(this).is(':checked')) {
$("input[type=radio]").prop("checked", true);
}
else { $("input[type=radio]").prop("checked", false); }
});

Once I remove an attribute I cant add it

I am trying to make a select all checkbox but when I deselect it and select it again it just doesn't select the boxes anymore. While it does work at the first time.
This is my code:
HTML:
<div id="Everything">
<input type="checkbox" id="all" />Select All
<br />
<br />
<div id="selectThese">
<input type="checkbox" id="First" />First
<br />
<input type="checkbox" id="Second" />Second
<br />
</div>
</div>
JS:
$(function () {
$("#Everything").on("click", "#all", function () {
var carStatus = $("#all").is(':checked');
if (carStatus == true) {
$("#selectThese input").attr("checked", "checked");
} else {
$("#selectThese input").removeAttr("checked");
}
});
});
Jsfiddle link: http://jsfiddle.net/Epsju/1/
You'll need to use prop() for that, and since it accepts a boolean to check and uncheck the element, you can use your variable directly, or just ditch the variable and use this.checked :
$(function () {
$("#Everything").on("change", "#all", function () {
$("#selectThese input").prop("checked", this.checked);
});
});
FIDDLE
http://jsfiddle.net/Epsju/6/
Use change also your fiddle uses #car, when it should use #all.
$(function () {
$("#Everything").on("change", "#all", function () {
$('#selectThese :checkbox').prop('checked', $(this).is(':checked'));
});
});
Try this:-
Demo
$(function () {
$("#Everything").on("change", "#all", function () {
$('#selectThese :checkbox').prop('checked', $(this).is(':checked'));
});
});
And viceversa
$('#selectThese :checkbox').on('change', function () {
$('#all').prop('checked', $('#selectThese :checkbox:checked').length == $('#selectThese :checkbox').length)
});

jQuery to check and uncheck checkboxes only fires once

I have a very simple requirement for my jQuery: to check a set of boxes if a radio button is checked, and to clear them all if another is checked.
The jquery works, however it only works once - that is if I click to check them all (all boxes check) and then click to clear them (all boxes clear), and then again click to check them all - there is no effect. Similarly if I manually uncheck some boxes then click to select all again, there is no effect.
jQuery
$('#all').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').attr('checked', false);
} else {
$('.country').attr('checked', true);
}
});
$('#none').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').attr('checked', true);
} else {
$('.country').attr('checked', false);
}
});
HTML
<div class="subselect">
<input type="radio" class="TLO" name="radio1" id="all" />Check All
<br />
<input type="radio" class="TLO" name="radio1" id="none" />Clear All
<br />
</div>
<br />
<br />
<div class="cselect" id="countries">
<input type="checkbox" class="country" />1
<br />
<input type="checkbox" class="country" />2
<br />
<input type="checkbox" class="country" />3
</div>
jsFiddle
http://jsfiddle.net/vsGtF/1/
Change your .attr() to .prop().
$('#all').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').prop('checked', false);
} else {
$('.country').prop('checked', true);
}
});
$('#none').on('change', function() {
if (!$(this).is(':checked')) {
$('.country').prop('checked', true);
} else {
$('.country').prop('checked', false);
}
});
jsFiddle example
You could also reduce this to just:
$('#all').on('change', function () {
$('.country').prop('checked', $(this).is(':checked'));
});
$('#none').on('change', function () {
$('.country').prop('checked', !$(this).is(':checked'));
});
jsFiddle example
As the docs for .attr() state:
As of jQuery 1.6, the .attr() method returns undefined for attributes
that have not been set. To retrieve and change DOM properties such as
the checked, selected, or disabled state of form elements, use the
.prop() method.
I know that this has been duped alot on here but I did miss something, I had:
id = $(this).attr('id');
if($('#checkbox_' + id).prop('checked')){
$('#checkbox_' + id).attr('checked', false);
} else {
$('#checkbox_' + id).attr('checked', true);
}
And as mentioned above ALL cases of attr need swapping for prop()
if($('#checkbox_' + id).prop('checked')){
$('#checkbox_' + id).prop('checked', false);
} else {
$('#checkbox_' + id).prop('checked', true);
}
Hope that helps somebody...

Categories

Resources