Hiding/showing fields conditionally w/ checkboxes - javascript

I'm using a conditional fields form from Bootstrap Validator and don't know enough Javascript to make one last thing work.
The form as it is now is live here
My problem is both "...a brochure to be sent to me" and "...to arrange a field demonstration" need to open the same address fields, however, if you check "...a brochure sent to me," then check "...to arrange a field demonstration" the fields open and then close again.
How do I create an if statement to verify if the field is already visible and leave it open if it IS, and open it is it's NOT?

It looks the bootstrapValidator.js file is addressing the checkboxes by class, both of your checkboxes have the name "topic[]" with the same value of "address". You could give each field its unique ID, add in javascript that tells the page to see if either of the checkboxes are checked, and then make the style display set to block.
Try
//HTML - Added ID's to each and the onclick='showblock()'
<input type='checkbox' value='address' name='topic[]' id='address1' onclick='showblock()'></input>
<input type='checkbox' value='address' name='topic[]' id='address2' onclick='showblock()'></input>
<div data-topic="address" style="display: block;" id="addressform">
//JS
function showblock() {
if (document.getElementById("address1").checked == true || document.getElementById("address2").checked == true) {
document.getElementById("addressform").style.display = "block";
} else {
document.getElementById("addressform").style.display = "none";
}
}
This should work, if it doesn't then the bootstrapValidator is probably overwriting it, you can just change the value of "address" to something other than address.

Related

jQuery form validation. How to prevent error messages appearing multiple times

I'm trying to validate a form in jQuery. I have it working, with 1 issue. If i click the submit button twice, the error messages will show twice, stacked on top of eachother.
EG
Name must not be empty
Name must not be empty
//Form Validation
//Store checkbox, and checkbox label in jQuery object
$terms = $('#terms');
$termsdoc = $('#terms-doc');
//Check if pet name is empty
if($name.val() == '')
{
$name.after('<p class="error">Name must not be empty</p>')
}
if($terms.is(':not(:checked)'))
{
$termsdoc.after('<p class="error">Please agree to the terms and conditions</p>')
}
Using .last() just adds the desired content as the last child of the target selection, so what you're seeing is a duplicate element being added.
SOLUTION:
You could target <p> tags with the class "error" and remove them before you add them with .last():
$("p.error").remove();
You could also disable the submit button in the handler. $(".submit").prop("disabled",true);
This would prevent duplicate submissions.

Homemade "Captcha" System - One minor glitch in javascript, can't enable submit button

