How do you do a mandatory checkbox in a form? - javascript

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.

Related

How to hide form fields with Jquery in Shopify

I am trying to write a simple script which follows the logic below but I am having difficulties.
If "Name" field = blank
Then Hide "Comment" field
Else Show "Comment" field
$(document).ready(function() {
if ($('#ContactForm-name').value() == "") {
$('#ContactForm-body').hide();
} else {
$('#ContactForm-body').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Can someone please help me? I provided a screen shot of the form and its HTML.
The shopify store is https://permaink.myshopify.com/pages/contact with the store PW = "help".
Taking a look at the example link you provided w/ 'help' password, it doesn't look like jQuery is actually loaded on the site, after running the following in console: console.log(typeof window.jQuery) returns undefined.
You may need to use vanilla JS to achieve what you're trying to do (or side load jQuery, if you have permissions to do so and really need to use it).
Using JS without jQuery, you can try doing something like:
window.addEventListener('load', function() {
if (document.getElementById('ContactForm-name').value === '') {
document.getElementById('ContactForm-body').style.display = 'none';
} else {
document.getElementById('ContactForm-body').style.display = 'block';
}
});
Note, that just hiding the ContactForm-body textarea will still leave a border outline and the label Comment showing, so you may need to do more than just hiding the textarea (find the parent <div> in JS and hide whole block).

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>

Checkbox can't be unchecked

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

Hide / Show Multiple Divs

I am trying to create a form that has various hide/reveals in it and one of the last parts I need to do to this form is SHOW the payment information fields when only Credit Card is selected.
I have a test page setup here: http://www.faa.net.au/test/femmes-member-form.html
Process so far is:
Enter your details
Select Event Date
Selecting Member + 1 or more Guests ask for payment details
At the moment, I have displayed the 3 DIVs that I want to appear depending on the radio selection made but when I hide these, the code I have in place at present doesn't work.
Can anyone help me here at all please?
If you need the code, please let me know, with a number of different elements involved I didnt want to paste the whole thing on here, hopefully you can see the Source Code?
Here is the Javascript I have at present but not sure if its this that is wrong or if its clashing with something else?
<script type="text/javascript">
$(function() {
$('.cat_dropdown').change(function() {
$('#payMethod').toggle($(this).val() >= 2);
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".payOptions").click(function () {
$(".paymentinfo").hide();
switch ($(this).val()) {
case "Credit Card Authorisation":
$("#pay0").show("slow");
break;
case "Direct Deposit":
$("#pay1").show("slow");
break;
case "Cash Payment (FAA Office)":
$("#pay2").show("slow");
break;
}
});
});
</script>
As per viewing code from View Souce and guessing that you have not added correct class in event handler. thus click event for radio is not getting invoked.
Change
$(".payOptions").click(function () {
to
$(".paymentmethod").click(function () {
You have not posted any source, but if you are using jQuery, you can simply do:
$(".commonclass").hide();
Provided that all 3 divs have the "commonclass" class.
Process goes something like this:
Start clean: hide all payment methods
Your radio inputs have paymentmethod class, so attach a change event listener to those elements
When one of the radios is selected, hide all of the payment methods, determine the one you want to show using index, and show that div
$('#pay0, #pay1, #pay2').hide();
$('input.paymentmethod').on('change', function(){
$('#pay0, #pay1, #pay2').hide();
var selected = $('input.paymentmethod').index($('input.paymentmethod:checked'));
$('#pay'+selected).show();
});
Used to jquery as like this
Css
#pay0, #pay1, #pay2{display:none;}
Jquery
$(document).ready(function(){
$('#payment').change(function(){
if($('#CAT_Custom_255277_0').attr('checked')){
$('#pay0').show();
$('#pay1').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_1').attr('checked')){
$('#pay1').show();
$('#pay0').hide();
$('#pay2').hide();
}
else if($('#CAT_Custom_255277_2').attr('checked')){
$('#pay2').show();
$('#pay0').hide();
$('#pay1').hide();
}
});
});
Demo
As per my understanding, you're trying like below,
select value from dropdown, if the value !== "1" then show payment radio buttons
Based on the radio button selection, you want to show the respective div
From viewing your source code, it seems you're using jQuery lib and there use this
$(document).ready(function() {
$('input[type=dropdown]').on('change', function(){
if($(this).val() !== 1)
{
$('input[type=radio]').show();
}
}
$('input[type=radio]').on('change', function(){
if($(this).val() === "Credit Card Authorisation") {
$('#pay1').hide();
$('#pay2').hide();
$('#pay0').show();
}
else if($(this).val() === "Direct Deposit"){
$('#pay0').hide();
$('#pay2').hide();
$('#pay1').show();
}
else if($(this).val() === "Cash Payment (FAA Office)"){
$('#pay0').hide();
$('#pay1').hide();
$('#pay2').show();
}
});
});
Hope you understand.

Radio Button "Select" Toggle issue

I am trying to make a very very simple script that checks to see if a certain radio button option is clicked, and if so, shows another set of fields (this works fine), but if you unselect that radio button option, it hides the extra set of fields (seemingly simple, but does not work for me!)
Also I am newish to JS/JQuery so debugging this has been a struggle! Thanks for any help :)
My HTML radio button that triggers the fields display - imagine there are 6 other radio button options with this (each classed with [class="otherFund"]).
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" onclick="set_item('DOP-Relief-Fund', 8)" onchange="relief_fund_handler()" />
Here is the text and field and I want to toggle with the above button's selection
<p id="Earmark1" style="display: none;">
<strong>Please designate below what relief fund you would like your <em>DOP Charitable Relief</em> donation to go towards (see bulleted examples above).</strong><br />
<strong>Earmarked for <span class="required">*</span>:</strong><input type="text" name="Earmark1" id="Earmark1" size="50" />
</p>
And here are my JS attempts...
Attempt 1:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else if (".otherFund".checked) {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 2:
function relief_fund_handler() {
var relief_elem = document.getElementById("Relief1"),
earmark_elem = document.getElementById("Earmark1"),
donate_elem = document.getElementById("ItemName1");
if (relief_elem.checked) {
earmark_elem.setAttribute("style", "display: inline;");
} else {
earmark_elem.setAttribute("style", "display: none;");
}
}
attempt 3:
$("#Relief1:checked")(
function() {
$('#Earmark1').toggle();
}
);
On attempt #3, I have also replaced the :checked with .click, .select, .change and none have worked... Thanks for any help! :)
Try this:
$("input.otherFund").change(function() {
$('#Earmark1').toggle($(this).attr('id') == 'Relief1');
});​
Try removing all of the events off of the radio button like this:
<input type="radio" name="ItemName1" id="Relief1" value="Daughters of Penelope Charitable Relief Fund" />
And using the following jquery script:
​$(function(){
$("#Relief1").change(function(){
$(this).is(":checked") ? $("#Earmark1").show() : $("#Earmark1").hide();
});
});​
You could iterate through each radio button and assign an event handler to each radio button, so when selected it shows the other fields and when deselected it hides the other fields. The code below may help you arrive at the correct answer.
// Iterate the radio buttons and assign an event listener
$('input[name="ItemName1"]').each( function() {
// Click Handler
$(this).live('click', function() {
// Check for selected
if ( $(this).is(':checked') )
{
$('#EarMark1').show();
}
else
{
$('#EarMark1').hide();
}
});
});
It's not perfect, nor is it the most elegant solution. With some tweaking it should point you in the right direction.
thank you to everyone!!! I ended up using kennypu's example - the ":checked" seemed to work fine even though it is a radio button. I had to make some tweaks to it, and ended up with 2 separate functions instead of the "else". For some reason the other examples were not working for me - although I highly doubt it has to do with your code, and likely has to do with other things going on in the page. Since we're using an external form/database handler, we need to keep the events and other code there.
Here's what ended up working..
$(function(){
$("#Relief1").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").show();
}
});
});
$(function(){
$("#Radio1, #Radio2, #Radio3, #Radio4, #Radio5, #Radio6, #Radio7").change(function(){
if($(this).is(":checked")) {
$("#Earmark1").hide();
}
});
});
Pretty clunky, but I got it to work how I needed. Thank you to everyone who contributed, it helped quite a bit.
Try:
<script>
var r=$('input[name="ItemName1"]).is(:checked);
if(r)
{
alert("Item is checked");//replace with any code
}
</script>
if you're already using jQuery, this is simple as using .show() and .hide():
$('#Relief1').on('change',function() {
if($(this).is(':checked')) {
$('#Earmark1').show();
} else {
$('#Earmark1').hide();
}
});
example fiddle: http://jsfiddle.net/x4meB/
also note, don't use duplicate ID's, they are meant to be unique (in this case, you have a dulpicate #Earmark1 for the p tag and span). Also, in the example fiddle, I changed it to a checkbox instead of a radio since You can't uncheck a radio if there is only one option.

Categories