I am trying to build a webpage where you can oreder a ticket to a cinema movie.I have used an algorithm to change the cinema ticked price based on spot's id. The problem is that when I change the src of the image I get an undefined id. Why do I get that, and how to fix it?. Here is the code:
window.onload = main;
var initialPrice = 0;
var dayMultiplier = 1;
var price = 0;
function main()
{
addButtonLsn();
}
function addButtonLsn()
{
$("#setDate").click(addSeats);
}
function addSeats()
{
if($("#zi").val() === "--*--")
{
alert("Day select missing");
return;
}
if($("#movies").val() ==="--*--")
{
alert("Movie select missing");
return;
}
setInitialPrice();
setDayMutliplier();
$("#sala").empty();
$("#price").html("Pret : 0");
var myId = 1;
for(var i = 0; i < 20; i++)
{
for (var j = 0; j < 12; j++)
{
var s = document.createElement("img");
s.setAttribute("src", "liber.jpg");
s.setAttribute("id", myId);
myId ++;
s.addEventListener("click", changeSeat);
s.addEventListener("mouseover", getSeatTicket);
var d = document.getElementById("sala");
d.appendChild(s);
}
}
}
function getSeatTicket()
{
var spotPrice = initialPrice;
spotPrice = initialPrice * dayMultiplier;
var spotMultiplyer = 1;
var ct = 1;
if($(this).attr("id") < 130)
{
spotMultiplyer = 1;
ct = 3;
}
else if ($(this).attr("id") < 180)
{
spotMultiplyer = 1.1;
ct = 2;
}
else
{
spotMultiplyer = 1.2;
ct = 1;
}
spotPrice *= spotMultiplyer;
console.log($(this).attr("id"));//undefined
$(this).attr("title","Categorie: " + ct + " ,pret " + spotPrice);
return spotPrice;
}
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket();
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket();
$("#price").html("Price: " + price);
}
}
function setInitialPrice()
{
if($("#movies").val() === "The Gold Rush")
{
initialPrice = 10;
return;
}
if($("#movies").val() === "The Kid")
{
initialPrice = 11;
return;
}
if($("#movies").val() === "Modern Times")
{
initialPrice = 12;
return;
}
}
function setDayMutliplier()
{
if($("#zi").val() === "Luni-Joi")
{
dayMultiplier = 1;
return;
}
if($("#zi").val() === "Vineri")
{
dayMultiplier = 1.1;
return;
}
if($("#zi").val() === "Sambata")
{
dayMultiplier = 1.2;
return;
}
if($("#zi").val() === "Duminica")
{
dayMultiplier = 1.3;
return;
}
}
The function getSeatTicket is referring to this as the current element, which works fine when the function is used as a callback for the mouseover listener, but it will not work when you are calling it as you are in changeSeat.
Perhaps you should be using .call(this) to run the function using the same scope as changeSeat;
function changeSeat()
{
if($(this).attr('src') === "liber.jpg")
{
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
else
{
$(this).attr('src','liber.jpg');
price = price - getSeatTicket.call(this);
$("#price").html("Price: " + price);
}
}
After code inspection, my guess is that when you try to access the element's id within the getSeatTicket() function, you are calling a function where $(this) is not actually refering to the DOM element to which the event is attached to.
To overcome this, my recommendation would be to pass the id to the getSeatTicket() function, and getting the reference to the element inside it. Something like (conceptual):
function getSeatTicket(id){
var element = $(id);
...
}
and call it like:
...
$(this).attr('src','rezervat.jpg');
price = price + getSeatTicket($(this).attr("id"));
...
Best.
Related
Goal: Write a function that is called by the eventListener click event of an IMG. The function will use a conditional to see on which ElementID called the function, then initialize the on accumulator to that value, then add 1 and change the innerHTML to show that new value. Key goal is to make this occur with out have 3 similar identical functions
Code Thus Far
let likeCount = !NaN;
var classname = document.getElementsByClassName("like-heart");
function likeCounter() {
/*Note the elementID is very similar to the ELementID of the accumulator element - but not the same.*/
if (this.getElementById === "ft-recipe-like") {
likeCount = Number(document.getElementById('featured-likes').innerText);
likeCount += 1;
document.getElementById('featured-likes').innerText = likeCount;
} else if (this.getElementById === "macaroon-like") {
likeCount = Number(document.getElementById('macaroon-likes').innerText);
likeCount += 1;
document.getElementById('macaroon-likes').innerText = likeCount;
} else if (this.getElementById === 'brulee-like') {
likeCount = Number(document.getElementById('brulee-likes').innerText);
likeCount += 1;
document.getElementById('brulee-likes').innerText = likeCount;
}
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', likeCounter, false);
}
}
}
}
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', likeCounter, false);
}
}
}
You can have a map of acc id to Dom node id, and write a generic function to increment the likeCount.
let likeCount = !NaN;
var classname = document.getElementsByClassName("like-heart");
const accIdToDomIdMap = {
'ft-recipe-like': 'featured-likes',
'macaroon-like': 'macaroon-likes',
'brulee-likes': 'brulee-likes'
}
function likeCounter() {
/*Note the elementID is very similar to the ELementID of the accumulator element - but not the same.*/
if(accIdToDomIdMap.hasOwnProperty(this. getElementById)) {
const domId = document.getElementById(accIdToDomIdMap[this.getElementById]);
likeCount = (+domId.innerText || 0) + 1;
domId.innerText = likeCount;
}
}
function newFunction() {
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', likeCounter, false);
}
}
}
I have different id's on different elements that are used in an input field when the user can type in the letter (Element 1 = A, Element 2 = B.. Element 27 = AA). How can I properly scan these on input in order to determine if the element exists and if it does put it in a string that converts these id's to values which are later calculated?
I have an id system on a calculator where the user can generate different element (sliders, radio buttons, check boxes) that can be calculated. They all have a numeric id which is the translated into alphabetic characters in a progressive order ( Element 1 = A, Element 2 = B.. Element 27 = AA). I later have an input field where the user can create their own formula that will be calculated and put into a result tab.
Sample Formula: A+B*2
The reason I translate to letter is so that the user can use numbers in creating the formula. I have succeed in making this work for id's that are one letter but as soon as the id's start hitting AA and AB it doesn't work because currently I split this into an array and scan every element for it's value, which becomes problematic for two letters since they split into two different id's.
I have tried splitting the array based on the operators (+, -, *, /) but that removes them from the array.
function resultCalcInit(resultObject, resultFormulaObject) {
$('.createWrap').on('keyup input change', $(resultFormulaObject).find('.jvformbuilder-formula-panel-elements-result-field-formula'), function(e) {
var thisKey = new RegExp(String.fromCharCode(e.which).toLowerCase());
var keyNoRegEx = String.fromCharCode(e.which).toLowerCase();
var counter = 0;
var letters = /^[0-9a-zA-Z]+$/;
for (var call of $('.dropzone').find('.builder-elements')) {
if ($(call).find('.bf-number')[0]) {
var operators = ['»', '½', '/', '¿'];
if (String.fromCharCode(e.which) == $(call).find('.bf-number').attr("data-calcId").toUpperCase() || $.isNumeric(String.fromCharCode(e.which)) || wordInString(String.fromCharCode(e.which), operators)) {
counter++;
} else {}
} else if ($(call).find('.builder-list')[0]) {
var operators = ['»', '½', '/', '¿'];
if (String.fromCharCode(e.which) == $(call).find('.builder-list').attr("data-calcId").toUpperCase() || $.isNumeric(String.fromCharCode(e.which)) || wordInString(String.fromCharCode(e.which), operators)) {
counter++;
} else {}
} else if ($(call).find('.builder-radio')[0]) {
var operators = ['»', '½', '/', '¿'];
if (String.fromCharCode(e.which) == $(call).find('.builder-radio').attr("data-calcId").toUpperCase() || $.isNumeric(String.fromCharCode(e.which)) || wordInString(String.fromCharCode(e.which), operators)) {
counter++;
} else {}
} else if ($(call).find('.builderSlider')[0]) {
var operators = ['»', '½', '/', '¿'];
if (String.fromCharCode(e.which) == $(call).find('.builderSlider').attr("data-calcId").toUpperCase() || $.isNumeric(String.fromCharCode(e.which)) || wordInString(String.fromCharCode(e.which), operators)) {
counter++;
} else {}
} else if ($(call).find('.builder-checkboxes')[0]) {
var operators = ['»', '½', '/', '¿'];
if (String.fromCharCode(e.which) == $(call).find('.builder-checkboxes').attr("data-calcId").toUpperCase() || $.isNumeric(String.fromCharCode(e.which)) || wordInString(String.fromCharCode(e.which), operators)) {
counter++;
} else {}
}
}
if (String.fromCharCode(e.which).match(letters) && counter < 1) {
$(resultFormulaObject).find('.jvformbuilder-formula-panel-elements-result-field-formula').html($(resultFormulaObject).find('.jvformbuilder-formula-panel-elements-result-field-formula').html().replace(thisKey, ""));
var returnString = $(resultFormulaObject).find('.jvformbuilder-formula-panel-elements-result-field-formula').text();
$('#jvformbuilder-formula-panel').find('.jvformbuilder-formula-panel-elements').each(function() {
var formulaResultId = $(this).find('.jvformbuilder-formula-panel-elements-result-field-formula');
$('.builder-elements').each(function() {
if (formulaResultId.attr("id") == $(this).find('.result-number').attr("id")) {
var resultWindow = $(this).find('.result-number');
var formula = returnString.slice(1);
}
});
});
} else {
resultCalc(resultFormulaObject);
}
});
}
Here it check if the letter typed is an existing ID. If it isn't, it's removed. If it is, it stays and proceeds to be scanned for the value.
function resultCalc(resultFormulaObject) {
var returnString = $(resultFormulaObject).find('.jvformbuilder-formula-panel-elements-result-field-formula').text();
$('#jvformbuilder-formula-panel').find('.jvformbuilder-formula-panel-elements').each(function() {
var formulaResultId = $(this).find('.jvformbuilder-formula-panel-elements-result-field-formula');
$('.builder-elements').each(function() {
if (formulaResultId.attr("id") == $(this).find('.result-number').attr("id")) {
var resultWindow = $(this).find('.result-number');
var formula = returnString.slice(1).split("");
var formulaNbr = returnString.slice(1).split("");
var alphabet = ("abcdefghijklmnopqrstuvwxyz").split("");
var calculationArray = returnString.slice(1).split("");
var tempArr = formula;
for (var i = 0; i < formula.length; i++) {
$('.builder-elements').each(function() {
if ($(this).find('.builder-list').attr("data-calcid") == formula[i]) {
formulaNbr[i] = $(this).find('.builder-list').children("option:selected").val();
calculationArray[i] = "parseInt(ID" + alphabet.indexOf(formula[i]) + ").value)";
} else if ($(this).find('.builder-field').attr("data-calcid") == formula[i]) {
if ($(this).find('.bf-text')[0]) {
console.log(tempArr);
if (tempArr.indexOf(tempArr[i]) == 0) {
tempArr.splice(i, 2);
calculationArray.splice(i, 2);
} else {
tempArr.splice(i - 1, 2);
calculationArray.splice(i - 1, 2);
}
var formulaString = "";
for (var j = 0; j < formula.length; j++) {
formulaString += tempArr[j];
}
formulaResultId.empty();
formulaResultId.html("=" + formulaString);
} else if ($(this).find('.bf-telNum')[0]) {
if (tempArr.indexOf(tempArr[i]) == 0) {
tempArr.splice(i, 2);
calculationArray.splice(i, 2);
} else {
tempArr.splice(i - 1, 2);
calculationArray.splice(i - 1, 2);
}
var formulaString = "";
for (var j = 0; j < formula.length; j++) {
formulaString += tempArr[j];
}
formulaResultId.empty();
formulaResultId.html("=" + formulaString);
} else if ($(this).find('.bf-date')[0]) {
if (tempArr.indexOf(tempArr[i]) == 0) {
tempArr.splice(i, 2);
calculationArray.splice(i, 2);
} else {
tempArr.splice(i - 1, 2);
calculationArray.splice(i - 1, 2);
}
var formulaString = "";
for (var j = 0; j < formula.length; j++) {
formulaString += tempArr[j];
}
formulaResultId.empty();
formulaResultId.html("=" + formulaString);
} else if ($(this).find('.bf-number')[0]) {
if (!$(this).find('.bf-number').val()) {
formulaNbr[i] = 0;
} else {
formulaNbr[i] = $(this).find('.bf-number').val();
}
calculationArray[i] = "parseInt(ID" + alphabet.indexOf(formula[i]) + ").value)";
}
} else if ($(this).find('.builder-textarea').attr("data-calcid") == formula[i]) {
if (tempArr.indexOf(tempArr[i]) == 0) {
tempArr.splice(i, 2);
calculationArray.splice(i, 2);
} else {
tempArr.splice(i - 1, 2);
calculationArray.splice(i - 1, 2);
}
var formulaString = "";
for (var j = 0; j < formula.length; j++) {
formulaString += tempArr[j];
}
formulaResultId.empty();
formulaResultId.html("=" + formulaString);
} else if ($(this).find('.builder-radio').attr("data-calcid") == formula[i]) {
var resultRadio = [];
$(this).find('.builder-radio-input').each(function(i) {
resultRadio[i] = parseInt($(this).val());
});
var sum = resultRadio.reduce(add);
formulaNbr[i] = sum;
calculationArray[i] = "parseInt(ID" + alphabet.indexOf(formula[i]) + ").value)";
} else if ($(this).find('.builder-checkboxes').attr("data-calcid") == formula[i]) {
var resultCheck = [];
$(this).find('.builderCB').each(function(i) {
resultCheck[i] = parseInt($(this).val());
});
var sum = resultCheck.reduce(add);
formulaNbr[i] = sum;
calculationArray[i] = "parseInt(ID" + alphabet.indexOf(formula[i]) + ").value)";
} else if ($(this).find('.builderSlider').attr("data-calcid") == formula[i]) {
formulaNbr[i] = $(this).find('.builder-slider').val();
calculationArray[i] = "parseInt(ID" + alphabet.indexOf(formula[i]) + ").value)";
}
});
}
var calculationString = "";
for (var i = 0; i < calculationArray.length; i++) {
calculationString += calculationArray[i];
}
returnString = "";
for (var i = 0; i < formulaNbr.length; i++) {
returnString += formulaNbr[i];
}
if (returnString) {
printRes(returnString, resultWindow, calculationString);
}
}
});
});
}
Here it takes different values from the different objects that relates to the id written inside the formula tab. Later it is printed into the result tab.
function printRes(resString, resArea, calcString) {
resArea.empty();
var result = eval(resString);
if (!result) {
resArea.append(0)
resArea.attr("data-calcForm", "");
} else {
resArea.append(result)
resArea.attr("data-calcForm", calcString);
}
}
It completely crashes if the id becomes doubled. That's where I need you guys to help me. How can I make it scan after double characters id's as well as single ones, and triple ones and how ever many the user decides to generate.
There is no way to reproduce the issue you have from the big code bunch you posted. And I have to admit that what you try to achieve is unclear to me.
But what is really clear is that you need to segregate the formula's elements from the operator. You can achieve this with 2 regexes. I see you already use the first one: /[0-9a-zA-Z]+/, but I don't get how you use it...
Anyway, here is a real simple demo showing that you can have two arrays, one for the formula's elements and the other for the operators. Once you have that, you should be able to use it to do whatever you wish to.
$("button").on("click",function(){
// The input value
var input_val = $("input").val();
// Regexes
var elements_regex = /[0-9a-zA-Z]+/g;
var operators_regex = /[\+\-*\/]/g;
// Create the arrays
var elements_array = input_val.match(elements_regex);
var operators_array = input_val.match(operators_regex);
// Needed just for this demo
var regex_validation = $(".regex_validation");
var elements = $(".elements");
var operators = $(".operators");
// RESULTS
// Regex validation
for(i=0;i<elements_array.length;i++){
// Element
if(typeof(elements_array[i])!="undefined"){
regex_validation.append("<span class='element'>"+elements_array[i]+"<span>");
}
// Operator
if(typeof(operators_array[i])!="undefined"){
regex_validation.append("<span class='operator'>"+operators_array[i]+"<span>");
}
}
// Elements
elements.html(JSON.stringify(elements_array));
// Operators
operators.html(JSON.stringify(operators_array));
});
.result{
height: 50px;
width: 500px;
border: 1px solid black;
}
.element{
background: cyan;
}
.operator{
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Enter your formula: <input value="AA+B*2"><button type="button">Check</button><br>
<br>
Regex validation: (cyan for elements, yellow for operators)
<div class="result regex_validation"></div>
<br>
Elements array:
<div class="result elements"></div>
<br>
Operators array:
<div class="result operators"></div>
<br>
CodePen
How can I get the chat to scroll to bottom when new content is sent into the chat? I'm trying to add something like this:
$('#what do I have to put here?').animate({scrollTop: $('#and here?').prop("scrollHeight")}, 200);
but I can't make it work (I have no idea where in the code to place it).
Thanks!
This is an important part of the code... Maybe I have to add it here (but I don't know how or where):
<script type="text/javascript">
var _answerBot = new answerBot();
function keypressInput(sender, event) {
if (event.which == 13) {
document.getElementById('subcontent').innerHTML += _answerBot.processInput(sender.value);
sender.value = '';
}
}
</script>
This is a separate scripts.js file:
var answerBot = function () {
var _this = this;
_this.processInput = function (text) {
updateUrl(text);
var _result = "<p class='answerbot-input'>" + text + "</p>";
text = text.replace(new RegExp("[ ]{2,}", "g"), " ");
var _words = text.toLowerCase().split(" ");
var _answers = [];
var _title = "";
if (_words.length === 0 || _words.toString() === '') { //if the input is empty
_answers = _this.specialContext.emptyInput;
_title = _this.specialContext.emptyInput;
} else {
var _possibleAnswers = findMatches(_words);
if (_possibleAnswers.length === 0) { //if no answer found
_answers = _this.specialContext.wrongInput;
_title = _this.specialContext.wrongInput;
}
if (_possibleAnswers.length == 1) { //context recognized
_answers = _this.answers[_possibleAnswers[0]].values;
_title = _this.answers[_possibleAnswers[0]].description;
}
if (_possibleAnswers.length > 1) {
_result += formatText(_this.specialContext.rephrase, _this.specialContext.rephrase);
for (var i = 0; i < _possibleAnswers.length; i++) {
_result += formatText(_this.answers[_possibleAnswers[i]].description, _this.answers[_possibleAnswers[i]].description);
}
}
}
if (_answers.length > 0) {
var _rand = Math.floor((Math.random() - 0.001) * _answers.length);
_result += formatText(_answers[_rand], _title);
}
return _result;
};
function formatText(text, title) {
return "<p class=\'answerbot-ai\' title=\'" + title + "\'>" + text + "</p>";
}
function findMatches(words) {
var foundKeywords = [];
var _possibleAnswers = [];
for (var i = 0; i < _this.keywords.length; i++) {
foundKeywords[i] = 0;
for (var j = 0; j < words.length; j++) {
if (_this.keywords[i].keys.indexOf(words[j]) >= 0) {
foundKeywords[i]++;
if (foundKeywords[i] == _this.keywords[i].keys.length) {
return [_this.keywords[i].value];
}
}
}
if (foundKeywords[i] * 2 > _this.keywords[i].keys.length) {
_possibleAnswers.push(_this.keywords[i].value);
}
}
return _possibleAnswers.filter(function (elem, pos) {
return _possibleAnswers.indexOf(elem) == pos;
});
}
function updateUrl(text){
history.pushState(null, null, "#question=" + encodeURIComponent(text));
if(typeof ga === "function")//google analytics
ga('send', 'event', 'question', text);
}
};
function AddMessage() {
var $message = $("<p>").text("message");
var $messages = $("#messages");
$messages.append($message);
$messages.animate({
scrollTop: $messages.prop("scrollHeight")
});
}
#messages {
border: 1px solid #000;
height: 100px;
overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="chat">
<div id="messages"></div>
<button onClick="AddMessage()">Add Message</button>
</div>
I am new to JavaScript. I would like to add to add two buttons for my visitors to control font size. I would like to include two tags - 'p' and 'blockquote". Can you please help me edit this code in order to include both?
var min = 8;
var max = 18;
function increaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
p[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var p = document.getElementsByTagName('p');
for (i = 0; i < p.length; i++) {
if (p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
p[i].style.fontSize = s + "px"
}
}
Thank you.
Here's a working version:
http://jsfiddle.net/ny4p7pg9/
I took the liberty of refactoring a bit the functions to make the code more parameterized.
function changeFontSize(delta) {
var tags = document.querySelectorAll('p,blockquote');
for (i = 0; i < tags.length; i++) {
if (tags[i].style.fontSize) {
var s = parseInt(tags[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += delta;
}
tags[i].style.fontSize = s + "px"
}
}
function increaseFontSize() {
changeFontSize(1);
}
function decreaseFontSize() {
changeFontSize(-1);
}
Instead of using:
p = document.getElementsByTagName('p');
you could, instead use:
elems = document.querySelectorAll('p, blockquote');
(the variable name is irrelevant, and was changed only because the elements are no longer exclusively <p> elements):
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != max) {
s += 1;
}
elems[i].style.fontSize = s + "px"
}
}
function decreaseFontSize() {
var elems = document.querySelectorAll('p, blockquote');
for (i = 0; i < elems.length; i++) {
if (elems[i].style.fontSize) {
var s = parseInt(elems[i].style.fontSize.replace("px", ""));
} else {
var s = 12;
} if (s != min) {
s -= 1;
}
elems[i].style.fontSize = s + "px"
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
The querySelectorAll() method accepts CSS-style selectors, and returns a (non-live) NodeList, and is supported in all modern browsers, including IE from version 8 onwards.
That said, it's probably better to increase the font-size of the <body> element, otherwise font-adjustment is redundant (since other elements will still be unclear), so, instead, I'd suggest:
function increaseFontSize() {
// retrieving, and caching, the <body> element:
var body = document.body,
// finding the current computed fontSize of the <body> element, parsing it
// as a float (though parseInt() would be just as safe, really):
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
// if the currentFontSize is less than the specified max:
if (currentFontSize < max) {
// we set the fontSize of the <body> to the incremented fontSize,
// increasing the current value by 1, and concatenating with the 'px' unit:
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
var min = 8;
var max = 18;
function increaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize < max) {
body.style.fontSize = ++currentFontSize + 'px';
}
}
function decreaseFontSize() {
var body = document.body,
currentFontSize = parseFloat(window.getComputedStyle(body, null).fontSize);
if (currentFontSize > min) {
body.style.fontSize = --currentFontSize + 'px';
}
}
document.querySelector('#increase').addEventListener('click', increaseFontSize);
document.querySelector('#decrease').addEventListener('click', decreaseFontSize);
<button id="increase">↑A</button>
<button id="decrease">A↓</button>
<p>Some text to have its text adjusted by the buttons just up there.</p>
<blockquote>Some text in a blockquote</blockquote>
References:
document.body.
document.querySelectorAll().
Window.getComputedStyle().
i am new to html and js. I have created a form with the following script. i have an event handler for calculateTime. I cant seem to get the form to calculate. If you guys could point me in the right direction that would be great. Thanks
<script>
function getWaterSystem() {
var waterSystem;
var selectedSystem = 0;
for (var i = 1; i <= 4; i++) {
waterSystem = document.getElementById("system + i");
if (waterSystem.checked == true) {
waterSystem = waterSystem(i).value;
}
}
return waterSystem;
}
function largePlant() {
var checkbox;
checkbox = document.getElementById("large");
if (checkbox(i).checked) {
checkbox = 1.5;
}
else {
checkbox = "";
}
return checkbox;
}
function getSoilType() {
var soilType;
var selectedSoil = 0;
for (var i = 1; i <= 3; i++) {
soilType = document.getElementById("soil + i");
if (soilType[i].checked) {
soilType = soilType[i].value;
}
}
return soilType;
}
function calculateTime() {
var waterTime = getWaterSystem() * getSoilType() * largePlant();
alert("The recommended watering time is " + waterTime);
}
</script>
I made some adjustment, just check it out, it's quite simple:
document.getElementById("check1").checked
<script>
function getWaterSystem() {
var waterSystem=0;
var selectedSystem = 0;
for (var i = 1; i <= 4; i++) {
if (document.getElementById("system" + i).checked) {
reutrn waterSystem = document.getElementById("system" + i).value;
}
}
return waterSystem;
}
function largePlant() {
var checkbox=0;
if (document.getElementById("large").checked) {
checkbox = 1.5;
}
else {
checkbox = 0;
}
return checkbox;
}
function getSoilType() {
var soilType=0;
var selectedSoil = 0;
for (var i = 1; i <= 3; i++) {
soilType = document.getElementById("soil" + i);
if (document.getElementById("soil" + i). checked) {
soilType = document.getElementById("soil" + i).value;
return soilType;
}
}
return soilType;
}
function calculateTime() {
var waterTime = getWaterSystem() * getSoilType() * largePlant();
alert("The recommended watering time is " + waterTime);
}
</script>
Could it have something to do with these two lines:
waterSystem = document.getElementById("system + i");
soilType = document.getElementById("soil + i");
If you want to target the id of #systemX or #soilX where X is being a number from you i var. You should write it like this:
waterSystem = document.getElementById("system" + i);
soilType = document.getElementById("soil" + i);