run function onclick of disabled checkbox - javascript

I have a checkbox that I do not want the user to have direct access to. I want them to accept some terms. To do this I want them to be able to click on a disabled checkbox which opens this mini popup (not checking the box) that contains the terms so the reader can read them and accept them. Once they accept them the popup will close and the checkbox will be checked. The issue I have is i cant figure out to run a function onclick of the disabled checkbox.

Handling the click on a disabled element is indeed tricky ... but I don't think it's the desirable user experience anyway. If a checkbox is disabled, some users will see that and be disinclined to even attempt clicking it. Instead, consider intercepting the click event and using it for your own purposes using preventDefault.
<input type='checkbox' id="cb" name="cb" />
$(document).ready(function() {
$("#cb").click(function(e) {
// cancel click event so that checkbox remains unchecked
e.preventDefault();
// display popup here, then manually check the checkbox if needed
}
});

$('#chk').click(function () {
if (confirm('Accept')) {
$(this).attr('checked', 'checked');
}
else {
$(this).attr('checked', false); }
});

A disabled checkbox might not handle click events properly and would be displayed as "disabled".
But, you could try this:
add an attribute to the checkbox to store if the popup was displayed (e.g. data-popup="0")
handle the onclick event on the checkbox
if the popup was displayed (data-popup="1" ) simply return true to allow to use to check it
if the popup was not displayed (data-popup="0" ), then prevent the default behaviour, set data-popup="1" and display the popup with the terms and conditions
Another improvement, depending on the design of your popup, could be the add a new checkbox in that popup and when the user reads the terms and conditions, he can accept the terms and conditions directly from the popup. If you do that, you need to treat the click event on the checkbox in the popup and automatically check the checkbox on your page as well.

#dbaseman
Here is my code.
Take a look.Here,I get the alert on div but not on checkbox.
<html>
<head>
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#checkbox, #hello").click(function(){
alert("hello");
});
});
</script>
</head>
<body>
<div id="checkbox">
<p> hello</p>
<input type="checkbox" id="hello" disabled="disabled" />
</div>
</body>
</html>

Related

JavaScript Check box with collapse button

