I want to have one checkbox that will check all others and I'm stuck. I'm trying to do that with a loop but that returns nothing.
It's an exercise so I cant change the html ids.
HTML:
<p>
Price for adds: <span id="price">0 usd</span>
</p>
</div>
<div class='panel'>
<div class='panel-body'>
<form>
<div class="checkbox">
<label><input type="checkbox">All adds</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="3.50">Additional cheese, 3,50 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="2.20">Salami, 2,20 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="5.00">Additional Ham, 5 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="4.10">pepper, 4,10 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox" data-price="3.50">Mushroms, 3,50 USD</label>
</div>
<div class="checkbox">
<label><input type="checkbox">Clear all</label>
</div>
<br>
<p>
<button class='btn btn-primary'>Submit</button>
</p>
</form>
</div>
</div>
JS:
$(function(){
$('.panel-body').on('change','input',function(e){
if($(this).parent().text()=='All adds'){
var inps = $('.checkbox input');
$(inps).each(function{
$(this).prop('checked', true)
})
var price = $('#price').html()
price = price.replace("USD", "");
price = parseFloat(price)
var add = $(this).attr('data-price')
if ($(this).prop('checked')) {
console.log($(this).text())
var totalPrice = parseFloat(add) + parseFloat(price)
$('#price').html(totalPrice.toFixed(2))
}
else {
var totalPrice = parseFloat(price) - parseFloat(add)
$('#price').html(totalPrice.toFixed(2))
}
})
})
1st you are missing () after function:
$(inps).each(function() {
$(this).prop('checked', true)
})
2nd use trim() to remove whitespace from both sides$(this).parent().text().trim()
3rd the if you have is closed with )} which is wrong, just use )
4th Instead of using each you can just do $('.checkbox input').prop('checked', true):
if ($(this).prop('checked')) {
$('.checkbox input').prop('checked', true)
} else {
$('.checkbox input').prop('checked', false)
}
This allowed you to uncheck all as well.
$(function() {
$('.panel-body').on('change', 'input', function(e) {
if ($(this).parent().text().trim() == 'All adds') {
if ($(this).prop('checked')) {
$('.checkbox input').prop('checked', true)
} else {
$('.checkbox input').prop('checked', false)
}
var price = $('#price').html()
price = price.replace("USD", "");
price = parseFloat(price)
var add = $(this).attr('data-price')
if ($(this).prop('checked')) {
console.log($(this).text())
var totalPrice = parseFloat(add) + parseFloat(price)
$('#price').html(totalPrice.toFixed(2))
} else {
var totalPrice = parseFloat(price) - parseFloat(add)
$('#price').html(totalPrice.toFixed(2))
}
}
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<p>
Price for adds: <span id="price">0 usd</span>
</p>
</div>
<div class='panel'>
<div class='panel-body'>
<form>
<div class="checkbox">
<label>
<input type="checkbox">All adds</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="3.50">Additional cheese, 3,50 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="2.20">Salami, 2,20 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="5.00">Additional Ham, 5 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="4.10">pepper, 4,10 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" data-price="3.50">Mushroms, 3,50 USD</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox">Clear all</label>
</div>
<br>
<p>
<button class='btn btn-primary'>Submit</button>
</p>
</form>
</div>
</div>
You have a typo:
$(inps).each(function{
$(this).prop('checked', true)
})
You should change this:
$(inps).each(function{
To this:
$(inps).each(function(){
Give your main checkbox an id "cAll". and use jQuery:
$("#cAll").click(function(){
$('input:checkbox').not(this).prop('checked', this.checked);
});
Related
In the below code, show/hide is not happening on page reload. If I check another radio button after page reloading, it's working. Help me to resolve the same.
$(window).load(function(){
$("[name=image_type]").on("change",imageTypeToggle);
})
function imageTypeToggle(){
let selectedValue, $showElements, $hideElements;
selectedValue = $(this).val();
$hideElements = $(this).parents(".image_video_sec").find(".image_sec, .video_sec");
$hideElements.hide().find("input").attr('disabled',true);
if(selectedValue == "0") {
$showElements = $(this).parents(".image_video_sec").find(".image_sec");
} else if(selectedValue == "1") {
$showElements = $(this).parents(".image_video_sec").find(".video_sec");
}
$showElements.show().find("input").attr('disabled',false);
};
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
One way to do it is to trigger a click on the radio button when the document loads. (I changed your $(window).load (which was throwing an error) to $(document).ready.
$("[name=image_type]").eq(0).trigger('click')
$(document).ready(function() {
$("[name=image_type]").on("change", imageTypeToggle);
$(".image_video_sec").each(function() {
$(this).find("[name=image_type]").eq(0).trigger('click')
})
})
function imageTypeToggle() {
let selectedValue, $showElements, $hideElements;
selectedValue = $(this).val();
$hideElements = $(this).parents(".image_video_sec").find(".image_sec, .video_sec");
$hideElements.hide().find("input").attr('disabled', true);
if (selectedValue == "0") {
$showElements = $(this).parents(".image_video_sec").find(".image_sec");
} else if (selectedValue == "1") {
$showElements = $(this).parents(".image_video_sec").find(".video_sec");
}
$showElements.show().find("input").attr('disabled', false);
};
.image_sec,
.video_sec {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
<div class="image_video_sec">
<label class="on">
<input type="radio" name="image_type" value="0" checked>R1
</label>
<label>
<input type="radio" name="image_type" value="1">R1
</label>
<dl class="image_sec">Image</dl>
<dl class="video_sec">Video</dl>
</div>
I have few checkboxes. When I click on any of them I pass the value to span. Everything seems to work fine but there's something that I can't resolve. When I click first time value is passed to my span (checkbox is checked) but when I unclick this checkbox, value is passing to span again instead of delete it from my span. Next thing, when I want to write my own text I have other checkbox for that. When I click on it I see input. I cant write text and it will be appended to my span. I want to remove this value too when I unclick this checkbox. Last thing, I want to add red border to empty elements. Anyone could help me?
$('.checkbox').on('click', function(){
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
check whether the event is fired when the checkbox is checked or not checked.
$('.checkbox').on('click', function(){
if($(this).is(':checked')){
//do you logic when the checkbox is checked.
}else{
//do your logic when the checkbox is not checked.
}
});
You need to loop over all checkboxes when each checkbox is clicked
Note I wrapped the whole thing in the label.
$('.component-other-value, .fruits').on('change', function() {
var fruits = [], other = [];
$('.component-other-value, .fruits').each(function() {
if (this.checked) {
var dataName = $(this).attr('data-product');
var value = $(this).val();
if (dataName) other.push(value)
else fruits.push(value)
}
});
$('#summary_fruits').text(fruits.join(","));
$('#summary_other_fruits').text(other.join(","));
});
$('.component-other').on('click', function() {
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<img src="img/ananas.png">
<p class="description">Ananas</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<img src="img/jablko.png">
<p class="description">Jabłko</p>
</label>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<img src="img/owoce-wlasne.png">
<p class="description">Własna propozycja</p>
</label>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<label>
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<img src="img/owoce-brak.png">
<p class="description">Bez owoców</p>
</label>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
$('.checkbox').on('click', function(){
var check = $(this);//PROPERTIES OF CLICKED CHECKBOX
var dataAttr = $(this).attr('name');
var dataAttrVal = $(this).val();
if (check.prop('checked')==true){ // check weather checkbox is checked.
$('[name="' + dataAttr + '-value"]').append(dataAttrVal + ", ");
$('#summary_' + dataAttr).append(dataAttrVal + ", ");
}
else { //if not remove the occurence of value that you unchecked
str = $('#summary_' + dataAttr).html();
$('#summary_' + dataAttr).html(str.replace(dataAttrVal+", ",""));
}
});
$('.component-other-value').on('change touchstart tap', function(){
var dataName = $(this).attr('data-product');
var value = $(this).val();
$('#summary_other_' + dataName).text(value);
$('[name="' + dataName + '-value"]').append(value + ", ");
});
$('.component-other').on('click', function(){
$(this).closest('.container')
.find('.component-other-value')
.prop("disabled", !this.checked);
});
input:disabled {
opacity: 0;
}
input:enabled {
opacity: 1;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-pineapple" value="Ananas" class="fruits checkbox">
<label for="fruit-pineapple"><img src="img/ananas.png"></label>
<p class="description">Ananas</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-apple" value="Jabłko" class="fruits checkbox">
<label for="fruit-apple"><img src="img/jablko.png"></label>
<p class="description">Jabłko</p>
</div>
</div>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruits-oth" class="component-other">
<label for="fruits-oth"><img src="img/owoce-wlasne.png"></label>
<p class="description">Własna propozycja</p>
</div>
</div>
<input type="text" name="fruits-other" id="fruits-other" class="component-other-value" data-product="fruits" placeholder="Wpisz owoce" disabled>
<div class="col-sm-3">
<div class="input-item">
<input type="checkbox" name="fruits" id="fruit-nofruit" value="Bez owoców" class="fruits checkbox">
<label for="fruit-nofruit"><img src="img/owoce-brak.png"></label>
<p class="description">Bez owoców</p>
</div>
</div>
</div>
<p>
Owoce: <br>
<span id="summary_fruits" class="summary"></span>
<span id="summary_other_fruits" class="summary" style="border-bottom: 1px solid red;"></span>
</p>
</div>
I am using this codepen as a basis.
HTML
<form>
<div>
<input type="radio" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
jQuery
$("input").on("click", function() {
$("#log").html($("input:checked").val() + "");
});
I have changed the radio buttons to checkboxes - but I would like to alter the js so that every selected item is then shown at the bottom of the list, rather than just the first.
The purpose is for a self awareness exercise - i.e. the user could select all statements which apply to them from a long list, and then they get an output that narrows it down to just the ones they've chosen. The form response doesn't need to be saved/submitted anywhere.
How can this be done?
$( "input" ).on( "click", function(e) {
if(e.currentTarget.checked){
var div = document.createElement("p");
div.id=e.target.value+"1";
div.innerHTML=e.target.value;
var tar=document.getElementById("log");
tar.appendChild(div);
} else {
var tag = document.getElementById(e.target.value+"1");
tag.parentNode.removeChild(tag);
}
});
You can try this its working.
Now when you click orange displayed and unchecked removed.
You need to make a couple of changes
If want to be able to select multiple radio buttons, then either keep their names different or use checkboxes.
Maintain an attribute wasChecked to toggle the checked property.
You need to iterate the checked boxes and then get their values.
Demo
$("input").on("click", function(e) {
var val = [];
var wasChecked = $(this).attr( "wasChecked" ) == "true";
if ( wasChecked )
{
$(this).prop( "checked", false );
}
else
{
$(this).prop( "checked", true );
}
$(this).attr( "wasChecked", $(this).prop( "checked") );
$("input:checked").each( function(){
val.push( $(this).val() );
});
$("#log").html( val.join( "," ));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="radio" name="fruit1" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="radio" name="fruit2" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="radio" name="fruit3" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
a lot of jQuery function like .val() are designed to operate on a single element, i.e., $("input#first-name").val(), and so only return the value for the first element matched if there are multiple matches.
you will probably need a loop to extract a value for each element. fortunately, jQuery provides a function to do this as well.
$( "input" ).on( "click", function() {
var html = "";
$( "input:checked" ).each(function() {
// "this" in this context is the jQuery element in this position in the list
html += $(this).val() + "";
}
$( "#log" ).html(html);
});
$( ":checkbox" ).on('change',function(){
var li_id = 'li_'+$(this).attr('id');
if(this.checked){
$('#list').append("<li id="+li_id+">"+$(this).val()+"</li>")
}else{
$('#'+li_id).remove();
}
})
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<ul id='list'>
</ul>
This is just a simple example to add and remove items from the list if they're checked or not. At least it gives you an idea on how you can achieve it.
Now you have an array. So, maybe you need something like this?
$( "input" ).on( "click", function() {
var selectedItems = $( "input:checked" );
var results = "";
for(var i = 0; i < selectedItems.length; i++){
if(i > 0) results += ", ";
results += selectedItems[i].value;
}
$( "#log" ).html( results );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
function add(element)
{
var fruits=document.getElementById("log").innerHTML;
var fruit=element.value;
if(fruits=="")
{
document.getElementById("log").innerHTML = fruit.toString();
}
else
{
if(document.getElementById(element.id).checked == true)
{
fruits= fruits+' '+fruit.toString();
}
else
{
fruits = fruits.replace(element.value,'');
}
document.getElementById("log").innerHTML=fruits;
}
}
<form>
<div>
<input type="checkbox" value="orange" id="orange" onclick="add(this);">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" value="apple" id="apple" onclick="add(this);">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" value="banana" id="banana" onclick="add(this);">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
Plain JavaScript solutions:
With one loop:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked"),
res = new Array(checkboxes.length);
function checkChecked() {
[].forEach.call(checkboxes, (checkbox, i) => {
checkbox.addEventListener("change", function() {
checkbox.checked ? res[i] = checkbox.value : res[i] = "";
checked.innerHTML = res.join(",").replace(/(^[,]+)|([,]+$)/g, "").replace(/(,){2,}/g, ",");
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
With two loops:
var form = document.getElementById("myForm"),
checkboxes = form.querySelectorAll("input[type=checkbox]"),
checked = document.getElementById("checked");
function getResult() {
var res = "";
[].forEach.call(checkboxes, checkbox => {
checkbox.checked ? res += checkbox.value + "," : false
})
res = res.replace(/(,$)/, "");
return res;
}
function checkChecked() {
[].forEach.call(checkboxes, checkbox => {
checkbox.addEventListener("change", function() {
checked.innerHTML = getResult();
})
})
}
checkChecked();
<form id="myForm">
<div>
<input type="checkbox" name="fruit" value="orange" id="orange">
<label for="orange">orange</label>
</div>
<div>
<input type="checkbox" name="fruit" value="peach" id="orange">
<label for="orange">peach</label>
</div>
<div>
<input type="checkbox" name="fruit" value="apple" id="apple">
<label for="apple">apple</label>
</div>
<div>
<input type="checkbox" name="fruit" value="banana" id="banana">
<label for="banana">banana</label>
</div>
<div id="log"></div>
</form>
<div id="checked"></div>
I am developing form.
What I need is when a user tries to go to another page with empty VISIBLE fields/checkboxes/radios these fields/checkboxes/radios should become red.
Filters for checkboxes: min 1, max 5.
My jQuery
const max = 5;
const min = 1;
const minCheckedCheckboxes = 1;
$('input.checkbox').on('click', function(evt) {
const checkboxes = $(this).closest('.cd-form-list-inner').find('input:checked');
if(checkboxes.length > max) {
alert('You can select only 5 checkboxes');
return false;
}
});
$('.next').click(function() {
let error = false;
$(['input[required]:visible', 'textarea[required]:visible']).each(function(index, selector) {
$(selector).each(function(index, input) {
error = error == true ? error : $(input).val() == '';
});
});
$('.parent:visible').each(function(index, group){
if(error == true) {
error = error;
}
else {
error = $('input:checked', group).length < minCheckedCheckboxes;
}
});
if(error == false) {
error =! $('input[type=radio]:required').is(':checked');
}
if(error) {
$('input[required]:visible, textarea[required]:visible').removeClass("error");
$('input[required]:visible, textarea[required]:visible').filter(function() {
return !this.value;
}).addClass('error');
return alert('Not all required fields are filled');
}
alert('All required fields are filled');
});
Here is jsFiddle
Check if below code works for you!
Looped on all desired inputs.
Checked the input type while looping, accordingly created the condition to add the error class, also maintained the elem on which error class needs to be added.
Then if condition is true then added error class to elem.
const max = 5;
const min = 1;
$('.next').click(function() {
$('input[required]:visible,textarea[required]:visible,input[type="checkbox"]:visible').each(function(index, selector) {
var elem;
if ($(this).is(":checkbox") || $(this).is(":radio")) {
var pDiv = $(this).parents("div").first();
var condition = false;
elem = pDiv;
if ($(this).is(":radio")) {
condition = pDiv.find("[type='radio']:checked").length <= 0
} else {
condition = pDiv.find("[type='checkbox']:checked").length < min || pDiv.find("[type='checkbox']:checked").length > max;
}
} else {
condition = !$(this).val();
elem = $(this);
}
if (condition) {
elem.addClass('error');
} else {
elem.removeClass('error');
}
});
});
.error {
background-color: pink;
border-color: red;
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<p>press button</p>
<input type="text" required/>
<input type="text" required style="display: none" />
<div>
<textarea cols="5" required placeholder="textarea"></textarea>
</div>
<div>
<textarea cols="5" required placeholder="textarea" style="display:none"></textarea>
</div>
<div class="parent">
<p>this div should be red</p>
<div>
<input type="radio" required>
</div>
</div>
<div class="parent" display: none>
<p>this div shouldn't be red</p>
<div>
<input type="radio" checked required>
</div>
</div>
<div style="display:none">
<p>this div shouldn't be red</p>
<input type="radio" required>
</div>
<div class="parent">
<p>this div shouldn't be red</p>
<div class="cd-form-list-inner checkboxes">
<input type="checkbox" class="checkbox" checked>
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
</div>
</div>
<div class="parent" style="display: none;">
<p>this div shouldn't be red</p>
<div class="cd-form-list-inner checkboxes">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
</div>
</div>
<div class="parent">
<p>this div should be red</p>
<div class="cd-form-list-inner checkboxes">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
<input type="checkbox" class="checkbox">
</div>
</div>
<div>
<button class="next">Next page</button>
</div>
$("#button").click(function () {
var pp = []
var ing = []
for (var q = 1; q <= 6; q++) {
pp[q - 1] = $('input[name=P' + (q) + ']').is(":checked");
ing[q - 1] = $('div#ingp' + (q) + '').show();
}
for (var q = 1; q <= 6; q++) {
if (pp[q - 1] == true) {
ing[q - 1];
}
}
});
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="ingp1"></div>
<div id="ingp2"></div>
<div id="ingp3"></div>
<div id="ingp4"></div>
<div id="ingp5"></div>
<div id="ingp6"></div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So the problem I have is that when I look if one or more of P1 to P6 is check then it shows all 6 div with id ingp1 to ingp6.
I want it to show ingp1 when P1 is checked, and ingp3 when P3 is checked. You get it.
How do I do this (small thing I am only allowed to use javascript and jquery).
First of all add a common class names for the elements in the form and the div's in the container as I have given test1,test2 etc.
$('document').ready(function() {
var test
$("#Pi input[ type = 'checkbox']").click(function() {
var test = this.className
if ( this.checked == true )
{
$('#ingredienten .'+test).show()
console.log($('#ingrediënten .'+test))
}
else
{
$('#ingrediënten .'+test).hide()
}
})
})
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" class = "test1" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" class = "test2" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" class = "test3" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" class = "test4" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" class = "test5" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" class = "test6" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingredienten">
<div>
<h1>Kies extra ingredienten</h1></div>
<div id="ingp1" class = "test1">
</div>
<div id="ingp2" class = "test2">
</div>
<div id="ingp3" class = "test3">
</div>
<div id="ingp4" class = "test4">
</div>
<div id="ingp5" class = "test5">
</div>
<div id="ingp6" class = "test6">
</div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
</body>
<html>
Then take the class name of the clicked check-box and search the div with the class name of this check-box and show or hide the div depending on its checked property.
try this
for (var q = 1; q <= 6; q++)
{
if ( $( 'input[ name = "P' + q + '"]').is(":checked") )
{
$( 'div#ingp' + q ).show();
}
}
$("#button").click(function () {
$('input[name^=P]').each(function () {
var idx = this.name.replace('P', '');
$('div#ingp' + idx).toggle(this.checked);
});
});
In words
for each <input> whose name starts with 'P',
find the associated <div> with the proper ID
toggle its visibility based on whether the <input> is checked or not
#Ttech thanks for clarifying the SO to me. Here's my solution. I slightly changed the markup in the part concerning the ids of the extra ingredients section (the divs).
Please, check my working example and see if this is what you need.
$('#ingrediënten div').hide();
$('#knop').on('click', function() {
$('#ingrediënten div').hide();
var $checkedOptions = $('#Pi input[type=checkbox]').filter(':checked'),
$extraIngredients = $('#ingrediënten div');
$checkedOptions.each(function() {
var id = $(this).attr('name');
$extraIngredients.filter('[id=' + id + ']').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="P1">
Extra ingredient 1
</div>
<div id="P2">
Extra ingredient 2
</div>
<div id="P3">
Extra ingredient 3
</div>
<div id="P4">
Extra ingredient 4
</div>
<div id="P5">
Extra ingredient 5
</div>
<div id="P6">
Extra ingredient 6
</div>
<br>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>