Checkbox can't be unchecked - javascript

I am currently trying to solve a problem with my jquery and my html form.
Problem: I have a checkbox that allows people to check to accept or not accept the terms and conditions. This checkbox is being validated by a jquery function, named validateAccept(). However, after i insert the if valid return true and if not valid return false, the checkbox become unresponsive to clicking. I am a beginner with jquery. I am not sure which part went wrong.
my HTML code:
<form action="<? echo $filename; ?>" id="acceptanceForm" name="acceptanceForm" method="post">
<p>Terms and conditions.......</p>
I ACCEPT THE TERMS AND CONDITIONS
<input type="checkbox" name="accept" id="accept" value="yes"/>
<span id="acceptInfo" class="inputInfo"></span>
</form>
My jQuery validating code:
$(document).ready(function(){
//Validation (TERMSANDCONDITION)
//termsandconditions variables
var acceptanceForm = $("#acceptanceForm");
var accept = $("#accept");
var acceptInfo = $("#acceptInfo");
//Trigger validation
//On blur
accept.click(validateAccept);
//On key press
accept.keyup(validateAccept);
//On submit
acceptanceForm.submit(function () {
if (validateAccept())
return true
else
return false;
});
//Validation
//validate accept
function validateAccept() {
var isChecked = $('#accept').is(':checked');
if (isChecked) {
accept.removeClass("error");
acceptInfo.text("Thanks");
acceptInfo.removeClass("error");
acceptInfo.removeClass("inputInfo");
acceptInfo.addClass("validated");
return true;
} else {
accept.addClass("error");
acceptInfo.text("Please Read and Accept the Terms and Conditions");
acceptInfo.removeClass("inputInfo");
acceptInfo.removeClass("validated");
acceptInfo.addClass("error");
return false;
}
}
What I know:
I know that the problems lies with the return true and return false that I added in. I tried without them on JS Fiddle and the check box is working but the form is not. Therefore, I know that return true and false is necessary but I don't really know how I should sort them out to make it work. I have did some researched and realised that little little cases similar to mine. This validation technique is suppose to work on text input so I am not sure if the way i edit it is alright to work for checkbox.
JSFiddle

The problem is that returning false in a click handler prevents the default behavior. If you need to use this in both situations, but ignore the return value in the case of the click handler, you could do this:
accept.click(function(){
validateAccept();
});
http://jsfiddle.net/8JdRb/1/
In this case the click handler function has no return value and does not affect the functioning of the checkbox.

I found the answer. I can use .change(validateAccept); instead. It would work exactly the same as I wanted to. Thanks all.
JSFiddle

Related

Hiding fields based on email value AND boolean yes/no field using JavaScript

I have a Microsoft Power Apps Portals page on my portal that requires a bit of customization through JavaScript. I would like to hide fields based on an email address entered, which works fine. However, when the user enters the email domain that will show some fields, I would like to apply additional formatting.
Here is the code I currently have:
$(document).ready(function () {
$("#emailaddress1").change(onShowHideEmployeeFields);
onShowHideEmployeeFields();
});
function onShowHideEmployeeFields() {
var varEmail = $("#emailaddress1").val()
//alert(varEmail)
if (varEmail.includes("#example.org")) {
$('#xxx_employeeid').parent().parent().show();
$('#xxx_employeeid').prop('required', true);
$('#xxx_employeeid').closest(".control").prev().addClass("required");
$('#xxx_defaultfacilityid').parent().parent().show();
$('#xxx_defaultfacilityid').prop('required', true);
$('#xxx_defaultfacilityid').closest(".control").prev().addClass("required");
$('#xxx_positiontitle').parent().parent().show();
$('#xxx_officer').parent().parent().show();
$('#xxx_officer').prop('required', true);
$('#xxx_officer').closest(".control").prev().addClass("required");
$('#xxx_jopositiontitle').parent().parent().show();
}
else {
$('#xxx_employeeid').parent().parent().hide();
$('#xxx_defaultfacilityid').parent().parent().hide();
$('xxx_defaultfacilityid_label').parent().parent().hide();
$('xxx_positiontitle_label').parent().parent().hide();
$('#xxx_positiontitle').parent().parent().hide();
$('#xxx_officer').parent().parent().hide();
$('#xxx_jopositiontitle').parent().parent().hide();
}
}
The code works fine, however, I want to extend the code by showing the JO Position Title IF the Officer field has been marked as 'Yes' (it is a boolean yes/no radio checkbox field).
I've tried testing this component separately using the below code:
function onShowHideEmployeeFields() {
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").val();
//alert(varJO)
if (varJO === 'Yes') {
$('xxx_jopositiontitle').parent().parent().show();
}
else {
$('xxx_jopositiontitle').parent().parent().hide();
}
})
}
This code doesn't seem to do anything. Any thoughts on this issue?
Thank you!
AFAICT your question boils down to how can I check if a checkbox is checked?. The code you tried is on the right track, but that's not how you get a checkbox's state. A quick search turns up many many examples:
$('xxx_officer').change(function () {
var varJO = $("$xxx_officer").prop('checked');
if (varJO) {
$('xxx_jopositiontitle').parent().parent().show();
} else {
$('xxx_jopositiontitle').parent().parent().hide();
}
});
There are many, many examples of this here on SO, and I've voted to close this question as a duplicate.
How do I check whether a checkbox is checked in jQuery?
Get checkbox value in jQuery
get current state of check box jquery
Check if checkbox is checked with jQuery
Get checkbox selected state with JQuery
...

