Using preventDefault in checkbox click event - javascript

I have a checkbox and the requirement is that when the user clicks it, instead of immediately changing its state, a modal window should pop up asking them a yes/no question. Depending on their answer, the checkbox should either become checked or remain unchecked.
I thought that this requirement should be handled using Event.preventDefault() but when I tried to do it I discovered that when I exit the event handler, the checkbox is reverted to its original state, regardless of my programmatic attempts to set the state in the handler.
$(function() {
$(":checkbox").click(function(e) {
e.preventDefault();
$(this).prop("checked", confirm("Confirm to check the checkbox"));
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="checkbox">Click me</label>
<input type="checkbox" id="checkbox">
</form>
So how can I implement the required behavior?

The problem is because you called preventDefault() at all. You don't need it in this case as the checked state is entirely dependant on the outcome of the confirm() call.
Also note that you should use the change event, not click, when dealing with checkboxes. Try this:
$(function() {
$(":checkbox").change(function(e) {
$(this).prop("checked", confirm("Confirm to check the checkbox"));
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<label for="checkbox">Click me</label>
<input type="checkbox" id="checkbox">
</form>

Related

Event listener only triggers correctly after second click

I have an event listener that listens for clicks on a group of radio buttons, then passes the checked value to a function.
I then output the checked value to the web console whenever a radio button is selected, but this only works if the radio button is clicked twice after page load.
var t1q1El = document.getElementById("t1q1");
function question_1() {
$(function(){
$("#t1q1").one('click',function(){
var t1q1UserInput = $("input[name=t1q1]:checked").val();
questionsData['question_1']['input'] = t1q1UserInput;
assessPoints('question_1', t1q1UserInput);
});
});
}
t1q1El.addEventListener("click", question_1);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<fieldset id="t1q1">
<label>Strongly Agree
<input type="radio" value="strongly-agree" name="t1q1">
</label>
<label>Agree
<input type="radio" value="agree" name="t1q1">
</label>
<label>No Stance
<input type="radio" value="no-stance" name="t1q1">
</label>
<label>Disagree
<input type="radio" value="disagree" name="t1q1">
</label>
</fieldset>
</form>
On the second click, the value is passed to the web console immediately after clicking. All consecutive clicks function as expected. Why doesn't the first click trigger anything?
I'm still learning JS so please excuse/correct any bad practices..
Here is what happening:
1) t1q1El.addEventListener("click", question_1); You assign a function to t1q1El. Basically you are saying do question_1 when t1q1El is clicked.
2) Click 1. We do question_1 which is assigning a click event to t1qE1. Now t1qE1 has 2 events.
3) Click 2. Doing question_1 (which is assigning another click event on itself) and executing that click.
Solution is simple to just assign a click event:
$(function(){
$("#t1q1").one('click',function(){
var t1q1UserInput = $("input[name=t1q1]:checked").val();
questionsData['question_1']['input'] = t1q1UserInput;
assessPoints('question_1', t1q1UserInput);
});
});
BTW one() will execute only once, if you need to keep the event after first executions use on()

How to setCustomValidity on radio input immediately before form submission

I would like to setCustomValidity on an input immediately before the form is submitted. This seems like the logical approach:
document.querySelector('form').addEventListener('submit', function(e) {
var button = e.currentTarget.querySelector('input[type="radio"]');
button.setCustomValidity('You did it wrong.');
console.log(button.willValidate); // true
console.log(button.checkValidity()); // false
// Open Dev Tools to see output
debugger;
});
<form>
<label for="radio">
<input id="radio" type="radio">
Radio button
</label>
<br>
<input type="submit">
</form>
Despite setting a custom error, the form continues to submit. Is there some other event I need to handle, something that happens before the browser decides it's done dealing with validation?
I realize I could use the required attribute. The above approach may be better for when:
for whatever reason you can edit JavaScript but not the HTML
you just want to set a customized error message
Try to use reportValidity():
document.querySelector('form').addEventListener('submit', function(e) {
// prevent the default action first
e.preventDefault();
var button = e.currentTarget.querySelector('input[type="radio"]');
button.setCustomValidity('You did it wrong.');
button.reportValidity();
//console.log(button.willValidate); // true
//console.log(button.checkValidity()); // false
// Open Dev Tools to see output
//debugger;
});
<form>
<label for="radio">
<input id="radio" type="radio">
Radio button
</label>
<br>
<input type="submit">
</form>
Validity isn't checked in the submit event because, by design, submit is not fired if the form is invalid - the invalid event is fired instead. Therefore you have to manually stop the submit event and force re-validation (or at least reporting of the validation).

Checkboxes control Radio Checked/Unchecked

I have a checkout page with two radio buttons one for 'Register Account' and 'Guest Account' checkout methods.
I want a single checkbox that when it is checked, it checks the Register Account radio button and when it isn't checked it checks the Guest Account checkout radio button.
Here is my code so far:
http://jsfiddle.net/hQbpZ/160/
HTML:
Remember Me for Future Purposes :<input type="checkbox" id="checkbox1"/> <br/><br/>
Register Account :<input type="radio" id="radio1" name="radio"/><br>
Guest Checkout :<input type="radio" id="radio2" name="radio"/><br>
JS:
jQuery('#checkbox1').click(function(){
jQuery('#radio1').attr('checked', true);
});
jQuery('#checkbox1').click(function(){
jQuery('#radio2').attr('checked', false);
});
I got part of the functionality down but I don't know how to uncheck a radio button when a checkbox is unchecked.
You can do it like this:
jQuery('#checkbox1').click(function () {
jQuery('#radio1').prop('checked', $(this).is(':checked'));
jQuery('#radio2').prop('checked', !$(this).is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Remember Me for Future Purposes :
<input type="checkbox" id="checkbox1" />
<br/>
<br/>Register Account :
<input type="radio" id="radio1" name="radio" />
<br>Guest Checkout :
<input type="radio" id="radio2" name="radio" />
<br>
Just add a toggle variable and link the checked attribute to it
http://jsfiddle.net/hQbpZ/163/
var registered = false;
jQuery('#checkbox1').click(function(){
registered = !registered
jQuery('#radio1').attr('checked', registered);
jQuery('#radio2').attr('checked', !registered);
});
It is impossible to manually uncheck radio buttons, simply because they're not meant to be used that way (read more). The only way to have a radio button uncheck is by creating multiple radio buttons sharing the same name tag, meaning your HTML is already correct.
Your JavaScript does need some changes. It is not necessary to bind a function twice to the same event, so you could reduce it to one binding. Inside that binding you check whether the clicked checkbox is now on or off, and depending on that you check one of the two radio buttons, like so:
$('#checkbox1').click(function() {
if($('#checkbox1').prop('checked') === true) {
$('#radio1').attr('checked', true);
} else {
$('#radio2').attr('checked', false);
}
});

Check if checkbox is checked then send

I have this markup:
<form action="http://acumbamail.com/signup/13565/" method="POST">
<input type="checkbox" id="privacidad-btn" > Acepto polĂ­tica de privacidad<br>
<input type="button" value="Enviar" id="submit_acumba">
</form>
I want that if the user clicks on the button without checkbox checked there is an alert that he must agree to the terms (check the checkbox). Any ideas on the best approach to this?
I'm starting doing this way but don't know how which way to go:
if (jQuery("#privacidad-btn").is(":checked")) {
}
One approach that i like with html5 is the form validation
just put required on the checkbox and when the try to submit it they will be alerted with a popover dialog in there own language (its a good highlighter in the form of what is wrong with it)
<input required type="checkbox" id="privacidad-btn">
You could do it the way tymeJV suggest with button clicked event $("#submit_acumba").click(...)
That way you would support more browsers. but: It would just only validate on a click of a button
But there is the form submit event as well.
$("form").submit(function(e) {
if ( ! jQuery("#privacidad-btn").is(":checked")) {
// Not checked abort the default submit
e.preventDefault();
}
});
The difference is that it has to do all the native form validation before -> if it is invalid it won't trigger a submit or call the function
with button.onclick it would avoid the native validation since it would run before the submit event
You need a handler for the button as well:
$("#submit_acumba").click(function(e) {
e.preventDefault();
if (jQuery("#privacidad-btn").is(":checked")) {
//submit!
}
})
Using this straight and simple HTML implementation, you can do this without any special scripting (JavaScript/jQuery):
<form>
<p><input type="checkbox" required name="terms"> I accept the <u>Terms and Conditions</u></p>
<p><input type="submit"></p>
</form>
Here's a JSFiddle link where you can play with this implementation: http://jsfiddle.net/zs9b167b/

jQuery Mobile click event.preventDefault does not seem to prevent change

I am trying to prevent a radio button from changing when a use clicks, it works when using standard jQuery but when you include jQuery Mobile it does not seem to work, is there something else I have to do in jQuery Mobile?
<fieldset data-role="controlgroup" data-type="horizontal">
<input type="radio" name="trade-direction" id="buy" value="B" checked="checked" />
<label for="buy">Buy</label>
<input type="radio" name="trade-direction" id="hold" value="H" />
<label for="hold">Hold</label>
<input type="radio" name="trade-direction" id="sell" value="S" />
<label for="sell">Sell</label>
</fieldset>
$('[name="trade-direction"]:radio').click(function(event) {
if(!confirm("Do You Want To Change?")) {
event.preventDefault();
}
});
below is a link to the code in jsFiddle.
http://jsfiddle.net/mikeu/xJaaa/
The problem is that with jQuery.Mobile, the element that is effected by the UI change is not the input element. In fact, the radio element isn't actually clicked at all. The Element that is clicked is <div class="ui-radio">. If you want to bind to the radio input itself, you need to use the change event, but in this case it won't work for you, because the function gets called after the change has already taken place.
What you need is something like this:
// Probably a good idea to give your fieldset an ID or class
$('fieldset').delegate('.ui-radio','click',function(event){
if(!confirm("Do You Want To Change?")) {
event.stopImmediatePropagation();
event.preventDefault();
}
})
The event.stopImmediatePropagation() prevents the the .ui-radio from triggering the click event to the input, and the event.preventDefault prevents the default action. The stopImmediatePropagation may not be necessary, but it gives an added guarantee that may be helpful across different browsers.

Categories

Resources