http://liveweave.com/R9jW9x
I have 4 textbox's each representing a css padding location (ex. padding-top, padding-left, etc:)
I'm experimenting with value detections. What I'm trying to figure out is when padding top and bottom [A] are the same values (as well as left and right [B]) how to set the values to padding: A B;
If all are same to set value to padding: A;
If all are different set value to nothing/blank
and
If all are different, or A & B maybe same, but C and D maybe different then to set value to padding: A B C D;
The script works fine onload, but when the input values are changed my result is not finalizing.
Can anybody explain why this is?
$(document).ready(function() {
var top = $(".padding-top").val(),
bottom = $(".padding-bottom").val(),
left = $(".padding-left").val(),
right = $(".padding-right").val(),
result = $(".padding-final");
// Update padding code
var Finalize = function() {
if ((top === "") && (right === "") && (bottom === "") && (left === "")) {
// Check if all are empty
result.val("");
} else if ((top === right) && (bottom === left)) {
// If all are same
result.val("padding: " + top + "px;");
} else if ((top === bottom) && (left === right)) {
// Check if first two values are same
result.val("padding: " + top + "px " + left + "px;");
} else {
result.val("padding: " + top + "px " + right + "px " + bottom + "px " + left + "px;");
}
};
// Update padding code when sides change
$(window).on('load keyup change', function() {
Finalize();
});
});
I won't write the code for you. But, I will hopefully send you in the right direction:
First, you should check whether padding-top, padding-right, padding-bottom, and padding-left are equal to each other.
>> If they are equal, then you can set the middle one equal to any of the values (since they're equal).
>> If they are not equal, then you can check to see if top and bottom are equal to each other && left and right are equal to each other. If they are, then you can set the middle to the top/bottom number + " " + left/right number.
>> Else set the middle to top number, right number, bottom number, left number.
EDIT
Actually, I got to tinkering a bit with the idea and came up with this to help you a bit more. But, that's it. No more help from me!
var top = 2;
var bottom = 2;
var right = 5;
var left = 5;
top == bottom && right == left && top == left ? alert(top)
: top == bottom && right == left ? alert(top + " " + left)
: alert(top + " " + right + " " + bottom + " " + left);
JSFiddle
After you solve this, a more challenging problem would be to type numbers into the middle box and change the top/right/bottom/left paddings accordingly.
I would play with this
var a=$(".padding-top"), b=..., c=..., d=...;
var test=0,padding;
if (a) test += 1;
if (b&& b!=a) test += 2;
if (c && c!=a) test += 4;
if (d && d!=c && d!=a) test += 8;
if (test== 1) padding = a;
if (test== 2 || test == 3) padding = a + " " + b; // when a+b or just b, we need a and b
if (test>4 && test < 8) padding = a + " " + b + " " + c; // c, a+c or b+c
if (test > 8) padding = a + " " + b + " " + c " " + d;
Also you can do
$(".paddings").on('keyup change', function() {
Finalize();
});
and use IDs for padding-top, left, bottom, right
As stated cases in your question, i have made following code:
$(document).ready(function() {
var top = $(".padding-top").val(),
bottom = $(".padding-bottom").val(),
left = $(".padding-left").val(),
right = $(".padding-right").val(),
result = 'Padding: ';
// Applies new code value
function Finalize() {
if(top === bottom === left === right) {
//If all are same
result += top + ' ';
} else {
if ((top === bottom) && (left === right)) {
// Check if first two values are same
result += top + ' ' + left + ' ';
} else {
result += left + ' ' + right + ' ' + top + ' ' + bottom + ' ';
}
}
result += 'Px';
$('#middle-input').val(result);
}
Finalize();
$(".padding-inputs").on('keyup change', function() {
Finalize();
});
});
Related
I have a function that sums my values and everything works fine, but only when all inputs have a value entered. However, I would like default to have 0 assigned to it.so that the function works when at least one value is given . How to do it ?.
var DeductiblepercentageM = thisPointer.entity.getValue('number.DeductiblepercentageM[' + i + ']');
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']');
var insuranceRaitingM = thisPointer.entity.getValue('number.insuranceRaitingM[' + i + ']');
var InsurerNumberM = thisPointer.entity.getValue('number.InsurerNumberM[' + i + ']');
DeductiblepercentageM = DeductiblepercentageM.replace(",", ".");
DeductiblepercentageM = parseFloat(DeductiblepercentageM)
InsuranceLimitM = InsuranceLimitM.replace(",", ".");
InsuranceLimitM = parseFloat(InsuranceLimitM)
insuranceRaitingM = insuranceRaitingM.replace(",", ".");
insuranceRaitingM = parseFloat(insuranceRaitingM)
InsurerNumberM = InsurerNumberM.replace(",", ".");
InsurerNumberM = parseFloat(InsurerNumberM)
//log the outcome of decimal separator change
var positionSum = +(DeductiblepercentageM + InsuranceLimitM +insuranceRaitingM + InsurerNumberM);
jQ('[id="DeductibleM[' + i + ']"]').val(positionSum);
thisPointer.entity.setValue('DeductibleM[' + i + ']', positionSum);
thisPointer.entity.mergeLocal(true);
if (totalSum != "NaN") {
totalSum = +(totalSum + positionSum).toFixed();
}
}
else {
totalSum = "-";
}
According to #Terry
var InsuranceLimitM = thisPointer.entity.getValue('number.InsuranceLimitM[' + i + ']') || 0;
adding || 0 to the end of the code helps and makes the code count right away
Very new to JavaScript, the first programming language I learned was Java. I am trying to make a simple website that displays the shortest distance between an infinite number of points using prompt boxes and a 2D array.
This code works as expected, however when one of the points has a negative number in it, nothing ever displays for an answer, throwing the error:
Uncaught TypeError: Cannot read property '0' of undefined
at run (index.html:54)
at HTMLButtonElement.onclick (index.html:63)
Google Chrome highlights the error at this line:
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
How can I get this program to work with negative numbers as well?
function run() {
var x, y;
var finalPoints = [];
var min = 0;
var toRun;
var temp;
var list = []; //using 2d array to store points
while (true) {
x = prompt("Enter an X-Value: ");
if (x == null || x == "") {
break;
}
y = prompt("Enter a Y-Value: ");
if (y == null || y == "") {
break;
}
list.push([x, y]);
}
if (list.length < 2) {
toRun = "Sorry, you didn't enter enough points for this program to run correctly. Please try again.";
} else if (list.length == 2) {
toRun = "Distance between points (" + list[0][0] + ", " + list[0][1] + ") and (" + list[1][0] + ", " + list[1][1] + ") is " + Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
} else {
min = Math.sqrt(Math.pow((list[0][0] - list[1][0]), 2) + Math.pow((list[0][1] - list[1][1]), 2));
for (var i = 0; i < list.length; i++) {
for (var j = 0; j < list.length; j++) {
temp = Math.sqrt(Math.pow((list[i][0] - list[j][0]), 2) + Math.pow((list[i][1] - list[j][1]), 2));
if (temp < min && temp != 0) {
min = temp;
finalPoints.push([list[i][0], list[j][0]]);
finalPoints.push([list[i][1], list[j][1]]);
}
}
}
toRun = "Shortest distance is " + min + " with these points: (" + finalPoints[0][0] + ", " + finalPoints[1][0] + ") and (" + finalPoints[0][1] + ", " + finalPoints[1][1] + ").";
}
document.getElementById("output").innerHTML = toRun;
}
body {
background-color: #0d0d0d;
}
p,
button,
h3 {
color: #FFFFFF;
background-color: #0d0d0d;
}
button {
border: 1px solid #FFFFFF;
}
<h3>Continue entering points. When done, click cancel or don't enter anything.</h3>
<br>
<button onclick="run()" style="size:40%">Click me to start!</button>
<p id=output>(Output will display here).</p>
So, I have a function (i am workng with jquery ui and running this on drag event, though for this question I don't think that is important)
Basically I have the following repetitive if else code:
And I am curious if there is a way to write this in one line(ish) and not have a 100 else if lines if I want to be able to support 100 steps (divisions of a total slider value).
var thisPos = $( ".sliderknob" ).position();
var x = thisPos.left - window['sliderhome'].left;
console.log("(" + x + ")");
l = Object.keys(obj_frameindex).length;
framefraction = 290/l;
if (x>-1 && x<framefraction){
console.log('frame 1');
frameselector(0);
$('#framecounter').html("FRAME " + 1);
}
else if (x>framefraction && x<framefraction*2){
console.log('frame 2');
frameselector(1);
$('#framecounter').html("FRAME " + 2);
}
else if (x>framefraction*2 && x<framefraction*3){
console.log('frame 3');
frameselector(2);
$('#framecounter').html("FRAME " + 3);
}
else if (x>framefraction*3 && x<framefraction*4){
console.log('frame 4');
frameselector(3);
$('#framecounter').html("FRAME " + 4);} //etc..........
Showing only 4 here, but imagine it goes on...
Any ideas?
One possible approach:
var frameNo = Math.max(0, Math.floor(x / framefraction)) + 1;
console.log('frame ' + frameNo);
frameselector(frameNo - 1);
$('#framecounter').html('FRAME ' + frameNo);
Do something like:
if x < 0 { return };
var f = Math.ceil(x / framefraction);
console.log(`frame` + f);
frameselector(f - 1);
$(`#framecounter`).html("FRAME " + f);
I am making a basic game with popup boxes.
My problem is that if you look at the goblinAttack function it will repeat till the goblin is dead but the damage is random.
For example, I hit the goblin 6 damage every time until it dies instead of it being a random number between 1 and 25 and the goblin does 4 damage on me every time it hits. Its boring. I wanted it to be random each hit but repeating the function seems to not give a random number each time.
//VARIABLES
var dmgMultiply = Math.floor(Math.random() * 10 + 1);
var dmg = 10;
var armour = 0;
var hp = 100;
//ENEMY VARIABLES
var dmgGoblin = Math.floor(Math.random() * 10 + 1);
var goblinHP = 100;
//ARRAYS
var choiceArray = ["Type 'sword' equip your sword.",
"Type 'run' if you're scared.",
"Type 'stats' to see your stats."];
var answerArray = ["sword", "run", "stats"];
var outcomeArrayOne = ["You equip your sword.",
"You run away. Game Over."];
var outcomeArrayTwo = ["Sword Equipped."]
//GAME CHOICE
function choice(a, b, c, x, y, z, aa, bb)
{
var answer = prompt(a + "\n" + b + "\n" + c);
if(answer == x)
{
alert(aa);
swordEquipped(outcomeArrayTwo[0]);
}
if(answer == y)
{
alert(bb);
}
if(answer == z)
{
displayStats();
}
}
//EQUIPPED SWORD
function swordEquipped(a)
{
dmg = 25;
dmgMultiply = Math.floor(Math.random() * 25 + 1);
alert(a + "\n" + "DMG : " + dmg);
goblinCombatStart("goblin");
}
//GOBLIN COMBAT START
function goblinCombatStart(g)
{
alert("A wild " + g + " appears!" + "\n" + "The " + g + " has 100 HP!");
goblinAttack("goblin")
}
function goblinAttack(g)
{
alert("The " + g + " swings his axe at you!" + "\n" + "The " + g + " does " + dmgGoblin + " damage to you!");
hp -= dmgGoblin;
var attack = prompt("Type 'attack' to swing your sword at the " + g + "\n" + "HP : " + hp);
if(attack == "attack")
{
alert("You swing your sword at the " + g + "\n" + "You did " + dmgMultiply + " to the " + g);
goblinHP -= dmgMultiply;
alert("The " + g + " is on " + goblinHP + "HP");
if(goblinHP < 0)
{
goblinDead();
}
if(goblinHP > 0)
{
goblinAttack("goblin");
}
}
else
{
alert("You dropped your sword an shouted " + "'" + attack + "'" + " in the goblins face. It wasn't very effective and the goblin choppped your head off");
}
}
function goblinDead()
{
alert("You have slain the puny goblin with only a few scratches!");
}
//GAME START
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
//STATISTICS
function displayStats()
{
var statCheck = confirm("HP : " + hp + "\n" +
"ARMOUR : " + armour + "\n" +
"DMG : " + dmg + "\n" +
"Press OK to continue");
if(statCheck == true)
{
choice(choiceArray[0], choiceArray[1], choiceArray[2],
answerArray[0], answerArray[1], answerArray[2],
outcomeArrayOne[0], outcomeArrayOne[1]);
}
}
Instead of computing the random damage value only once at the beginning of your script, compute them whenever you need them. That would probably be in your attack function.
Maybe you are misunderstand something here: Math.random doesn't return some special magical value which changes every time it's read. It returns a number and that number doesn't change.
If you want multiple random values, you have to call Math.random multiple times. If you want a different random value whenever the goblin attacks, you have to call Math.random when it attacks.
The problem here is that you're initializing your variables at the beginning as random.
That means that, on every move, it will use the same random number that was generated at the beginning.
If you want it to be random for each time, you have to call Math.random() on every move.
As it stands, dmgMultiply and dmgGoblin are computed randomly once and use the same value on each turn, so you end up getting the same amount of damage taken and dealt each time.
Declare your variables at the beginning:
var dmgMultiply;
var dmgGoblin;
Then, set them to a random number within your attack function so that it computes a random number each turn:
function goblinAttack(g)
{
dmgMultiply = Math.floor(Math.random() * 10 + 1);
dmgGoblin = Math.floor(Math.random() * 10 + 1);
...
}
Demo
Purpose of the code shown is to add by time some reminder. the cases are for different days of the week and in that days specific times.
Strange thing some statements are working most not, but i dont see what breaks the code:
function refreshTime() {
var now = getTime();
$('#date').html(now.day + ', ' + now.date + '. ' + now.month);
$('#time').html("<span class='hour'>" + now.hour + "</span>" + "<span class='minute'>" + now.minute + "</span>" + "<span class='second'>" + now.second + "</span>");
if (now.day != "Sonntag" && now.day != "Samstag")
{
if (now.hour == "9" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == '11' && now.minute >= '50')
{
var left = '60' - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == '14' && now.minute >= '50')
{
var left = '60' - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "17" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
else
{
$('#gh').html("");
}
}
if (now.day == "Samstag")
{
if (now.hour == "9" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "12" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
if (now.hour == "13" && now.minute >= "50")
{
var left = "60" - now.minute;
$('#gh').html("<span class='gh_remind'>Grosshandel einstellen in " + left + " Minuten!</span>");
}
else
{
$('#gh').html("");
}
}
}
Thanks for your help!
Consider this:
var a = 'a', b;
if (a == 'a') {
b = 'right';
}
if (a == 'c') {
b = 'wrong';
}
else {
b = 'FOOBAR!';
}
alert(b);
Even though you (probably) expect b to store 'right' value in the end of that if structure, it - surprise, surprise! - will contain FOOBAR instead. The reason is that if all your ifs are written like this, they're independent of each other. The first one will assign 'right' string to b variable - but the second one, going through else branch, will happily reassign it (to some foobar).
If you want to create a chain of ifs, use if - else if - else syntax instead:
var a = 'a', b;
if (a == 'a') {
b = 'right';
}
else if (a == 'c') {
b = 'wrong';
}
else {
b = 'FOOBAR!';
}
alert(b);
Now that will show you the right thing, right? )
Strings are not numbers. Do not use quotes around numbers unless you actually want it to be a string.
> console.log("1">"50")
false
> console.log("9">"50")
true