Focus specific 'id' after submit action

I want to focus on specific id (ex. using $('#a')) after submit.
There is nothing special with my code yet.
My javascript code is
function get_info(id){
$(user_id).submit();
$('#a).focus();
};
After submit, it should focus on where id='a'.
But after submit window focus on id='a' and reset the page.
I tried using
function get_info(id){
$(user_id).submit(function(e){
e.preventDefault();
$('#a').focus();
});
};
But this code make program worse. I think it stops performing submit.
Can anyone help me?
As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.
You need to use cookies or local storage, here a suggested sample using local storage like :
function get_info(id) {
localStorage.setItem('focusItem', '#a');
$(user_id).submit();
};
Then in the ready function, you could add :
$(function(){
var focusItem = localStorage.getItem('focusItem');
if( focusItem != null ){
$(focusItem).focus();
localStorage.removeItem('focusItem');
}
});
function SetFocus(){
$("#FocusingID").focus();}
/***********another way **********************//*
$("#submitbtnId").click(function(){
//your submession and other task;
$("#FocusingID2").focus();
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>

How to render a new page in a javascript script

I am using XHTML, JSF and JavaScript to create a form, validate that information has been submitted into selected fields onclick in a h:commandButton, and if validated, redirect to a different page homepage.xhtml. Everything works up to the redirection, which I can't get to work.
In the JavaScript function Validation(), I have tried location="homepage.xhtml", window.location.href="homepage.xhtml", location.url="homepage.xhtml" and a few others, but nothing seems to work. I have a feeling I'm supposed to have some sort of statement which adds href="homepage.xhtml" to the h:commandButton if Validate() returns true, but I am unsure as to how to do that.
Any help is greatly appreciated. I have added the relevant code below.
Button:
<h:commandButton class="btn btn-warning" value="Continue" onclick="Validation()"/>
Validation
function Validation() {
var nameCheck = document.getElementById('formdiv:cardName');
var numCheck = document.getElementById('formdiv:cardNumber');
var expCheck = document.getElementById('formdiv:expDate');
console.log(nameCheck.value);
console.log(numCheck.value);
console.log(expCheck.value);
var variablesToCheck = [nameCheck, numCheck, expCheck];
for(i=0; i < variablesToCheck.length; i++){
if(variablesToCheck[i].value == null || variablesToCheck[i].value == ""){
alert("Fields marked with a * must be completed");
return false;
}
}
// This is where the redirection needs to go, I think...
return true;
}
EDIT: Just noticed the if else statement is incorrect logically, but syntactically it shouldn't make a difference. The else part needs to be a statement outside of the loop without a condition; this code simply tries to redirect when the field it is checking has something in, not when all fields have something in.
EDIT 2: Loop corrected
Why you need h:commandButton anyway you are using simple javascript validation
h:commandButton is rendered as <input type="submit" ../> its mission is
to submit the form so what ever javascript you are writing your form will be submitted and your page is gonna be refreshed, So If you need it this way you have to force it not to submit the form,
However from understanding your needs all you need is simple <a /> or <button /> , Or you can just add type="button" into your h:commandButton ex:<h:commandButton type="button" .../>
You can either use..
window.location.replace('Your_url'); ..
or you can use..
window.location.href= 'Your_url'; .. I guess there must be other functions too. If you want to open it in another window, like a popup, you can use.. window.open('your_url');
Hope this helps!

How to disable button in javascript

Onclick of button,(In clientclick event)I show confrmation box having ok and cancel button.Onclick of ok button,buttonclick event fire.I want to disable button and show to message(Pls wait) to user.I am trying but not working.Unable to disable the button and set text to label.
function validate()
{
var response = confirm(Proceed)
if(response)
{
document.getElementById('btnSave').disabled = true;
document.getElementById('lblMessage').innerText = 'Please Wait';
return true;
}
else
{
return false;
}
}
I am getting error.Error is
JavaScript runtime error: Unable to get property 'innerText' of undefined or null reference in asp.net
First of all there's maybe a problem in your HTML. Javascript cannot find the 'lblMessage' element. Fix that first and you're good to go.
Maybe you're using ASP.NET Web Forms. ASP.NET changes the client ID's of server controls depending on the ID of their container. You can change this behavior easily by reading this article:
http://weblog.west-wind.com/posts/2009/Nov/07/ClientIDMode-in-ASPNET-40
Or, find your elements by class name. That way it won't cause conflict with any configuration you're now using.
I think you need to add your html code. I'm guessing your html looks like this
<button onclick="validate()">
you need to add a return statement into the html code so it looks like this
<button onclick="return validate()">

How do you do a mandatory checkbox in a form?

I need a checkbox, where you move from one page to another after clicking the box. The checkbox should be required, given that you've read the terms and conditions link next to it.
I'm only half sure how to do this, something like this:
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" />
with Jquery:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'strong');
return false;
}
}
</script>
At the moment though, I can't view the checkbox at all on the page, so perhaps my HTML is incorrect?
Hope you can help.
Your HTML is fine - is will show a checkbox - but without any text. You could add some using this markup :
<input type="checkbox" value="confirm_prepay_terms" name="confirm_prepay_terms" align="middle" >​Text here</input>​​​​​​​​​​​​​​​​​​​​​​​
In your JavaScript you are missing a closing ) :
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked') {
should be
if ($('form#prepay input:checkbox', 'confirm_prepay_terms').is(':checked')) {
and a ) on the last line :
}
</script>
should be
})
</script>
and your selector is incorrect
$('form#prepay input:checkbox', 'confirm_prepay_terms')
should be
$('form#prepay input:checkbox[name=confirm_prepay_terms]')
This uses the multiple attribute selector
and
$('#confirm_terms_hint').css('font-weight', 'strong');
should be
$('#confirm_terms_hint').css('font-weight', 'bold');
font-weight has no strong value (see here) ... use bold instead
in your script you are returning true or false but the code is not being called by anything - its executing as soon as the page has completed loading. Have a look at the .submit() method in jQuery if you want to perform form validation. An example would be this :
$(document).ready(function() {
$('#prepay').submit(function() {
if ($('form#prepay input:checkbox[name=confirm_prepay_terms]')) {
return true;
} else {
$('#confirm_terms_hint').text('Please try again - you need to check the box to move on');
$('#confirm_terms_hint').css('font-weight', 'bold');
return false;
}
});
});
This would prevent the form from being submitted now - as you return false to the submit event.
Fully working example here
I don't think it is necessary for you to provide a CheckBox as long as they must accept this terms and conditions before using the service.
You can just do the following and stress-less yourself .
- Provide a link to the terms and conditions for reading
- Notify them that they have automatically accept this terms while proceeding.

Categories