I have a JSON data coming through AJAX GET method is:The JsonData is stored in var trDataSecondTable and displayed when I did console.log(trDataSecondTable).
{
"assessCatAmount":[
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"A",
"assessAmount":1,
"assessPenalty":2,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":1,
"assessReason":"D",
"assessAmount":3,
"assessPenalty":4,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"B",
"assessAmount":5,
"assessPenalty":6,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":2,
"assessReason":"E",
"assessAmount":7,
"assessPenalty":8,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"C",
"assessAmount":9,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
},
{
"assessmentNo":1,
"assessmentType":"PRE",
"assessCatId":3,
"assessReason":"F",
"assessAmount":10,
"assessPenalty":10,
"entryBy":"PCS",
"rStatus":"1"
}
]
}
My form looks like this which is dynamic type (can be added by clicking "+" or can be deleted by pressing "-")
My form when page is loaded first looks like :
I need to show these six JSON data into this form.If there is three JSON data then there should be three row total along with data.If there is twelve json data then twelve row needs to appear along with data in input field.
function sumIt() {
$("#formContainer [type=number]").each(function() {
var $row = $(this).closest(".row");
var $fields = $row.find("[type=number]");
var val1 = $fields.eq(0).val();
var val2 = $fields.eq(1).val();
var tot = (isNaN(val1) ? 0 : +val1) + (isNaN(val2) ? 0 : +val2)
$row.find(".sum").text(tot);
});
var total = 0;
$(".sum").each(function() {
total += isNaN($(this).text()) ? 0 : +$(this).text()
});
$("#tot").text(total);
return total;
}
$(".customs-table .remove:lt(1)").hide();
$(".vat-table .remove:lt(1)").hide();
$(".excise-table .remove:lt(1)").hide();
$("#formContainer").on("click", "button", function() {
var selector = "div.row";
var $div = $(this).closest(selector);
if ($(this).is(".add")) {
var $newDiv = $div.clone();
$newDiv.find(":input").val(""); // clear all
$newDiv.find("[type=number]").val(0); // clear numbers
$newDiv.find(".sum").text(0); // clear total
$newDiv.insertAfter($div)
}
else {
$div.remove();
sumIt();
}
$(".customs-table .remove:gt(0)").show();
$(".vat-table .remove:gt(0)").show();
$(".excise-table .remove:gt(0)").show();
});
$("#formContainer").on("input", "[type=number]", sumIt);
$("form").submit(function() {
event.preventDefault();
var user_profile = [];
$(".row").each(function() {
var $fields = $(this).find(":input");
if ($fields.length > 0) {
var cat = $(this).find("div>label").eq(0).text(); // use the label of the row
var catId = ["","Customs","VAT","Excise"].indexOf(cat)
user_profile.push({
assessmentType: "PRE",
assessCatID : catId,
assessReason: $fields.eq(0).val(),
assessAmount: $fields.eq(1).val(),
assessPenalty: $fields.eq(2).val(),
assessTotal: +$fields.eq(1).val() + +$fields.eq(2).val() // the leading + makes it a number
});
}
});
console.log(user_profile);
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<form id="myForm">
<div id="formContainer" class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="customs-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control customReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customPenalty" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="col-md-12 pull-right">
<label>Total:</label> <b><span id="tot">0</span></b>
</div>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</div>
</form>
</body>
</html>
I tried to manipulate using the for loop but not able to show them into those dynamic field.How can i achieve this?
Updated Code:
Since there are customs,vats,excise i need their each number like 1,2.Each of their start with 1,2,3 so on.
So here is what i try:
i added customNo class.
<div class="col-md-1 customNo">
<label>Customs</label>
</div>
and to show 1,2,3 i declared 3 different variable.
var showEmpty=true;
var i=1,j=1,k=1;
$.each(data.assessCatAmount, function(_,cat) {
showEmpty = false; // there was data
var type = types[cat.assessCatId];
var $newDiv = $("#formContainer").find("."+type+"-table").eq(0).clone();
$.each(cat,function(key,value) {
$(".customNo").append("<div><label for="name"> i </label></div>");
var fieldName = key.replace("assess",type);
var $field = $newDiv.find("."+fieldName);
if ($field) $field.val(value);
i=i+1;
});
$("#formContainer").append($newDiv)
So i tried $(".customNo").append("<div><label for="name"> i </label></div>"); it is not displaying me 1,2. How can i get this?
You need to copy the clone part
var types = ["","customs","vat","excise"]; // 1,2,3 must match class names
$.each(data.assessCatAmount, function(_,cat) {
var type = types[cat.assessCatId];
var $newDiv = $("#formContainer").find("."+type+"-table").eq(0).clone(); // clone the FIRST one
$.each(cat,function(key,value) {
var fieldName = key.replace("assess",type);
var $field = $newDiv.find("."+fieldName);
if ($field) $field.val(value);
});
$("#formContainer").append($newDiv)
});
You may need to hide or fill the first 3 divs since I do not fill them, I only use them to clone from
Also move the total to the bottom like I did with the submit
var types = ["", "customs", "vat", "excise"]; // 1,2,3
function getText(str) {
return $.trim(/\s/.test(str)?str.split(/\s+/)[1]:str);
}
var data = {
"assessCatAmount": [{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 1,
"assessReason": "A",
"assessAmount": 1,
"assessPenalty": 2,
"entryBy": "PCS",
"rStatus": "1"
},
{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 1,
"assessReason": "D",
"assessAmount": 3,
"assessPenalty": 4,
"entryBy": "PCS",
"rStatus": "1"
},
{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 2,
"assessReason": "B",
"assessAmount": 5,
"assessPenalty": 6,
"entryBy": "PCS",
"rStatus": "1"
},
{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 2,
"assessReason": "E",
"assessAmount": 7,
"assessPenalty": 8,
"entryBy": "PCS",
"rStatus": "1"
},
{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 3,
"assessReason": "C",
"assessAmount": 9,
"assessPenalty": 10,
"entryBy": "PCS",
"rStatus": "1"
},
{
"assessmentNo": 1,
"assessmentType": "PRE",
"assessCatId": 3,
"assessReason": "F",
"assessAmount": 10,
"assessPenalty": 10,
"entryBy": "PCS",
"rStatus": "1"
}
]
}
function sumIt() {
$("#formContainer [type=number]").each(function() {
var $row = $(this).closest(".row");
var $fields = $row.find("[type=number]");
var val1 = $fields.eq(0).val();
var val2 = $fields.eq(1).val();
var tot = (isNaN(val1) ? 0 : +val1) + (isNaN(val2) ? 0 : +val2)
$row.find(".sum").text(tot);
});
var total = 0;
$(".sum").each(function() {
total += isNaN($(this).text()) ? 0 : +$(this).text()
});
$("#tot").text(total);
return total;
}
// data={} // test no data
function addNums(i) {
$(this).html(function() {
var text = $(this).text();
// Get the text without leading number - fake a space in case there are none yet
var type = getText(text);
var length = $("."+type.toLowerCase()+"-table").length;
return (length===1?"":i+ " ") + type; // only show numbers if more than one
});
}
function cleanUp() {
$(".customs-table .remove:gt(0)").show();
$(".vat-table .remove:gt(0)").show();
$(".excise-table .remove:gt(0)").show();
$(".customs-table.row > div > label").each(addNums);
$(".vat-table.row > div > label").each(addNums);
$(".excise-table.row > div > label").each(addNums);
}
$(function() {
$(".customs-table .remove:lt(1)").hide();
$(".vat-table .remove:lt(1)").hide();
$(".excise-table .remove:lt(1)").hide();
$("#formContainer").on("click", "button", function() {
var selector = "div.row";
var $div = $(this).closest(selector);
if ($(this).is(".add")) {
var $newDiv = $div.clone();
$newDiv.find(":input").val(""); // clear all
$newDiv.find("[type=number]").val(0); // clear numbers
$newDiv.find(".sum").text(0); // clear total
$newDiv.insertAfter($div)
} else {
$div.remove();
sumIt();
}
cleanUp();
});
$("#formContainer").on("input", "[type=number]", sumIt);
$("form").submit(function() {
event.preventDefault();
var user_profile = [];
$(".row:visible").each(function() {
var $fields = $(this).find(":input");
if ($fields.length > 0) {
var cat = getText($(this).find("div>label").eq(0).text()); // use the label of the row
var catId = types.indexOf(cat.toLowerCase())
user_profile.push({
assessmentType: "PRE",
assessCatID: catId,
assessReason: $fields.eq(0).val(),
assessAmount: $fields.eq(1).val(),
assessPenalty: $fields.eq(2).val(),
assessTotal: +$fields.eq(1).val() + +$fields.eq(2).val() // the leading + makes it a number
});
}
});
console.log(user_profile);
});
var showEmpty = true;
$.each(data.assessCatAmount, function(_, cat) {
showEmpty = false; // there was data
var type = types[cat.assessCatId];
var $newDiv = $("#formContainer").find("." + type + "-table").eq(0).clone();
$.each(cat, function(key, value) {
var fieldName = key.replace("assess", type);
var $field = $newDiv.find("." + fieldName);
if ($field) $field.val(value);
});
$("#formContainer").append($newDiv)
});
$(".customs-table").eq(0).toggle(showEmpty);
$(".vat-table").eq(0).toggle(showEmpty);
$(".excise-table").eq(0).toggle(showEmpty);
cleanUp();
});
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<form id="myForm">
<div id="formContainer" class="col-md-12" style="float: none;">
<!-- <button onclick="myFunction()" class="pull-right">+</button> -->
<div style="margin-bottom: 30px;">
<div class="form-group row">
<div class="col-md-1"></div>
<div class="col-md-4">
<label>Reason</label>
</div>
<div class="col-md-2">
<label>Amount</label>
</div>
<div class="col-md-2">
<label>Penalty</label>
</div>
<div class="col-md-1">Total</div>
<div class="col-md-2">Action</div>
</div>
<div class="customs-table row">
<div class="col-md-1">
<label>Customs</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control customsReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customsAmount" value="0" name="abc" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt customsPenalty" value="0" name="abc" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="vat-table row">
<div class="col-md-1">
<label>VAT</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control vatReason" name="vatReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
<div class="excise-table row">
<div class="col-md-1">
<label>Excise</label>
</div>
<div class="col-md-4">
<input type="text" class="form-control exciseReason" name="exciseReason" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" />
</div>
<div class="col-md-2">
<input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" />
</div>
<div class="col-md-1">
<span class="sum">0</span>
</div>
<div class="col-md-2">
<button type="button" class="add">+</button>
<button type="button" class="remove">-</button>
</div>
</div>
</div>
</div>
<div class="col-md-12 pull-right">
<label>Total:</label> <b><span id="tot">0</span></b>
</div>
<button type="submit" class="btn btn-success pull-right">Submit</button>
</form>
</body>
</html>
Related
Here is my code...
<div id="estimate">
<div class="form-group">
<div class="range-slider">
<input class="range-slider__range form-control prc e-range" type="range" value="100" min="0" max="500" pst="3">
<span class="range-slider__value">0</span>
</div>
</div>
<div class="form-group">
<div class="range-slider">
<input class="range-slider__range form-control prc e-range" type="range" value="100" min="0" max="500" pst="5">
<span class="range-slider__value">0</span>
</div>
</div>
<div class="form-group">
<input type="number" class="form-control prc" value="{{vl}}"/>
</div>
<div class="form-group">
<input type="number" class="form-control prc" value="5"/>
</div>
<div class="form-group">
<input type="checkbox" value="10" class="form-control prc">
</div>
<p id="result"></p>
</div>
<script>
estimate();
$('.form-group').on('change','.prc',estimate);
function estimate(){
let totalSum = 0;
$('.form-group .prc').each(function(){
if(this.type=="checkbox" && !this.checked) return
let inputVal = $(this).val();
if($.isNumeric(inputVal)){
totalSum += parseFloat(inputVal);
}
});
$('#result').html(totalSum);
}
var rangeSlider = function(){
var slider = $('.range-slider'),
range = $('.range-slider__range'),
value = $('.range-slider__value');
slider.each(function(){
value.each(function(){
var value = $(this).prev().attr('value');
$(this).html(value);
});
range.on('input', function(){
$(this).next(value).html(this.value);
});
});
};
rangeSlider();
</script>
Here I wants the range slider only multiply value with pst attribute then calculate with other fields and then its show the result..
here can't use any specific id for each item... only can call by any specific class with same type input field like range. and each range vlue should multiply with each pst value then calcualte with other fields
Consider the following example.
estimate();
$('.form-group').on('change', '.prc', estimate);
function estimate() {
var totalSum = 0,
add, v, m;
$('.form-group .prc').each(function(i, el) {
if ($(el).is(":checkbox") && !$(el).is(":checked")) {
add = 0;
} else if ($(el).hasClass("e-range")) {
v = parseInt($(el).val());
m = parseInt($(el).attr("pst"));
add = (v * m);
} else {
add = parseFloat($(el).val());
}
totalSum += add;
});
$('#result').html(totalSum);
}
function rangeSlider() {
var slider = $('.range-slider'),
range = $('.range-slider__range'),
value = $('.range-slider__value');
slider.each(function() {
value.each(function() {
var value = $(this).prev().attr('value');
$(this).html(value);
});
range.on('input', function() {
$(this).next(value).html(this.value);
});
});
};
rangeSlider();
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
<div id="estimate">
<div class="form-group">
<div class="range-slider">
<input class="range-slider__range form-control prc e-range" type="range" value="100" min="0" max="500" pst="3">
<span class="range-slider__value">0</span>
</div>
</div>
<div class="form-group">
<div class="range-slider">
<input class="range-slider__range form-control prc e-range" type="range" value="100" min="0" max="500" pst="5">
<span class="range-slider__value">0</span>
</div>
</div>
<div class="form-group">
<input type="number" class="form-control prc" value="0" />
</div>
<div class="form-group">
<input type="number" class="form-control prc" value="5" />
</div>
<div class="form-group form-check">
<input type="checkbox" value="10" class="form-check-input form-control prc"> <label class="form-check-label">10</label>
</div>
<p id="result"></p>
</div>
If you need to get the attribute of an element, use .attr().
See more:
https://api.jquery.com/attr/
I have a form which sends data to localStorage, which I am able to view, delete and edit. My form has a mixture of input types, text select and textarea, when I submit the form, these values store correctly, however when I use my edit function, the values show correctly on the edit form, but if I don't change the values (even to the same value), they update/store as null.
For example:
I have a form with Name(type text), Address(type address) and Dog Breed(type select), when I edit, the values of all three will be there from the form before, but if I hit submit without changing any, the dog breed would return null. They update correctly if I change the values, but as this is an appointment scheduler, not every value will be changed (for eg they may only need to change the time or breed).
Here is my snippet - I know it can't be run fully because of sandboxing but just so you can see:
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
window.onload = showBooking();
window.onload = showTimes();
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button onclick="editBooking(${i})" class="col-md-4 btn btn-outline-danger ">Edit</button>
<button onclick="deleteBooking(${i})" class="col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="${bookings[i].fname}" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="${bookings[i].lname}" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="${bookings[i].email}" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" onchange="validateContact()" placeholder="Contact Number" name="${bookings[i].number}" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="${bookings[i].sdate}" onchange="checkStartDate()" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="${bookings[i].stime}" onfocus="showTimes()" class="time select form-control required" value="${bookings[i].stime}">${bookings[i].stime}
<option value="${bookings[i].stime}" selected disabled hidden>${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="${bookings[i].duration}" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">${bookings[i].duration}
<option value="${bookings[i].duration}" selected disabled hidden>${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="${bookings[i].address}" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="${bookings[i].postcode}" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="${bookings[i].dogname}" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="${bookings[i].breed}" value="${bookings[i].breed}">
<option value="${bookings[i].breed}" selected disabled hidden>${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="${bookings[i].info}">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" onchange="checkStartDate()" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
There are a few issues in the code you'll need to take care of:
First thing is, I'd wrap everything in a "document.ready" event handler from jQuery:
$(function() {
...
});
The above is shorthand and just ensures your code runs once all of the HTML code has been parsed.
Now, the caveat with that is now all of your functions are no longer in the global scope, so you can't reference them in HTML attributes like onclick. So, you'll need to attach them to your elements using jQuery or plain old DOM methods.
You had two lines which set the window.onload property. In the code below I've changed it to use jQuery-style event handler attachment.
You were setting the name attribute of the form elements to the value of edited appointment, but the name attribute really shouldn't need to change that often.
$(function() {
const BREEDS_URL = 'https://dog.ceo/api/breeds/list/all';
function loadBreeds() {
const select = document.getElementById('breed');
fetch(BREEDS_URL)
.then(res => {
return res.json();
})
.then(data => {
const breedsObject = data.message;
const breedsArray = Object.keys(breedsObject);
for (let i = 0; i < breedsArray.length; i++) {
const option = document.createElement('option');
option.value = breedsArray[i];
option.innerText = breedsArray[i];
select.appendChild(option);
}
console.log(breedsArray);
});
}
// ~~~ add bookings to localStorage
var bookings = JSON.parse(localStorage.getItem("bookings")) || [];
$(window).on('load', function() {
showBooking();
showTimes();
loadBreeds();
});
$("#submit").click(function() {
var newBookings = {
id: new Date().getTime(),
fname: $('#fname').val(),
lname: $('#lname').val(),
email: $('#email').val(),
number: $('#number').val(),
sdate: $('#sdate').val(),
stime: $('#stime').val(),
duration: $('#duration').val(),
address: $('#address').val(),
postcode: $('#postcode').val(),
dogname: $('#dogName').val(),
breed: $('#breed').val(),
info: $('#info').val()
}
bookings.push(newBookings);
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
alert('Form submitted!');
showBooking();
});
$(document).on('click', '#edit', function(e) {
e.preventDefault();
var parent_form = $(this.form);
var fname = parent_form.find('.fname').val();
var lname = parent_form.find('.lname').val();
var email = parent_form.find('.email').val();
var number = parent_form.find('.number').val();
var sdate = parent_form.find('.datepicker').val();
var stime = parent_form.find('.select').val();
var duration = parent_form.find('.duration').val();
var address = parent_form.find('.address').val();
var postcode = parent_form.find('.postcode').val();
var dogname = parent_form.find('.dogname').val();
var breed = parent_form.find('.breed').val();
var info = parent_form.find('.info').val();
let i = bookings.findIndex(booking => booking.id == $(this).data("id"));
bookings[i].fname = fname;
bookings[i].lname = lname;
bookings[i].email = email;
bookings[i].number = number;
bookings[i].sdate = sdate;
bookings[i].stime = stime;
bookings[i].duration = duration;
bookings[i].address = address;
bookings[i].postcode = postcode;
bookings[i].dogname = dogname;
bookings[i].breed = breed;
bookings[i].info = info;
var json = JSON.stringify(bookings);
window.localStorage.setItem("bookings", json);
window.location.reload();
alert('Form updated!');
showBooking();
});
$(document).on('change', '.datepicker', checkStartDate);
$(document).on('change', '.number', validateContact);
$(document).on('focusin', '.time', showTimes);
$(document).on('click', '.edit-booking', function(e) {
var index = +$(this).data('index');
editBooking(index);
});
$(document).on('click', '.delete-booking', function(e) {
var index = +$(this).data('index');
deleteBooking(index);
});
// ~~~ display bookings in browser
function showBooking() {
var bookingResult = document.getElementById("result");
var ul = document.createElement("ul");
bookingResult.innerHTML = `<h3 class="text-center">Your Bookings</h3>`;
for (let i = 0; i < bookings.length; i++) {
bookingResult.innerHTML += `
<div class="card card-body bg-light m-4">
<div class="row">
<p>${bookings[i].fname + " " + bookings[i].lname}</p>
</div>
<div class="row">
<div class="d-grid gap-2 d-md-block">
<button data-index="${i}" class="edit-booking col-md-4 btn btn-outline-danger ">Edit</button>
<button data-index="${i}" class="delete-booking col-md-4 btn btn-danger text-light ">Delete</button>
</div>
</div>
</div>`;
}
}
// ~~~ edit bookings in browser
function editBooking(i) {
$('#result').hide();
var currentItem = document.getElementById("currentItem");
var editBooking = document.getElementById("editAppt");
currentItem.innerHTML += `
<h3 class="text-center">Currently Amending</h3>
<div class="card card-body bg-light m-4">
<p data-id="${bookings[i].id}">${bookings[i].fname + " " + bookings[i].lname}</p>
</div>`;
editBooking.innerHTML = `
<h3 class="text-center">Amend Your Booking</h3>
<div class="row">
<div class="col-md-6">
<input type="text" class="fname form-control required" data-id="${bookings[i].id}" placeholder="First Name" name="fname" value="${bookings[i].fname}">
</div>
<div class="col-md-6">
<input type="text" class="lname form-control required" data-id="${bookings[i].id}" placeholder="Last Name" name="lname" value="${bookings[i].lname}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="email" class="email form-control required" data-id="${bookings[i].id}" placeholder="Email Address" name="email" value="${bookings[i].email}">
</div>
<div class="col-md-6">
<input type="number" class="number form-control required" data-id="${bookings[i].id}" placeholder="Contact Number" name="number" value="${bookings[i].number}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" value="${bookings[i].sdate}">
</div>
<div class="col-md-6">
<select id="stime" name="stime" class="time select form-control required" value="${bookings[i].stime}">
<option value="${bookings[i].stime}">${bookings[i].stime}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<select name="duration" class="duration form-control required" data-id="${bookings[i].id}" value="${bookings[i].duration}">
<option value="${bookings[i].duration}">${bookings[i].duration}</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="address form-control required" placeholder="Address" name="address" value="${bookings[i].address}">
</div>
<div class="col-md-6">
<input type="text" data-id="${bookings[i].id}" class="postcode form-control " placeholder="Post Code" name="postcode" value="${bookings[i].postcode}">
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname" value="${bookings[i].dogname}">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required" name="breed" value="${bookings[i].breed}">
<option value="${bookings[i].breed}">${bookings[i].breed}</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-12">
<textarea id="info" name="info" class="info form-control required" placeholder="Any additional info - favourite toys or places?" name="info">${bookings[i].info}</textarea>
</div>
</div>
<div class="d-grid gap-2 d-md-block">
<input data-id="${bookings[i].id}" id="edit" class="btn btn-danger toggle-disabled" type="submit" value="Edit" disabled>
Cancel
</div>
`;
loadBreeds();
}
function showTimes() {
let startTime = document.getElementById('stime');
let times = ['9:00', '9:30', '10:00', '10:30', '11:00', '11:30', '12:00', '12:30', '13:00', '13:30', '14:00', '14:30', '15:00'];
let options = times.map(time => `<option value="${time}">${time}</option>`).join('');
startTime.innerHTML += options;
}
// ~~~ delete bookings from localStorage
function deleteBooking(i) {
alert('Are you sure you want to delete this booking?');
bookings.splice(i, 1);
localStorage.setItem("bookings", JSON.stringify(bookings));
showBooking();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
<link rel="stylesheet" href="css/style.css">
<section class="form row">
<form id="regForm" name="regForm" action="" class="col-md-6">
<div id="editAppt">
<div class="row text-center">
<h3>Book your dog walk now</h3>
<p>Tell us about yourself first..</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" class="input form-control required" id="fname" placeholder="First Name" name="fname" required>
</div>
<div class="col-md-6">
<input type="text" class="input form-control required" id="lname" placeholder="Last Name" name="lname" required>
</div>
</div>
<div class="row text-center">
<p>When should we pick your dog up?</p>
</div>
<div class="row">
<div class="col-md-6">
<input type="date" id="sdate" class="datepicker form-control required" name="sdate" required>
</div>
<div class="col-md-6">
<select name="duration" class="duration form-control required" id="duration" required>
<option value="" selected disabled hidden>Duration</option>
<option value="30 mins">30 mins</option>
<option value="1 hour">1 hour</option>
<option value="1.5 hours">1.5 hours</option>
<option value="2 hours">2 hours</option>
</select>
</div>
</div>
<div class="row">
<div class="col-md-6">
<input type="text" id="dogName" class="dogname form-control required" placeholder="Dogs Name" name="dogname">
</div>
<div class="col-md-6">
<select id="breed" class="breed form-control required">
<option value="" selected disabled hidden>Select Breed</option>
</select>
</div>
</div>
<div class="col-md-6">
<input id="submit" class="btn btn-danger toggle-disabled" type="submit" value="Submit">
</div>
</div>
</form>
<div class="col-md-6">
<div id="result" class="row"></div>
<div id="currentItem" class="row"></div>
</div>
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>
<div class="row">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<input type="text" class="form-control" v-model="act" >
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Section </label>
<input type="text" class="form-control" v-model="section">
</div>
</div>
<button>Add row</button>
</div>
So, when I click on add button, i need to keep on adding the above row. How can I able to add this row when I click on add row button.
I need to pass values as BOOKED UNDER :
[{
act :,
section:,
}]
If I have more rows i need to pass values as comma seperated. I am weak in js and this is my first project having this kind of problem. How can I able to add values in this way.
My vue js code is
addForm = new Vue({
el: "#addForm",
data: {
bookedUnder:[],
act: '',
section:'',
},
methods: {
handleSubmit: function(e) {
var vm = this;
data['otherNatureofOffense'] = //in the abve way
$.ajax({
url: 'http://localhost:3000/record/add/f/',
data: data,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success")
} else {
vm.response = e;
console.log(vm.response);
alert(" Failed")
}
}
});
return false;
},
},
});
Please help me to have a solution
If you use javascript or jquery this may helpful
var count=1;
$("#btn").click(function(){
$("#container").append(addNewRow(count));
count++;
});
function addNewRow(count){
var newrow='<div class="row">'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Act '+count+'</label>'+
'<input type="text" class="form-control" v-model="act" >'+
'</div>'+
'</div>'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Section '+count+'</label>'+
'<input type="text" class="form-control" v-model="section">'+
'</div>'+
'</div>'+
'</div>';
return newrow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="container">
<div class="row">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<input type="text" class="form-control" v-model="act" >
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Section </label>
<input type="text" class="form-control" v-model="section">
</div>
</div>
</div>
</div>
<button id="btn">Add row</button>
Try please,
document.getElementById("clickMe").onclick = function () {
//first div
var newDivCol = document.createElement("div");
newDivCol.setAttribute("class","col-md-4");
//second div
var newDivForm = document.createElement("div");
newDivForm.setAttribute("class","form-group label-floating");
newDivCol.appendChild(newDivForm);
//label
var newlabel = document.createElement("label");
newlabel.setAttribute("class","control-label");
newlabel.innerHTML = "Here goes the text";
newDivForm.appendChild(newlabel);
//input
var newInput = document.createElement("input");
newInput.setAttribute("type","text");
newInput.setAttribute("class","form-control");
newInput.setAttribute("v-model","act");
newDivForm.appendChild(newInput);
var element = document.getElementById("addRowsHere");
element.appendChild(newDivCol);
};
<div class="row" id="addRowsHere">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<input type="text" class="form-control" v-model="act" >
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Section </label>
<input type="text" class="form-control" v-model="section">
</div>
</div>
</div>
<button id="clickMe">Add row</button>
https://jsfiddle.net/kkyunLzg/2/#
You need to v-for the fields first then post the model like this:
<div class="row" v-for="(book, index) in bookedUnder" :key="index">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Act {{index}}</label>
<input type="text" class="form-control" v-model="book.act" >
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Section {{index}}</label>
<input type="text" class="form-control" v-model="book.section">
</div>
</div>
</div>
<button #click="addNewRow">Add row</button>
addForm = new Vue({
el: "#addForm",
data: {
bookedUnder:[
{
act: null,
section: null,
},
],
},
methods: {
addNewRow: function() {
this.bookedUnder.push({ act: null, section: null, });
},
handleSubmit: function(e) {
var vm = this;
$.ajax({
url: 'http://localhost:3000/record/add/f/',
data: vm.bookedUnder,
type: "POST",
dataType: 'json',
success: function(e) {
if (e.status) {
vm.response = e;
alert("success")
} else {
vm.response = e;
console.log(vm.response);
alert(" Failed")
}
}
});
return false;
},
},
});
Depending on the typ of row you want to add there are different solutions.
If you want to add 'Section'-rows only, you could use an v-for in Vue and push a object to the array connected to the v-for:
Template:
<div class="col-md-4" v-for="(row, index) in rows" :key="index">
<div class="form-group label-floating">
<label class="control-label">Section </label>
<input type="text" class="form-control" v-model="row.section">
</div>
</div>
<button #click="addRow">
Add Row
</button>
JS:
data: {
rows: [],
defaultRow: {
section: 'new-row'
}
},
methods: {
addRow() {
// Clone the default row object
this.rows.push(Object.assign({}, this.defaultRow))
}
}
If you want to add different types of rows you'll either have to create vue-components and add those, or get creative with different defaultRows (like maybe adding different types for different input).
var count=1;
$("#btn").click(function(){
$("#container").append(addNewRow(count));
count++;
});
function addNewRow(count){
var newrow='<div class="row">'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Act '+count+'</label>'+
'<input type="text" class="form-control" v-model="act" >'+
'</div>'+
'</div>'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Section '+count+'</label>'+
'<input type="text" class="form-control" v-model="section">'+
'</div>'+
'</div>'+
'</div>';
return newrow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<div id="container">
<div class="row">
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Act</label>
<input type="text" class="form-control" v-model="act" >
</div>
</div>
<div class="col-md-4">
<div class="form-group label-floating">
<label class="control-label">Section </label>
<input type="text" class="form-control" v-model="section">
</div>
</div>
</div>
</div>
<button id="btn">Add row</button>
Im adding all textboxes values on blur call. I give some number in one textbox. When it tries to add value of the other textbox value, it throws NaN.
Here is my code
function sumOfIncome() {
var sum = 0;
$('.add').each(function() {
sum += parseInt(this.value);
console.log(sum)
});
$('#netPay').val(sum);
}
$('.add').blur(function() {
sumOfIncome();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<div class="col-md-3">
<label for="DA" class="col-form-label">DA</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control add" id="da" placeholder="DA">
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="HRA" class="col-form-label">HRA</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control add" id="hra" placeholder="HRA">
</div>
</div>
Where am I doing wrong?
The easiest solution is to change your sum line to sum += parseInt(this.value) || 0;. This way, if the field is empty and returns a falsey value like NaN, it will instead use 0.
function sumOfIncome() {
var sum = 0;
$('.add').each(function() {
sum += parseInt(this.value) || 0;
console.log(sum)
});
$('#netPay').val(sum);
}
$('.add').blur(function() {
sumOfIncome();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<div class="col-md-3">
<label for="DA" class="col-form-label">DA</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control add" id="da" placeholder="DA">
</div>
</div>
<div class="form-group row">
<div class="col-md-3">
<label for="HRA" class="col-form-label">HRA</label>
</div>
<div class="col-sm-2">
<input type="number" class="form-control add" id="hra" placeholder="HRA">
</div>
</div>
Use this $.isNumeric() jsfiddle:
Html:
<div class="form-group row">
<div class="col-md-3"><label for="DA" class="col-form-label">DA</label></div>
<div class="col-sm-2"> <input type="number" class="form-control add" id="da" placeholder="DA">
</div>
</div>
<div class="form-group row">
<div class="col-md-3"><label for="HRA" class="col-form-label">HRA</label></div>
<div class="col-sm-2"> <input type="number" class="form-control add" id="hra" placeholder="HRA">
</div>
</div>
<div id="netPay">
</div>
Jquery:
function sumOfIncome() {
var sum = 0;
$('.add').each(function(){
var val = $(this).val();
if($.isNumeric(val))
{
sum += parseInt(val);
console.log(sum)
}
});
$('#netPay').text(sum);
}
$('.add').blur(function(){
sumOfIncome();
});