How do i make a checkbox fire a function? - javascript

I have a checkbox inside a <label> and i want that checkbox, when checked or unchecked, to trigger a function.
I attached a onchange trigger to the checkbox but in IE6 the trigger only fires after the focus is turned away from the checkbox, while in FF3 and Chrome it fires right away.
I removed the onchange trigger and attached a onclick trigger to the <label> but now the trigger fires twice when the label is clicked once (does enyone know why?)...
My question is: how can i make the checkbox fire a function when it is checked or unchecked by a click on it or on it's label.
Thanks.

Assuming you don't want a fancy ASP / JQuery solution, just attaching the function to the onClick of the checkbox itself should work fine.
(Of course, you'll need to inspect the current state of the checkbox in the function if you want to have the function behave differently based on if the checkbox is checked or not.)

As "Electrons_Ahoy" says, you should be able to simply attach an onclick handler to the checkbox element. This handler should also get called when the user clicks on the label instead of the checkbox.
HTML:
<label><input type="checkbox" id="myCheckbox" />My Checkbox</label>
JavaScript:
document.getElementById("myCheckbox").onclick = function() {
if (this.checked) {
alert("Checkbox was checked.");
}
else {
alert("Checkbox wasn't checked.");
}
};
The above code seems to work correctly in Safari 4 and Firefox 3 (I'm not sure how it would work in IE).
Steve

not sure if using Prototype is an option for you, but if so you'd do it this way (this assumes Prototype 1.6. Code written against earlier versions will be slightly different):
HTML:
<label><input type="checkbox" id="myCheckbox" />My Checkbox</label>
JS:
$('myCheckbox').observe('click', function(cbox)
{
var cbox = $('myCheckbox');
//do work in here.
//cbox is the DOM element that represents your checkbox
}
);
Doing it this way is slightly nicer than the "naked" JS approach (in my opinion), and it's a bit safer too.

Thank you for all your responses.
#Electrons_Ahoy and #Steve: You are tight. My problem was that i was putting the checkbox inside the labe, so i did the folowing:
I took the checkbox outside the label, put the onclick trigger on the checkbox only and it works fine.
I also figured out why the trgger fired twice when the checkbox was inside the label and the onclick trigger was on the label :
It was because when i clicked the label a click on the checkbox was simulated and the checkbox being inside the label the click was simulated on the label, duuuuuhhh :)

You probably need to turn on the autopostback property:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.checkbox.autopostback.aspx
<asp:CheckBox id="checkbox1" runat="server"
AutoPostBack="True"
Text="Include 8.6% sales tax"
TextAlign="Right"
OnCheckedChanged="Check_Clicked"/>

Related

how to make action after clicking a radio button on a site made by html, css

I have made a a site using html and css where users use radio buttons to make choice now I am looking forward to putting action to the choices made. If a user chooses an option and action should be made, however I do not know how to put action to a radio button action. I require help please!
You could use the addEventListener method. So, say you have a the following HTML:
<input type="radio" name="myRadio" value="1">
Then you can use this code:
var radio = document.getElementsByName("myRadio")
radio.forEach(r => r.addEventListener('change', myFunc))
You can also bind the function in your HTML, using the onchange attribute:
<input type="radio" name="myRadio" value="1" onchange="myFunc()">
You can see more details in previous questions that seem very similar to yours:
onchange not working with radio button
OnChange event handler for radio button (INPUT type="radio") doesn't work as one value
Radio Input onChange only fires once?
Also, as suggested by #devdgehog, you could give a look at the documentation on:
addEventListener: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
inputs's onchange: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/change_event

JQuery selector to negate specific HTML elements within a parent element

I have HTML label structures generated by a JQuery multiselect dropdown library as shown:
<label for="ui-multiselect-selectedSku-option-1"><input id="ui-multiselect-dropdown-option-1" type="radio" value="DropDownVal1"><span>DropDownText1</span></label>
<label for="ui-multiselect-selectedSku-option-2"><input id="ui-multiselect-dropdown-option-2" type="radio" value="DropDownVal2"><span>DropDownText2</span></label>
My requirement is: except the input element, whenever the user clicks on anywhere else in the
<label></label>
(including the label) area,I need to do event.preventDefault(). I have tried as
$(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"]',function(event){
event.preventDefault();
});
But the above handler gets triggered even when I click on the <input> within the label as well(which is obvious and I know that!)
How do I write a JQuery selector for to filter this.
The best thing would be to have the input out of the label... But:
I do not have control over this markup structure... (your comment on another answer)
You can use .stopImmediatePropagation() on the <input> elements... So the click event won't bubble up to the label.
See below... Try a click a label, then on a radio.
$(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"]',function(event){
console.log("Clicked on a label");
event.preventDefault(); // Don't know if that is useful...
});
$(document).on('click', 'label[for^="ui-multiselect-selectedSku-option-"] input',function(event){
console.log("Clicked on a radio input");
event.stopImmediatePropagation();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="ui-multiselect-selectedSku-option-1"><input id="ui-multiselect-dropdown-option-1" type="radio" value="DropDownVal1"><span>DropDownText1</span></label>
<label for="ui-multiselect-selectedSku-option-2"><input id="ui-multiselect-dropdown-option-2" type="radio" value="DropDownVal2"><span>DropDownText2</span></label>
The first problem is your label. You generally should either have your input inside the label OR use the for attribute. Your for attributes are for different controls than the ones inside the labels. I am not sure how browsers will handle this.
If you don't want clicks on the label to trigger an input, don't associate them at all. Consider not using a label at all, use a span instead.
If there is a condition that turns on/off whether the label affects a control, you can use code to set/clear the label's for attribute.

Checking/unchecking a box with JQuery

I'm having some trouble using JQuery to check and uncheck an input. I know that .prop is the proper way to do it, but it doesn't seem to be working for me. Here's my code:
HTML:
<div class="checkwrap"><input name="mentoringType" type="checkbox" checked="false" value="test">test</div>
JS:
$('.checkwrap').click(function() {
if ($(this).find('input').is(':checked')){
$(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',false);
} else {
$(this).toggleClass('checkwrap-active').find('input').filter(':checkbox').prop('checked',true);
}
});
The input is wrapped for styling purposes. If I use .attr('checked',true/false) instead, then it works to change the checked property to checked, but it does not uncheck. What's going on?
Eggplant is right: you should use a lebel element to make "test" clickable.
To answer your question:
Your skript does work, when only the text ist clicked.
It also works, but not as expected, when the checkbox is clicked. In this case your code leads to a duplication of the ation executed, because the click event bubbles up the DOM tree.
If the checkbox is not selected, a click on it makes it being selected and your code comes in, detects it as being selected and unselects it again.
For an unselected box it works vice versa.
But as stated before: you should have chosen a label in the first place.

knockoutjs checkbox and click on parent td

I have a table with a row. The row has a TD(with a checkbox in it) and on the TD I have a click function. So that when the TD is clicked the checkbox will get checked/unchecked.
It works fine when I click on the TD , but when clicking on the checkbox the (visual) value of the checkbox does not change( It does not get checked/unchecked )
The wanted situation is:
When I click the checkbox, the (visual) value of the checkbox changes and I can call a function.( for example to make an AJAX call )
When I click on the TD, the (visual) value of the checkbox changes and I can call a function. ( for example to make an AJAX call )
How can we achieve this?
Sample Code
The problem is that the click handler for the TD fires also when you click the checkbox, which means the checkbox gets changed by both the default click handler for the checkbox and your custom click handler for the TD (they counteract each other). The solution is to prevent clicks on the checkbox from bubbling to the TD. You can do this in Knockout with this binding: click:function(){return true}, clickBubble:false.
Here it is in action: http://jsfiddle.net/mbest/Eatdh/12/
I do think, however, that using a label is a better approach (see my other answer).
To avoid the click event issues, use the label element to make a larger area clickable. Here I've made the label a block element so it takes up the whole td:
<td>
<label style="display: block">
<input type="checkbox" data-bind="checked: checkBox" />
</label>
</td>
See http://jsfiddle.net/mbest/LsxSh/
Td Event seems to be overriding the the input's check click event
clicking the check box invokes the click hander code for the td:
self.checkBox(!self.checkBox());
this removes the check.
This isn't quite DRY, but its quick and functional: fiddle
<td data-bind="click:tdClick">
<input type="checkbox" data-bind="checked: checkBox, click:tdClick" />
</td>

jQuery/Javascript problem with IE

I have two radio buttons each with a unique ID. When one is clicked, I would like to add $10 to a total. When the other is clicked, we go back to the original total price. My jquery looks like this:
function check_ceu() {
var price = <%= conference_price %>;
if($('#ceu_yes').is(':checked')){
$('#total').val(parseFloat(price) + 10)
}
else{
$('#total').val(price)
}
}
I have this function bound to document.ready (for page refreshes) and also the onchange handler of the radio buttons.
In FF and Chrome this works fine. In IE, when the radio button with ID of "ceu_yes" is checked nothing happens, then when clicking back to the other radio button, 10 is added. So in essence, IE has the checkbox functionality reversed. Below is my code for the buttons:
<input type="radio" name="ceu" id="ceu_yes" value="1" onchange="check_ceu()" /> $10
<input type="radio" name="ceu" id="ceu_no" value="0" checked="checked" onchange="check_ceu()" /> No, thank you
Any ideas on this?
IE's 'change' event handler is messed up. It doesn't fire when expected.
(http://webbugtrack.blogspot.com/2007/11/bug-193-onchange-does-not-fire-properly.html)
If you change your logic to attach to the 'click' event on your radio button, you will get the effect that you want.
NB. Nicely enough, the click event still fires properly when you tab into the field and manipulate it using the spacebar on the keyboard, so no functionality is lost.

Categories