JavaScript: after append script is not working - javascript

I have script which is creating number of new inputs according to inserted value to input.
New inputs are extended with another script but this script is not working.
This script is working when appended html code is not in js but in index.html. Then this script works fine but the first script is not launched.
CODE:
$(function () {
$(".main-input1").on("change", function () {
$(".activityType1.active").removeClass("active");
var subList = $(".activityType1." + $(this).val());
if (subList.length) {
subList.addClass("active");
}
});
});
const button = document.querySelector('button');
const input = document.getElementById('NumberOfNights');
const wrapper = document.querySelector('div.wrapper-activity');
function generateItems(numOfItems) {
let html = "";
wrapper.innerHTML = "";
for(i = 1; i <= numOfItems; i++) {
html += `
<style>
.activityType1 {
display: none;
}
.activityType1.active {
display: inline-block;
}
</style>
<section class="activity-wrapper">
<label for="activity">Activity ${i}</label>
<div class="select-style">
<select id="activity" style="width: 300px;" name="activity" class='main-input1'>
<option value='none' disabled selected>--</option>
<option value='Hiking'>Hiking</option>
<option value='Biking'>Biking</option>
<option value='Tasting'>Tasting</option>
</select>
</div>
</section>
<section class='activityType1 Hiking activity-wrapper'>
<div class="bottom-row">
<label class="hiking-activity">
<input type="radio" name="hiking-activity" value="National park Pieniny">
<img src="../assets/img/3.jpg">
</label>
<label class="hiking-activity">
<input type="radio" name="hiking-activity" value="National park Slovak paradise">
<img src="../assets/img/4.jpg">
</label>
</div>
</section>
<section class='activityType1 Biking activity-wrapper'>
<div class="top-row">
<label class="biking-activity">
<input type="radio" name="biking-activity" value="National park High Tatras">
<img src="../assets/img/5.jpg">
</label>
<label class="biking-activity">
<input type="radio" name="biking-activity" value="National park Pieniny">
<img src="../assets/img/6.jpg">
</label>
</div>
</section>
<section class='activityType1 Tasting activity-wrapper'>
<div class="top-row">
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Beer tasting">
<img src="../assets/img/10.jpg">
</label>
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Whisky tour">
<img src="../assets/img/11.jpg">
</label>
</div>
<div class="bottom-row">
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Tokaj wine tour">
<img src="../assets/img/12.jpg">
</label>
</div>
</section>
`;
};
return html;
};
button.addEventListener('click',() => {
const n = parseInt(input.value);
if (n) {
wrapper.innerHTML = generateItems(n);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="NumberOfNights" placeholder="--" type="number" name="nights" max="5">
<button type="button">Continue</button>
<div class="wrapper-activity"></div>

Change it to $(document).on('change', '.main-input1', function () { this way your first script can be launched on the appended code.
$(function () {
$(document).on('change', '.main-input1', function () {
$(".activityType1.active").removeClass("active");
var subList = $(".activityType1." + $(this).val());
if (subList.length) {
subList.addClass("active");
}
});
});
const button = document.querySelector('button');
const input = document.getElementById('NumberOfNights');
const wrapper = document.querySelector('div.wrapper-activity');
function generateItems(numOfItems) {
let html = "";
wrapper.innerHTML = "";
for(i = 1; i <= numOfItems; i++) {
html += `
<style>
.activityType1 {
display: none;
}
.activityType1.active {
display: inline-block;
}
</style>
<section class="activity-wrapper">
<label for="activity">Activity ${i}</label>
<div class="select-style">
<select id="activity" style="width: 300px;" name="activity" class='main-input1'>
<option value='none' disabled selected>--</option>
<option value='Hiking'>Hiking</option>
<option value='Biking'>Biking</option>
<option value='Tasting'>Tasting</option>
</select>
</div>
</section>
<section class='activityType1 Hiking activity-wrapper'>
<div class="bottom-row">
<label class="hiking-activity">
<input type="radio" name="hiking-activity" value="National park Pieniny">
<img src="../assets/img/3.jpg">
</label>
<label class="hiking-activity">
<input type="radio" name="hiking-activity" value="National park Slovak paradise">
<img src="../assets/img/4.jpg">
</label>
</div>
</section>
<section class='activityType1 Biking activity-wrapper'>
<div class="top-row">
<label class="biking-activity">
<input type="radio" name="biking-activity" value="National park High Tatras">
<img src="../assets/img/5.jpg">
</label>
<label class="biking-activity">
<input type="radio" name="biking-activity" value="National park Pieniny">
<img src="../assets/img/6.jpg">
</label>
</div>
</section>
<section class='activityType1 Tasting activity-wrapper'>
<div class="top-row">
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Beer tasting">
<img src="../assets/img/10.jpg">
</label>
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Whisky tour">
<img src="../assets/img/11.jpg">
</label>
</div>
<div class="bottom-row">
<label class="tasting-activity">
<input type="radio" name="tasting-activity" value="Tokaj wine tour">
<img src="../assets/img/12.jpg">
</label>
</div>
</section>
`;
};
return html;
};
button.addEventListener('click',() => {
const n = parseInt(input.value);
if (n) {
wrapper.innerHTML = generateItems(n);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="NumberOfNights" placeholder="--" type="number" name="nights" max="5">
<button type="button">Continue</button>
<div class="wrapper-activity"></div>

Related

jQuery - Assign the click function to the radio input

What I would like to do is assign both the checked value and the click function to the radio input located inside the parent div.
I currently have this code but it only works for assigning the checked value. The click () function does not work:
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
</div>
</div>
<script>
jQuery('.contPosition').click(function () {
var val = $(this).find('input:radio').prop('checked')?false:true;
$(this).find('input:radio').prop('checked', val);
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input').click(function(){
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
});
//THIS FUNCTION DOES NOT WORK AS EXPECTED
jQuery('.contPosition input[type=radio]').click(function(){
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
</script>
I dont know what you want to achieve exactly but only one click event could replace all the other event as below snippet :
$(function() {
//should be ".contPosition input[type=radio]"
$('.contPosition input[type=radio]').click(function(e) {
var curCls = $(this).attr('class');
$(`.contPrintPosition > input.${curCls}`).val("Test");
if (this.previous) {
this.checked = false;
}
this.previous = this.checked;
});
})
.contPrintPosition input::after {
content: attr(value);
width:100%;
margin-left:15px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="contPosition">
<div class="contPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPosition">
<input type="radio" class="posPrint3" />
</div>
</div>
<div id="contPrintPosition">
<div class="contPrintPosition">
<input type="radio" class="posPrint1" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint2" />
</div>
<div class="contPrintPosition">
<input type="radio" class="posPrint3" />
</div>
</div>

Create a canvasjs on submit on a dynamically generated element

NEW to javascript, jquery, and CanvasJS!
Here's my problem:
As you can notice, I'm going to submit a bunch of data with ajax. Since some don't exist, I'm gonna attach the event onsubmit, to make it works.
Now, my problem is the chart: I'm using CanvasJS to create my chart, and right before the code to make it happens, I created a div dynamically with the id chartContainer, and right after I will initiate the cart with the function CanvasJS.Chart().
The problem is that, if I create the div in the html file, the code will work, but if I will create the div in the script, the code will fail because:
CanvasJS Error: Chart Container with id "chartContainer" was not found.
How can I overcome the problem?
$(document).ready(function() {
$(document).on('submit', 'form', function(event) {
$.ajax({
type: 'POST',
url: $(this).attr("action"),
data: $(this).serialize(),
dataType: 'json',
encode: true
}).done(function(data) {
var result = data.kg / Math.pow((data.centimeter / 100), 2);
var result3 = result.toFixed(2);
var result2 = '<div class="results">' + result.toFixed(2);
result2 += '<div id="clickhere">back</div>';
if (result > 25) {
result2 += '<div>Your should loose at least the 5% of your weight</div>'
} else if (result > 18.5) {
result2 += '<div>Your weight is ideal</div>'
} else {
result2 += '<div>You\'re underweight, you should take integrate your diet with different food and eat more often</div>'
}
result2 += '<div id="chartContainer"></div>'
var gauge = {
title: {
text: "BMI"
},
data: {
y: result3
},
maximum: 30
};
var chart = new CanvasJS.Chart("chartContainer");
createGauge(chart);
function createGauge(chart) {
gauge.unoccupied = {
y: gauge.maximum - gauge.data.y,
color: "#e3e3e3",
toolTipContent: null,
highlightEnabled: false,
click: function() {
gauge.unoccupied.exploded = true;
}
}
gauge.data.click = function() {
gauge.data.exploded = true;
};
if (!gauge.data.color)
gauge.data.color = "#6b58f2";
gauge.valueText = {
text: gauge.data.y.toString(),
verticalAlign: "center"
};
var data = {
type: "doughnut",
dataPoints: [{
y: gauge.maximum,
color: "transparent",
toolTipContent: null
},
gauge.data,
gauge.unoccupied
],
};
if (!chart.options.data)
chart.options.data = [];
chart.options.data.push(data);
if (gauge.title) {
chart.options.title = gauge.title;
}
if (!chart.options.subtitles)
chart.options.subtitles = [];
chart.options.subtitles.push(gauge.valueText);
chart.render();
}
result2 += '</div>';
var clickhere = $('#clickhere');
var form = $('form');
$('form').replaceWith(result2);
$(document).on("click", "#clickhere", function() {
$('.results').remove();
});
});
event.preventDefault();
});
});
<form action="/send.php" id="formid" method="post">
<div class="row">
<div class="col-md-4">
<div class="row">
<h3 class="col-md-9">Height</h3>
<p class="switch col-md-3">cm</p>
</div>
<div class="antbits-bmi-form_section_layer antbits-bmi-metric">
<div>
<label for="antbits-bmi-cm" class="antbits-bmi-form_section_label">Centimetres</label>
<input class="form-control" id="antbits-bmi-cm" aria-describedby="antbits-bmi-form_height-error" alt="height, centimeters" inputmode="numeric" type="text" step="0.1" min="0" maxlength="5" name="centimeter" placeholder="cm" required="">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<h3 class="col-md-9">Weight</h3>
<p class="col-md-3 switch">st, lb</p>
</div>
<div class="antbits-bmi-form_section_layer antbits-bmi-imperial">
<div>
<label for="antbits-bmi-kg" class="antbits-bmi-form_section_label">Kg</label>
<input class="form-control" id="antbits-bmi-kg" placeholder="Kg" alt="kg" type="text" inputmode="numeric" min="0" maxlength="2" name="kg" required="">
</div>
</div>
</div>
<div class="col-md-4">
<h3>Age</h3>
<div class="antbits-bmi-form_section_inner">
<div>
<label for="antbits-bmi-age" class="antbits-bmi-form_section_label antbits-accessible_hidden">Age in years</label>
<select class="form-control" id="age" name="age" required=""></select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<h3>Sex<small>?</small></h3>
<div class="info hide">
<h3>Sex<small>?</small></h3>
<p>For children, BMI centile is gender specific. For both children and adults, we give more personalised information based on whether you are male or female.</p>
</div>
<div class="radio-click row height">
<div class="radio-inline col-md-6 checked" id="male">
<input type="radio" name="optradio" value="male">Male
</div>
<div class="radio-inline col-md-6" id="female">
<input type="radio" name="optradio" value="female">Female
</div>
</div>
</div>
<div class="col-md-4">
<h3>Ethnic Group (optional)<small>?</small></h3>
<div class="info hide">
<h3>Ethnic</h3>
<p>Black, Asian and other minority ethnic groups with a BMI of 23 or more have a higher risk of getting type 2 diabetes and other long term illnesses.</p>
</div>
<select class="form-control" id="antbits-bmi-ethnicity" alt="Ethnic group" name="ethnic" required="">
<option disabled selected value class="antbits-bmi-form_option">Not stated</option>
<option value="2" class="antbits-bmi-form_option">White</option>
<option value="3" class="antbits-bmi-form_option">Black Caribbean</option>
<option value="4" class="antbits-bmi-form_option">Black African</option>
<option value="5" class="antbits-bmi-form_option">Indian</option>
<option value="6" class="antbits-bmi-form_option">Pakistani</option>
<option value="7" class="antbits-bmi-form_option">Bangladeshi</option>
<option value="8" class="antbits-bmi-form_option">Chinese</option>
<option value="9" class="antbits-bmi-form_option">Middle Eastern</option>
<option value="10" class="antbits-bmi-form_option">Mixed</option>
<option value="11" class="antbits-bmi-form_option">Other</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Activity Level</h3>
<p>So we can personalize your results</p>
<div class="slidercontainer">
<input type="range" min="0" max="150" value="75" class="slider" id="myRange" name="range">
<div class="row center height activity">
<div class="col-md-4">
<p>Inactive</p>
</div>
<div class="col-md-4">
<p>Moderate Active</p>
</div>
<div class="col-md-4">
<p>Active</p>
</div>
</div>
<div class="row center height">
<div class="col-md-4">
<p>Less than 30 minutes a week</p>
</div>
<div class="col-md-4">
<p>Between 30 and 60 minutes a week</p>
</div>
<div class="col-md-4">
<p>Between 60 and 150 minutes a week</p>
</div>
</div>
<p>Value: <span id="demo"></span></p>
</div>
</div>
</div>
<!-- <div id="chartContainer"></div> -->
<div class="center">
<input type="submit" value="Calculate">
</div>
</form>
Append the div to the document before calling the chart.
You need to move
result2 += '</div>';
var clickhere = $('#clickhere');
var form = $('form');
$('form').replaceWith(result2);
to right before
var chart = new CanvasJS.Chart("chartContainer");
createGauge(chart);
You can even more the function outside as well. It is not needed inside the document.ready
And this
$(document).on("click", "#clickhere", function() {
$('.results').remove();
});
does not belong in the .done either
Here is a better version
function createGauge(chart) {
gauge.unoccupied = {
y: gauge.maximum - gauge.data.y,
color: "#e3e3e3",
toolTipContent: null,
highlightEnabled: false,
click: function() {
gauge.unoccupied.exploded = true;
}
}
gauge.data.click = function() {
gauge.data.exploded = true;
};
if (!gauge.data.color)
gauge.data.color = "#6b58f2";
gauge.valueText = {
text: gauge.data.y.toString(),
verticalAlign: "center"
};
var data = {
type: "doughnut",
dataPoints: [{
y: gauge.maximum,
color: "transparent",
toolTipContent: null
},
gauge.data,
gauge.unoccupied
],
};
if (!chart.options.data)
chart.options.data = [];
chart.options.data.push(data);
if (gauge.title) {
chart.options.title = gauge.title;
}
if (!chart.options.subtitles)
chart.options.subtitles = [];
chart.options.subtitles.push(gauge.valueText);
chart.render();
}
$(function() {
$(document).on("click", "#clickhere", function() {
$('.results').remove();
});
$(document).on('submit', 'form', function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: $(this).attr("action"),
data: $(this).serialize(),
dataType: 'json',
encode: true
}).done(function(data) {
var result = data.kg / Math.pow((data.centimeter / 100), 2);
var result3 = result.toFixed(2);
var result2 = '<div class="results">' + result.toFixed(2);
result2 += '<div id="clickhere">back</div>';
if (result > 25) {
result2 += '<div>Your should loose at least the 5% of your weight</div>'
} else if (result > 18.5) {
result2 += '<div>Your weight is ideal</div>'
} else {
result2 += '<div>You\'re underweight, you should take integrate your diet with different food and eat more often</div>'
}
result2 += '<div id="chartContainer"></div>'
result2 += '</div>';
var form = $('form');
$('form').replaceWith(result2);
var gauge = {
title: {
text: "BMI"
},
data: {
y: result3
},
maximum: 30
};
var chart = new CanvasJS.Chart("chartContainer");
createGauge(chart);
});
});
});
<form action="/send.php" id="formid" method="post">
<div class="row">
<div class="col-md-4">
<div class="row">
<h3 class="col-md-9">Height</h3>
<p class="switch col-md-3">cm</p>
</div>
<div class="antbits-bmi-form_section_layer antbits-bmi-metric">
<div>
<label for="antbits-bmi-cm" class="antbits-bmi-form_section_label">Centimetres</label>
<input class="form-control" id="antbits-bmi-cm" aria-describedby="antbits-bmi-form_height-error" alt="height, centimeters" inputmode="numeric" type="text" step="0.1" min="0" maxlength="5" name="centimeter" placeholder="cm" required="">
</div>
</div>
</div>
<div class="col-md-4">
<div class="row">
<h3 class="col-md-9">Weight</h3>
<p class="col-md-3 switch">st, lb</p>
</div>
<div class="antbits-bmi-form_section_layer antbits-bmi-imperial">
<div>
<label for="antbits-bmi-kg" class="antbits-bmi-form_section_label">Kg</label>
<input class="form-control" id="antbits-bmi-kg" placeholder="Kg" alt="kg" type="text" inputmode="numeric" min="0" maxlength="2" name="kg" required="">
</div>
</div>
</div>
<div class="col-md-4">
<h3>Age</h3>
<div class="antbits-bmi-form_section_inner">
<div>
<label for="antbits-bmi-age" class="antbits-bmi-form_section_label antbits-accessible_hidden">Age in years</label>
<select class="form-control" id="age" name="age" required=""></select>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
<h3>Sex<small>?</small></h3>
<div class="info hide">
<h3>Sex<small>?</small></h3>
<p>For children, BMI centile is gender specific. For both children and adults, we give more personalised information based on whether you are male or female.</p>
</div>
<div class="radio-click row height">
<div class="radio-inline col-md-6 checked" id="male">
<input type="radio" name="optradio" value="male">Male
</div>
<div class="radio-inline col-md-6" id="female">
<input type="radio" name="optradio" value="female">Female
</div>
</div>
</div>
<div class="col-md-4">
<h3>Ethnic Group (optional)<small>?</small></h3>
<div class="info hide">
<h3>Ethnic</h3>
<p>Black, Asian and other minority ethnic groups with a BMI of 23 or more have a higher risk of getting type 2 diabetes and other long term illnesses.</p>
</div>
<select class="form-control" id="antbits-bmi-ethnicity" alt="Ethnic group" name="ethnic" required="">
<option disabled selected value class="antbits-bmi-form_option">Not stated</option>
<option value="2" class="antbits-bmi-form_option">White</option>
<option value="3" class="antbits-bmi-form_option">Black Caribbean</option>
<option value="4" class="antbits-bmi-form_option">Black African</option>
<option value="5" class="antbits-bmi-form_option">Indian</option>
<option value="6" class="antbits-bmi-form_option">Pakistani</option>
<option value="7" class="antbits-bmi-form_option">Bangladeshi</option>
<option value="8" class="antbits-bmi-form_option">Chinese</option>
<option value="9" class="antbits-bmi-form_option">Middle Eastern</option>
<option value="10" class="antbits-bmi-form_option">Mixed</option>
<option value="11" class="antbits-bmi-form_option">Other</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h3>Activity Level</h3>
<p>So we can personalize your results</p>
<div class="slidercontainer">
<input type="range" min="0" max="150" value="75" class="slider" id="myRange" name="range">
<div class="row center height activity">
<div class="col-md-4">
<p>Inactive</p>
</div>
<div class="col-md-4">
<p>Moderate Active</p>
</div>
<div class="col-md-4">
<p>Active</p>
</div>
</div>
<div class="row center height">
<div class="col-md-4">
<p>Less than 30 minutes a week</p>
</div>
<div class="col-md-4">
<p>Between 30 and 60 minutes a week</p>
</div>
<div class="col-md-4">
<p>Between 60 and 150 minutes a week</p>
</div>
</div>
<p>Value: <span id="demo"></span></p>
</div>
</div>
</div>
<!-- <div id="chartContainer"></div> -->
<div class="center">
<input type="submit" value="Calculate">
</div>
</form>

Remove appended data on second click

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>

Jquery, for loop shows all

$("#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>

how can i call each value in one function?

when i calculate each price the problem is insert both.
I just want each price for pickup and delivery
Javascript
function refreshprices() {
var pickup_td = getDistanceFromLatLonInKm(origin_lat,origin_lng,pickup_lat,pickup_lng);
var pickup_cost = calculatePrice(base_cost, base_dist, additional_cost, additional_dist, pickup_td);
var pickup_output = document.getElementById('pickup_price');
pickup_output.innerHTML = " $ " + pickup_cost;
var delivery_td=getDistanceFromLatLonInKm(origin_lat,origin_lng,delivery_lat,delivery_lng);
var delivery_cost=calculatePrice(base_cost, base_dist, additional_cost, additional_dist, delivery_td);
var delivery_output = document.getElementById('delivery_price');
delivery_output.innerHTML = " $ " + delivery_cost;
}
HTML
<form action="#" method="post">
<div id="pickup_option_calculate_price">
<div class="row-fluid">
<div class="span12" >
<h2>Pickup Option</h2>
<label class="radio">
<div class="option-title"><input type="radio" name="pickup" value="no_pickup" id="type_0" checked>No pickup required</div>
</label>
<div class="option-desc">You must drop off your passports and supporting documents at our office.</div>
<label class="radio">
<div class="option-title"><input type="radio" name="pickup" value="pickup" id="type_1">Pickup required ( <span id="pickup_price"> Enter Address to calculate Price </span>)</div>
</label>
<div class="option-desc">We will pickup the passports and supporting documents from your home or office.</div>
</div>
</div>
<div id="pickup_location">
<div class="row-fluid">
<input type="text" name="address" class="span10">
<input type="button" name="search" class="span2" value="Calculate Price" class="btn">
</div>
<div class="row-fluid">
<div class="span12">
<div id="coords" style="margin-top: 10px;"></div>
<div id="gmap" style="height:200px;position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
</div>
</div>
</div>
</div>
<div id="delivery_option_calculate_price">
<div class="row-fluid">
<div class="span12" >
<h2>delivery Option</h2>
<label class="radio">
<div class="option-title"><input type="radio" name="delivery" value="no_delivery" id="type_0" checked>No delivery required</div>
</label>
<div class="option-desc">You must drop off your passports and supporting documents at our office.</div>
<label class="radio">
<div class="option-title"><input type="radio" name="delivery" value="delivery" id="type_1">delivery required ( <span id="delivery_price"> Enter Address to calculate Price </span>)</div>
</label>
<div class="option-desc">We will delivery the passports and supporting documents from your home or office.</div>
</div>
</div>
<div id="delivery_location">
<div class="row-fluid">
<input type="text" name="delivery_address" class="span10">
<input type="button" name="delivery_search" class="span2" value="Calculate Price" class="btn">
</div>
<div class="row-fluid">
<div class="span12">
<div id="coords" style="margin-top: 10px;"></div>
<div id="gmap" style="height:200px;position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
</div>
</div>
</div>
</div>
</form>
when i calculate each price the problem is insert both.
I just want each price for pickup and delivery
Image is below.
Ok.Now i found it all my brother.
refreshprices();
pickup_output = document.getElementById('pickup_price');
pickup_output.innerHTML = " $ " + pickup_cost;
refreshprices();
var delivery_output = document.getElementById('delivery_price');
delivery_output.innerHTML = " $ " + delivery_cost;
function refreshprices() {
var pickup_td = getDistanceFromLatLonInKm(origin_lat,origin_lng,pickup_lat,pickup_lng);
pickup_cost = calculatePrice(base_cost, base_dist, additional_cost, additional_dist, pickup_td);
var delivery_td=getDistanceFromLatLonInKm(origin_lat,origin_lng,delivery_lat,delivery_lng);
delivery_cost=calculatePrice(base_cost, base_dist, additional_cost, additional_dist, delivery_td);
}

Categories