So basically what I'm trying to do as a measure of security (and a learning process) is to my own "Capthca" system. What happens is I have twenty "label's" (only one shown below for brevity), each with an ID between 1 and 20. My javascript randomly picks one of these ID's and makes that picture show up as the security code. Each label has its own value which corresponds to the text of the captcha image.
Also, I have the submit button initially disabled.
What I need help with is figuring out how to enable the submit button once someone types in the proper value that matches the value listed in the HTML label element.
I've posted the user input value and the ID's value and even when they match the javascript won't enable the submit button.
I feel like this is a really really simple addition/fix. Help would be much much appreciated!!!
HTML code
<div class="security">
<label class="captcha enabled" id="1" value="324n48nv"><img src="images/security/1.png"></label>
</div>
<div id="contact-div-captcha-input" class="contact-div" >
<input class="field" name="human" placeholder="Decrypt the image text here">
</div>
<input id="submit" type="submit" name="submit" value="Send the form" disabled>
Javascript code
//Picks random image
function pictureSelector() {
var number = (Math.round(Math.random() * 20));
//Prevents zero from being randomly selected which would return an error
if (number === 0) {
number = 1;
};
console.log(number);
//Set the ID variable to select which image gets enabled
pictureID = ("#" + number);
//If the siblings have a class of enabled, remove it
$(pictureID).siblings().removeClass("enabled");
//Add the disabled class to all of the sibling elements so that just the selected ID image is showing
$(pictureID).siblings().addClass("disabled");
//Remove the disabled class from the selected ID
$(pictureID).removeClass("disabled");
//Add the enabled class to the selected ID
$(pictureID).addClass("enabled");
};
//Calls the pictureSelector function
pictureSelector();
//Gets the value of the picture value
var pictureValue = $(pictureID).attr("value");
console.log(pictureValue);
//Gets the value of the security input box as the user presses the keys and stores it as the variable inputValue
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
});
console.log($("#contact-div-captcha-input input").val());
//Checks to see if the two values match
function equalCheck() {
//If they match, remove the disabled attribute from the submit button
if ($(pictureValue) == $("#contact-div-captcha-input input").val()) {
$("#submit").removeAttr("disabled");
}
};
equalCheck();
UPDATE
Fiddle here
UPDATE #2
$("#contact-div-captcha-input input").keyup(function(){
var inputValue = $("#contact-div-captcha-input input").val();
console.log(inputValue);
if (pictureValue === inputValue) {
$("#inputsubmit").removeAttr("disabled");
}
});
So I got it working 99.9%, now the only problem is that if someone were to backspace or delete the correct value they have inputted, the submit button does not then change back to disabled. Any pointers?
Known issue.
Give your button a name OTHER THAN submit. That name interferes with the form's submit.
EDIT
A link was requested for this -- I don't have a link for pure JavaScript, but the jQuery docs do mention this issue:
http://api.jquery.com/submit/
Forms and their child elements should not use input names or ids that
conflict with properties of a form, such as submit, length, or method.
Name conflicts can cause confusing failures. For a complete list of
rules and to check your markup for these problems, see DOMLint.
EDIT 2
http://jsfiddle.net/m55asd0v/
You had the CSS and JavaScript sections reversed. That code never ran in JSFiddle.
You never re-called equalCheck. I added a call to your keyUp handler.
For some reason you wrapped pictureValue inside a jQuery object as $(pictureValue) which couldn't have possibly done what you wanted.
Basic debugging 101:
A console.log inside of your equalCheck would have shown you that function was only called once.
A console log checking the values you were comparing would have shown
that you had the wrong value.
Basic attention to the weird highlighting inside of JSFiddle would have shown you had the code sections in the wrong categories.

Insert input if it does not exist

