If user is selecting file and after it if user is unchecking checkbox than file is also at there so I want to make it like a when user is unchecking checkbox than after file is must be remove. How can I make it? And which event handler is perfect for checkbox?
HTML CODE:
<div class="checkbox">
<label for="email">electronics
<input type="checkbox" name="product_category[]" value="electronics" id="product_category" class="electronics">
</label>
</div>
<div class="form-group" id="efileu" style="display:none;" >
<input type="file" name="checkboxfile0" id="efile" style="width:100%">
</div>
<div class="checkbox">
<label for="email">kitchen
<input type="checkbox" name="product_category[]" value="kitchen" id="product_category" class="kitchen">
</div>
<div class="form-group" id="kfileu" style="display:none;" >
<input type="file" name="checkboxfile1" id="kfile" style="width:100%">
</div>
<script>
$(".electronics").click(function(){
if(!$("#efileu").is(":visible")){
$("#efileu").show();
}
else{
$("#efileu").hide();
$("#efileu").val();
}
});
$(".kitchen").click(function(){
if(!$("#kfileu").is(":visible")){
$("#kfileu").show();
}
else{
$("#kfileu").hide();
}
});
</script>
use this one line of jQuery in your existing code that seems fine to me
else{
$("#efileu").hide();
$("#efileu").replaceWith($("#efileu").val('').clone(true)); //clear the values
}
else{
$("#kfileu").hide();
$("#kfileu").replaceWith($("#kfileu").val('').clone(true));//clear the values
}
Found a workaround that works:
$(".electronics").click(function() {
if (!$("#efileu").is(":visible")) {
$("#efileu").show();
} else {
var $el = $('#efileu');
$el.wrap('<form>').closest('form').get(0).reset();
$el.unwrap();
$("#efileu").hide();
}
Here's a JSFiddle to see it in action. Credit goes to Gyrocode.
Related
I am trying to create Javascript verification code for a form, so that each section of the form is verified after hitting "submit". I am having trouble writing the code so that the checkbox section of the form verifies that two or more boxes have been selected. I tried to start simple by writing the code so that a div, errorcheckbox, would display a message if no checkbox is selected at all. However it does not work. Here is the HTML and script for the code pertaining to the checkbox:
HTML:
<form action="#" method="POST">
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
and the Javascript:
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("#checkbox").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if (document.getElementById("checkbox").checked == false){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
Right now, the code does nothing. The errorcheckbox div doesn't appear, and there is no change in the console log if a checkbox item is selected. So, this is one problem I'm having. I still need to verify that two or more of the boxes are checked. I'm hoping to do this by adding an if else statement to the checkContactee function, but am not sure how.
Looking at your code I would recommend a couple of things. Your check boxes look like you want to capture multiple values for a contact type, so they should have the same name attribute. Each check box should have it's own label and where you have a label now you should use a fieldset and legend.
By wrapping the checkboxes in a fieldset we can then use that as part of the validation process.
$("document").ready(function() {
console.log("Loaded");
$("fieldset[data-mincheckboxchecked] [type=checkbox]").on("click", function() {
console.log("Click")
//Get the parent fieldset
let $parent = $(this).closest("fieldset[data-mincheckboxchecked]");
validateMultiCheckBox($parent);
});
});
function validateMultiCheckBox($parent) {
console.log($parent)
//Get minimum checked from the data attribute
let minCheked = $parent.data("mincheckboxchecked");
minChecked = parseInt(minCheked, 10);
//Get the number of checked checkboxes in the parent
let numCheked = $parent.find("[type=checkbox]:checked").length;
//Validation Logic
if (numCheked < minCheked) {
$parent.find(".error").html("<p>Please select at least " + minChecked + " option" + (minCheked !== 1 ? "s" : "") + "</p>");
$parent.find(".error").addClass("showerror");
return false;
} else {
$parent.find(".error").html("");
$parent.find(".error").removeClass("showerror");
return true;
}
}
$("#submit").click(function() {
var isValid = false;
var multiCheckValid = true;
//Validate each group of multi checkboxes
$("fieldset[data-mincheckboxchecked]").each(function() {
console.log(this);
if (!validateMultiCheckBox($(this))) {
multiCheckValid = false;
}
})
//Normally you'e set this to return false, leaving like
//this for demo purposes
console.log(multiCheckValid);
return isValid;
});
.error {
display: none;
color: red;
}
.error.showerror {
display: block;
}
fieldset label {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" method="POST">
<div class="contactForm">
<fieldset data-mincheckboxchecked="2">
<legend>Contactee Type: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="contactType" value="Individual">Individual</label>
<label><input type="checkbox" name="contactType" value="Catering">Business:Catering</label>
<label><input type="checkbox" name="contactType" value="Partner">Business:Partner</label>
</fieldset>
<fieldset data-mincheckboxchecked="1">
<legend>One Required: </legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="oneReq" value="1">A Thing</label>
<label><input type="checkbox" name="oneReq" value="2">Another Thing</label>
<label><input type="checkbox" name="oneReq" value="3">Yet another thing</label>
</fieldset>
<fieldset data-mincheckboxchecked="3">
<legend>Top 3 Movies: Three required</legend>
<div id="errorcheckbox" class="error"></div>
<label><input type="checkbox" name="movie" value="Top Gun">Top Gun</label>
<label><input type="checkbox" name="movie" value="Terminator">Terminator</label>
<label><input type="checkbox" name="movie" value="Sound Of Music">Sound OF Music</label>
<label><input type="checkbox" name="movie" value="Mission Impossible">Mission Impossible</label>
</fieldset>
</div>
<div class="button"><input type="button" name="submit" id="submit" value="Submit"></div>
</form>
This way it's extensible and not reliant on Ids.
You can use the :checked which the selector to get the checked items.
function validate() {
console.log('Total Checked = ' + $('.contactForm input[type="checkbox"]:checked').length);
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div class="contactForm">
<label for="checkbox" id="checkbox" name="checkbox">Contactee Type: </label><br>
<div id="errorcheckbox" class="error"></div>
<input type="checkbox" name="type1" value="Individual">Individual<br>
<input type="checkbox" name="type2" value="Catering">Business:Catering<br>
<input type="checkbox" name="type3" value="Partner">Business:Partner<br>
<button onclick="validate()">Validate</button>
</div>
use a class for your checkboxes and select that or use tag name and type to select tags,
you are using the id of a label tag for checking checkboxes
, use .is() method in jquery to check is checked
$("document").ready(function(){
console.log("Loaded");
$("#submit").click(function(){
checkContactee();
});
$("input[type='checkbox']").change(function(){
console.log("Something in contactee changed");
checkContactee();
});
function checkContactee(){
if ($("input[type='checkbox']").is(':checked'){
$("#errorcheckbox").html("<p>You missed this field</p>");
$("#errorcheckbox").addClass("showerror");
}
else{
$("#errorregarding").html("");
$("#errorregarding").removeClass("showerror");
}
}
var checkedCount=$("input[name^='type']:checked).length - this pulls all inputs, looks for those with the name beginning with "type", keep the ones that are checked, and returns how many are check (here, assigned to the checkedCount variable). I'll leave further validation/scolding of the user up to you
I have this piece of code from a salesforce visualforce page.
<div id="testId" class="row mb25 mt15">
<div class="col-md-6 plr0">
<p class="en">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
<p class="fr">Would you like to add a co-applicant?<span class="asteriskField">*</span> </p>
</div>
<div class="col-md-4 mt-5r">
<apex:selectRadio id="innerTestId" value="{!client.Would_you_like_to_recieve_future_promo__c}" styleClass="radio">
<div class="row">
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="Yes" itemValue="Yes"/>
</div>
</div>
<div class="col-sm-6">
<div class="radio pa-cus">
<apex:selectOption itemLabel="No" itemValue="No"/>
</div>
</div>
</div>
</apex:selectRadio>
</div>
</div>
When the Submit button is clicked I need to have a JQuery script to check weather the radio button is selected Yes or No so that I can perform some custom validation. I call this function by adding onclick="validateInnerTestId();" to Submit button.
My problem is that I am unable to read/check whether the radio button is chosen Yes or No or True or False. If I can find out what state they are in then I can do my
Here is my goal
<script type="text/javascript">
<script>
function validateInnerTestId()
{
if(innerTestId is Selected as Yes)
{
execute fucntionX()
}
else
{
execute functionY()
}
}
<script>
Here is some examples of how I have tried to read the value of the radio button:
alert($("#innerTestId").itemValue()); this line doesn't return anything
alert($("#innerTestId").val()); this line also doesn't return anything
and this if else always return no
if ($('innerTestId').is(':checked'))
{
alert("yes");
}
else
{
alert("no");
}
Does anyone has any idea on how to check for the radio button in this case?
Thanks
As #Andrea mentioned in the comments, you simply forgot the # in your selector. There is a simple example below demonstrating the usage. If your code still isn't working we will need more info.
Are you sure validateInnerTestId() is being called?
How is it being called?
$('#doit').on('click',function() {
var str = "";
if ($('#test').is(':checked')) {
str += "Toggle checked? YES\n"
} else {
str += "Toggle checked? NO\n"
}
if ($('#option1').is(':checked')) {
str += "Option checked: 1";
} else if ($('#option2').is(':checked')) {
str += "Option checked: 2";
} else {
str += "Option checked: NONE";
}
alert(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input id="test" name="toggle" type="checkbox" value="" />
<label for="toggle">Toggle</label>
</div>
<div>
<input type="radio" id="option1" name="options" value="1">
<label for="option1">Option 1</label>
<input type="radio" id="option2" name="options" value="2">
<label for="option1">Option 2</label>
</div>
<br />
<input id="doit" type="button" name="test" value="Tell me!" />
It might also be something to do with the ASP/SalesForce implementation? Perhaps some of the answers in this question might help: How to check if an option is selected?
VF tags use dynamic ids, you should do following:
function validateInnerTestId(){
if($('#{!component.innerTestId}').is(':checked')){
execute fucntionX()
}
else{
execute functionY()
}
}
I've searched a while for this, but can't find a solution. Basically, I have a simple form, that will by dynamic (up to 20 cycles can exist for an ID). The validation to delete the Cycles, say that there are 3 of them, 1, 2, and 3, is that you can delete #3, but you cannot delete #2 until you delete #3, and you cannot delete #1 until you delete #2.
So, on the front-end, I was thinking of a design that would disable all but the last checkbox, then as you check the last checkbox, the next previous checkbox would be enabled and be able to be checked, and so on. Then, the user would delete (through a Bootbox modal submit button callback, which is even a bit trickier).
Here's a simple form I was using to test with:
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox"><label><input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label></div>
<div class="checkbox"><label><input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label></div>
<div class="checkbox"><label><input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label></div>
</div>
</form>
How can you dynamically write JavaScript (I'm using jQuery 1.12.4) to achieve this? I'm hoping to have something in the ID's that can almost make a chain of enabling the checkboxes -- the last one being enabled by default since it's not dependent on others to be deleted, but, then enabling the other checkboxes on the fly as the one above it is enabled.
Can anyone help with this?
Thanks so much!
So you can do this using jquery:
Initially set all but the last checkbox disabled
Use a checkbox listener that will:
a. enable the preceeding checkbox on ticking
b. disable all preceeding checkbox when unticking
See demo below:
// Initialize : disable all but the last checkbox
$('#deleteCycles .checkbox:last').prevAll().each(function() {
$(this).find('input').attr('disabled', 'disabled');
});
// checbox listener
$('#deleteCycles .checkbox input').change(function() {
if ($(this).is(":checked")) {
// enable the checkbox just above
$(this).closest('.checkbox').prev('.checkbox').find('input').removeAttr('disabled');
} else {
// disable all checkboxes preceeding
$(this).closest('.checkbox').prevAll().each(function() {
$(this).find('input').attr({
'disabled': 'disabled',
'checked': false
});
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox">
<label>
<input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label>
</div>
<div class="checkbox">
<label>
<input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label>
</div>
<div class="checkbox">
<label>
<input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label>
</div>
</div>
</form>
$(function () {
$(':checkbox').attr('disabled', true).each(function (index, element) {
$(this).data('index', index);
}).change(function () {
if($(this).is(':checked'))
{
$(this).parents('.checkbox:first').prev().find(':checkbox').attr('disabled', null);
}
else
{
$(this).parents('form:first').find(':checkbox:lt(' + $(this).data('index') + ')').attr('checked', false).attr('disabled', true);
}
}).last().attr('disabled', null);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox"><label><input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes">Cycle 1</label></div>
<div class="checkbox"><label><input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes">Cycle 2</label></div>
<div class="checkbox"><label><input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes">Cycle 3</label></div>
</div>
</form>
Assuming sequential IDs, something like this might work.
Add a data-attribute that lets you reference the checkbox that the currently-active checkbox "depends on":
<form class="form-horizontal" id="deleteCycles" action="/deleteCyclesScript" method="post">
<div class="col-md-12" style="margin-top: 30px; margin-bottom: 10px;">
<div class="checkbox">
<label>
<input id="cycle1" type="checkbox" value="cycle1" class="dynamicCheckboxes" />
Cycle 1
</label>
</div>
<div class="checkbox">
<label>
<input id="cycle2" type="checkbox" value="cycle2" class="dynamicCheckboxes" data-dependsOn="#cycle1" />
Cycle 2
</label>
</div>
<div class="checkbox">
<label>
<input id="cycle3" type="checkbox" value="cycle3" class="dynamicCheckboxes" data-dependsOn="#cycle2" />
Cycle 3
</label>
</div>
</div>
</form>
Then, when the checkbox is toggled, check both it's checkstate and the "depends on" checkbox's checkstate:
$('.dynamicCheckboxes').on('change', function(e){
// hold reference to the current checkbox
var _this = $(this);
if(!_this.is(':checked')){
var dependsOn = _this.data('dependsOn');
if(dependsOn != ""){
if($(dependsOn).is(':checked')){
e.preventDefault();
// display some sort of error message
}
}
}
});
You could use the jQuery .prev function, as well, if your markup supports it (if the dependent checkbox always precedes the checkbox you're checking, in the markup).
I have a Twitter Bootstrap form that has 6 vertical check boxes. I need to have an input form field each time they select a checkbox. It could be in the form of a popup or maybe something that appears out to the right of the checkbox. I figure this is some kind of javascript function but I have no idea how to do so. Any suggestions would be greatly appreciated. Each textbox if selected should have a field that pops up asking them for how many years experience they have in this certain field. This will info will be collected via $_POST variables. So each checkbox popup should have its own unique name so i can post it.
<div class="form-group">
<label class="col-md-4 control-label" for="positionsought">Position Sought</label>
<div class="col-md-4">
<div class="checkbox">
<label for="positionsought-0">
<input type="checkbox" name="positionsought" id="positionsought-0" value="Cutting">
Cutting
</label>
</div>
<div class="checkbox">
<label for="positionsought-1">
<input type="checkbox" name="positionsought" id="positionsought-1" value="Sewing">
Sewing
</label>
</div>
<div class="checkbox">
<label for="positionsought-2">
<input type="checkbox" name="positionsought" id="positionsought-2" value="Upholstery">
Upholstery
</label>
</div>
<div class="checkbox">
<label for="positionsought-3">
<input type="checkbox" name="positionsought" id="positionsought-3" value="Frame Department">
Frame Department
</label>
</div>
<div class="checkbox">
<label for="positionsought-4">
<input type="checkbox" name="positionsought" id="positionsought-4" value="Mill Room">
Mill Room
</label>
</div>
<div class="checkbox">
<label for="positionsought-5">
<input type="checkbox" name="positionsought" id="positionsought-5" value="Cushion">
Cushion
</label>
</div>
<div class="checkbox">
<label for="positionsought-6">
<input type="checkbox" name="positionsought" id="positionsought-6" value="Any">
Any
</label>
</div>
</div>
</div>
Although you already have found an answer, I believe that this would work better for your situation since you say you will have 6 checkboxes. This dynamically creates input fields for each checkbox by their names and removes them when the checkbox is unchecked.
First add this function to each checkbox onclick="dynInput(this);"
<input type="checkbox" name="check1" onclick="dynInput(this);" />
and add this to wherever you would like the inputs to display.
<p id="insertinputs"></p>
Then simply add this javascript function to your head.
<script type="text/javascript">
function dynInput(cbox) {
if (cbox.checked) {
var input = document.createElement("input");
input.type = "text";
var div = document.createElement("div");
div.id = cbox.name;
div.innerHTML = "Text to display for " + cbox.name;
div.appendChild(input);
document.getElementById("insertinputs").appendChild(div);
} else {
document.getElementById(cbox.name).remove();
}
}
</script>
JsFiddle here: http://jsfiddle.net/brL6gy7r/
You can use JavaScript here to do the job. When the checkbox is clicked and checked (because you can also check out.) a dialog will pop-up with all input-fields you want. You can change the dialog part to your desires. but this part is your main function:
$(document).ready(function () {
$('#chkBox').click(function () {
if ($(this).is(':checked')) {
// create input field
} else {
// if checkbox is not checked.. dont show input field
}
});
});
For a full demo on how to do this with a dialog, click this link and observe
http://jsfiddle.net/Runman44/5vy1m233/
Notice that you will need jQuery (and jQuery UI if you want to use the dialog like me)
There is a zero-JavaScript version that is dead simple and works in all major browsers. It takes advantage of the :checked pseudo-class and the adjacency selector. It works with an arbitrary number of checkboxes.
HTML:
<input type="checkbox" />
<input type="text" />
CSS:
input[type=text] {
visibility:hidden;
}
input[type=checkbox]:checked + input[type=text] {
visibility:visible;
}
here is the live demo
If you prefer, you can use display:none and display:inline rather than the visibility property.
The example I've provided assumes that the text field immediately follows the checkbox in the markup, but some variant of sibling/child selectors can be used to select it no matter where it is, as long as it is either a sibling or child (direct or indirect) of the checkbox.
The Problem
I am trying to run some ajax on one my pages for my website, basically I have three checkboxes all of which on pageload are unselected, when a checkbox is clicked I need to be able load in via ajax the relevant HTML. This system is currently a PHP script that depending on what the POST is set returns a different view, so I think all I need to is send the POST via AJAX, but I need to do everytime a new checkbox is checked.
My HTML looks like this,
div class="segment">
<div class="label">
<label>Choose region: </label>
</div>
<div class="column w190">
<div class="segment">
<div class="input">
<input type="checkbox" checked="checked" class="radio checked" value="Y" name="area[Nationwide]" id="inp_Nationwide">
</div>
<div class="label ">
<label for="inp_Nationwide">Nationwide</label>
</div>
<div class="s"> </div>
</div>
</div>
<div class="column w190">
<div class="segment">
<div class="input">
<input type="checkbox" checked="checked" class="radio checked" value="Y" name="area[Lancashire]" id="inp_Lancashire">
</div>
<div class="label ">
<label for="inp_Lancashire">Lancashire</label>
</div>
<div class="s"> </div>
</div>
</div>
<div class="column w190">
<div class="segment">
<div class="input">
<input type="checkbox" checked="checked" class="radio" value="Y" name="area[West_Yorkshire]" id="inp_West_Yorkshire">
</div>
<div class="label ">
<label for="inp_West_Yorkshire">West Yorkshire</label>
</div>
<div class="s"> </div>
</div>
<div class="s"> </div>
</div>
</div>
My current attempt was to ascertain whether the input has been clicked so I have done this with my javascript, though this is probably wrong,
$('input.radio').click(function(){
if($(this).hasClass('clicked')) {
$(this).removeClass('clicked');
} else {
$(this).addClass('clicked');
}
});
You can do
$('input.radio').change(function(){ // will trigger when the checked status changes
var checked = $(this).attr("checked"); // will return "checked" or false I think.
// Do whatever request you like with the checked status
});
Also, if you say
three checkboxes all of which on
pageload are unselected
They should have checked=""
$("input:checkbox:checked")
will return all checkboxes that are currently checked.
The event handler .change() will bind to whenever the input changes, so for radios/checkboxes, it binds to whenever they're toggled, so no need to use click().
$(".radio:checkbox").change(function() {
var boxChecked = $(this).is(":checked");
if(boxChecked) {
...do ajax...
}
});
But this is kind of sloppy too, considering you could use the toggle() method instead. Plus, are you wanting to destroy the html when they uncheck? Or is this a one time deal?
$('input:checkbox').bind('click', function(e){
switch(e.target.id){
case 'someid':{
if($(this).is(':checked')){
//ajax call here
}
break;
}
case 'anotherid':{
// something
break;
}
}
});
Actually, you could change the arragment in checking first if the element
is checked or unchecked and then switch through the id's.. hmm