I want to make below code works for Check box with collapse button.
<label>
<input type="checkbox" id="postageyes" name="postage1" value="Yes" />Yes</label>
<div id="conditional1">
<p>This should only show when the 'Yes' checkbox <input> element is checked.</p>
close
</div>
Javascript
var conditionalContent1 = $('#conditional1'),
group = $('input[type=checkbox][name=postage1]');
group.change(function() {
conditionalContent1.toggle(group.filter(':checked').val() === 'Yes');
}).change();
when i checked check box new div open, I want to get done is. when i click close link, the open div close and unchecked the checked box.How to do this.
anyone can help?
You can use change event on checkbox. And toggle to hide/show div.
$('#postageyes').on('change', function() {
$('#conditional1').toggle($(this).is(':checked'));
});
$('#conditional1').on('click', 'a', function() {
$('#postageyes').prop('checked', false);
$('#conditional1').hide();
return false;
});
Demo: http://jsfiddle.net/tusharj/n7044syx/1/
You can use the toggle function and click event to achieve what you have mentioned.
$('#postageyes').click(function() {
$('#conditional1').toggle();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<label>
<input type="checkbox" id="postageyes" name="postage1" value="Yes" />Yes</label>
<div id="conditional1" style="display:none">
<p>This should only show when the 'Yes' checkbox <input> element is checked.</p>
close
</div>
EDIT: Tushar updated his answer while I was writing this so... yeah, never mind! That would also work. The point still stands, though.
I think part of the problem is that you're trying to use an anchor tag inappropriately. Leaving the href blank will reload the page, so Tushar's answer looks right but doesn't actually do what you're asking. Use a button (and style it appropriately if you still want it to look like a link) and then handle its click event to toggle the checkbox and hide the content.
I've modified Tushar's jsfiddle to show what I mean. You'll probably be able to make it more streamlined than this, but the simple version is:
Replace the a tag with:
<button id="closeButton">close</button>
Then add the following to the js:
$('#closeButton').on('click', function () {
$('#postageyes').click();
});
https://jsfiddle.net/pnq8zu0L/

Click input on page load with jQuery

I have three radio buttons and I want, by default, to have the "BOTH" location which has a value of 3 to be clicked on page load so that it will run my jQuery post function. The radio button is filled-in giving the appearance of being clicked, but the click is not happening to post my function. Once I change the radio button however, the code works fine.
This is my code:
$("input:radio[name='location'][value='3']").click();
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
Would you try to register the event handle first before trigger the event? $("input:radio[name='location'][value='3']").click(); after the .change' event..
you may consider use the checked too, like $("input:radio[name='location'][value='3']").prop("checked", true).
but for my personally preference, any default state should be done before hand and not the in the script, for example initiate your radio DOM element to have checked property <input type="radio" value="3" checked />, and then onLoad script call the post directly (anyway POST is not designed for this purpose, just imagine POST as to save something, if you just want to get/query some data, GET would be more reasonable)
click was triggered before the change's event handler was regestered.
$('input[name="location"]').change(function() {
var location = $('input[name="location"]:checked').val(); var category = getUrlVars()["category"];
$.post(
'db/functions/package_conf.php',
{category:category, location:location},
function(data) {
$('#package_info').html(data);
});
});
$("input:radio[name='location'][value='3']").click();
$(window).on('load', (e) => { $("#test").focus() })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="test" value="23" type="number" style="font-size:30px;width:150px;">

jQuery Tools Overlay - Two buttons with different close conditions

I have the following jQuery Tools overlay:
<div id='editDescriptiontOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
Background info: The HTML for this overlay is static. I have a list of items each having their own Edit link. When a given Edit link is clicked, the overlay is generated by calling: $('a[rel=#editDescriptionOverlay]').overlay( { ... } ); and the input is populated with the respective text.
The Save button needs to validate the text in the input element and close the overlay if and only if the validation is successful. Otherwise, the overlay must remain open. The Cancel button simply closes the overlay without validation.
The validation logic has been independently verified to work.
I've tried setting the onBeforeClose event during overlay generation as a means of validation. Taking this approach, both the Save and Cancel buttons needed the same class .close. Unfortunately, the condition applies to all .close elements in the overlay so even the Cancel button was validating.
I've also tried binding a click event to the Save button immediately after generating the overlay, like so:
$('.save', $('#editDescriptionOverlay'))
.unbind('click')
.bind('click', function() {
if (validateText) {
console.log("Validation passed.");
$('a[rel=#editDescriptionOverlay]').overlay().close();
}
else {
console.log("Validation failed.");
}
});
The console.log's confirm that the validation is working, but the overlay doesn't close.
Any insight is appreciated, thanks.
For jquery widgets, public methods should be called as follows:
$('a[rel=#editDescriptionOverlay]').overlay("close");
wherein close is the method name that you wish to call.
If a method accepts parameters, then, these should be added as parameters right after the method name.
Updated:
I am sorry. I just had time to check what jQuery Overlay Tools is and I am mistaken. This is not similar to any jQuery widget, hence, my comment above will also not work for this case. I tried your code above and it worked. The overlay was closed. But, when I tried it with multiple <a rel="#editDescriptionOverlay">, which I think is what you did. It did not work. My suggestion would be to use just one <a rel="#editDescriptionOverlay"> and use a dummy anchor element for the Edit link, which when clicked would trigger a click to <a rel="#editDescriptionOverlay">. You can do something like this:
<script type="text/javascript">
$(document).bind("ready", function(e){
$("a[rel]").overlay();
$('.save', $('#editDescriptionOverlay')).unbind("click").bind("click", function(){
if (validationValue){
$("a[rel=#editDescriptionOverlay]").overlay().close();
}
});
});
function clickThis(){
$("a[rel=#editDescriptionOverlay]").trigger('click');
return false;
}
</script>
Edit1
Edit2
<a rel="#editDescriptionOverlay">Dummy</a>
<div id='editDescriptionOverlay' class='overlay'>
<input type='text' class='description'/>
<button class='save'>Save</button>
<button class='close'>Cancel</button>
</div>
I'd prefer binding an event to the save button (the second one you mentioned). Actually your code looks fine, except that you probably don't need to bind the event to $('#editDescriptionOverlay') and you have typo in your html markup above (<div id='editDescriptiontOverlay' should be <div id='editDescriptionOverlay').
See here for an example.

Fire an event on input.checked=true/false _without_ jQuery

Consider the following code (http://jsfiddle.net/FW36F/1/):
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].checked;">toggle</button>
If you click the checkbox, you get an alert telling you if it's checked or not. Great. However, if you click the toggle button, the checkbox changes it's checked state but the onchange event is NOT fired.
Essentially, the onchange for a checkbox only fires if the user actually clicks the checkbox, not if the checkbox is changed via JavaScript. This is be true in IE, FF, and Chrome. It appears that this behavior is to specification also.
However, I really need some kind of event to fire if, for any reason, the checkbox's checked state changes. Is this possible?
Oh yeah, and jQuery is not allowed. And please no setTimeout/setInterval based solutions either...
Update: Also, I should make it clear that the code above is for illustration only. In the real code, we need to ensure the state of the checkbox is checked or unchecked -- not just toggle it. Perhaps this would be better code to illustrate that:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].checked=true;">check</button>
<button onclick="document.getElementsByTagName('input')[0].checked=false;">un check</button>
Moreover, there may be code in other areas we don't fully control, which might do a simple .checked=true/false -- we'd like to make sure we see that also.
The existing answers work just fine, even with your update. Just be smart about it and don't call click if you don't need to. Also, please don't use inline JS. That was OK 10 years ago.
<input type="checkbox" onchange="alert(this.checked)">
<button id='check'>check</button>
<button id='uncheck'>uncheck</button>
document.getElementById('check').onclick = function() {
if (!this.checked) {
this.click();
}
}
If you need to be modified when a script changes the value, in Firefox, you can use https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/watch
Example here http://jsfiddle.net/PPuZ8/
// In FF $ is a shortcut for document.getElementById
// It doesn't fire when set from the UI, you have to use a regular handler for that
$('cb').watch("checked", function(){
console.log('Checked state changed from script', arguments);
return true;
});
For IE you can use onpropertychange http://msdn.microsoft.com/en-us/library/ie/ms536956(v=vs.85).aspx (Thanks to jivings for the reminder)
Example: http://jsfiddle.net/PPuZ8/1/
document.getElementById('cb').onpropertychange = function() {
if (event.propertyName == 'checked') {
console.log('Checked state changed onproperty change');
}
};
For other browsers, you have to poll using setInterval/setTimeout
Have the toggle button actually click the checkbox:
<input type="checkbox" onchange="alert(this.checked)">
<button onclick="document.getElementsByTagName('input')[0].click()">
toggle
</button>
If you wanted any change to the checkbox to inform you of its new position, then I would create a global method for changing the value of the checkbox, and deal with it as a proxy:
<script>
function toggleCB( state ) {
var cb = document.getElementById("cb");
arguments.length ? cb.checked = state : cb.click() ;
return cb.checked;
}
</script>
<input id="cb" type="checkbox" />
<input type="button" onClick="alert( toggleCB(true) )" value="Check" />
<input type="button" onClick="alert( toggleCB(false) )" value="Uncheck" />
<input type="button" onClick="alert( toggleCB() )" value="Toggle" />​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Now anytime you set or toggle the checkbox, you'll get the checked state back.
One last thing, I would avoid using the onClick attribute, and instead bind the click events up from within your JavaScript.
Use click()
<button onclick="document.getElementsByTagName('input')[0].checked=!document.getElementsByTagName('input')[0].click();">toggle</button>
oninput is the event you need to handle ...
https://developer.mozilla.org/en/DOM/DOM_event_reference/input

Enable/Disable onclick using JavaScript

I want to re-enable a disabled onclick. I am using:
$('#id_'+id).prop("onclick", null);
to disable the onclick, but when clicking once again on the button I want to re-enable the onclick again. How do I do that?
Like others said use
$(id).off('click')
in Another way
your Question is not proper,
From your question i get so,
<input type="Button" id="test" >
<script>
$('#test').on('click',function(){
if($(this).attr('class') == '_enable'){
alert(' its working');
}
$(this).addClass('_enable');
});
</script>
first time it won't get the alert from next on wards u ll get the Alert!!!!
if want to disable again then remove that _enable class!!!!

Categories

Resources