I am working on an email template editor where the user will select from a list of pre-existing templates and will be able to update the template as necessary. I had problems with using the CKEditor plugin across browsers and so I have attempted to create my own. When the user selects a template it opens in a modal window. To change the images I have included input tags which are removed upon close of the modal. This works so well and so good but if the user then wants to go back into the editor the input buttons are no longer there.
I want to add in the input button in the modal window if it does not exist. I have tried checking the length of the property but I am unable to return a value other than null whether it exists or not. My code is as follows:
function template1InputButtons() {
if ($("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
If I open it the first time the length comes up as one and so nothing is added as expected. If I remove and then click the button again length shows as 0 and input is added correctly as expected. If I then remove the input and click the button again the length comes up as 1 despite the control not existing.
Any ideas?
Try this:
function template1InputButtons() {
if (!$("#imageInput1T1")) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
}
and also assure that you have placed it inside ready function.
Try this:
if ($("body").find("#imageInput1T1").length == 0) {
$('<input id="imageInput1T1" type="file" name="newImage1T1" onchange="previewImage1T1(this)" />').insertBefore('.article_media');
}
Problem was a similar finding of class attribute article_media on the other modal my mistake thanks for the help anyway

Foundation checkbox value error

I'm using the Foundation 4 framework and I added a custom form into my page.
HTML:
<label for="checkbox2">
<input type="checkbox" id="checkbox2" style="display: none;">
<span class="custom checkbox"></span> <p> CHECKBOX TEST</p>
</label>
JS:
if($('#checkbox2').is(":checked")){
isnewsletter = 1;
} else {
isnewsletter = 0;
}
and even this
newsletter = $('#checkbox2').val(),
isn't working.
How can I check, if my checkbox is checked?
$('#checkbox2').change(function(){
if($(this).is(":checked")){
console.log(1);
} else {
console.log(0);
}
});
First checking works fine. If you add checked="checked" to your checkbox isnewsletter will be 1.
P.S. You don't mention any other way how you tick checkbox in your program. Your checkbox is not displayed on the page, so you cannot tick it manually.
The question isn't quite clear whether OP wants to check if checkbox is :checked on change, at any random moment during interaction on a page, or on validation using the Foundation 4 Abide library. I've run into issues with the custom form and toggling hidden fields, as well as validating hidden fields, and the custom form doesn't help. However, I've worked around it, but those are different questions.
The "custom" form does by default hide the input and create a span after it that gets the class "checked", and the property on the hidden checkbox doesn't visually appear in Chrome's developer toolbar (I haven't checked FireBug to see if that property appears). However, if you write a code based check of the property of the checkbox, it will return 'true':
$("#checkbox2").change(function() {
console.log($(this).is(":checked"));
console.log($(this).prop('checked'));
// set up if using either method above, your choice.
if( $(this).prop('checked')) {
// do stuff
}
});
Or you can check the span.checkbox.custom directly after the input for the class "checked":
$("#checkbox2").change(function() {
console.log($(this).next().hasClass("checked"));
// set up if statement using that logic above:
if($(this).next().hasClass("checked") ) {
// do stuff
}
});
Use the same logic to check whether the checkbox is checked at any point, just don't bother with the .change() function. These will return true if the box is checked:
$("#checkbox2").next().hasClass("checked");
$("#checkbox2").is(":checked");
$("#checkbox2").prop("checked");
Foundation 4 didn't have validation built into Abide, you'd have to add it in.
This requires adjusting Abide.
I answered that question here.

Dynamically created inputs with if else checkbox and multiple field validation

When the user clicks add more options, a from is created with javascript document.getElementById('addmore').innerHTML... It works great to display the form multiple times. I added a unique number each time to create unique IDs for each of the fields for submission. I have a checkbox that, if checked, needs to display another fields to get filled out:
document.getElementById('addmore').innerHTML += '<p><div class="required">*Type of Folder</div><label for="it09" class="hidelabel">Content Drive</label><input name="request['+fields+'][Type of Folder:]" id="cbpathCDB'+fields+'" type="checkbox" value="Content Drive" class="required" /><strong>Content Drive</strong> (A: drive)<br /><div id="pathCDB'+fields+'"><label for="newpathCDB"><span class="req">*Path to Content Drive Folder</span></label><input name="request['+fields+'][Path to Content Drive Folder:]" type="text" id="npcdb'+fields+'" size="50" class="required"/><br /><small>Path of folder to be created on Content Drive (A: drive)<br><em>(example: A:\drivefolder</em></small><br /></div></p>';
I have tried multiple ways (jquery included) of getting the next div, pathCDB+fields, to show when the checkbox is checked. It works fine without the +fields in there... see http://jsfiddle.net/kuVzV/4/ however, when I add the fields it fails to show/hide with the checkbox.
When the form is created though, the div doesn't show at first, just like it shouldn't... so I know the ID is correct. According to Firebug it is showing the correct ID with the field showing the correct # that is create...
I am at a loss right now.
Any suggestions on how to show/hide this div if the checkbox is checked for multiple inputs created dynamically?
Try checking out jQuery .show() and Jquery .hide(). I believe this is what you are looking for.
$(document).ready(function(){
$("#cbpathCDB1").on('click', $("#cbpathCDB1 input[type=checkbox]").is(":checked"), someFunction);
});
function someFunction(event){
if (event.target.checked){
$("#pathCDB1").hide('slow');
}
else{
$("#pathCDB1").show('slow');
}
}​
jsfiddle http://jsfiddle.net/FERMIS/7ThtT/6/ Here is an example with multiple fields.

Categories

Resources