I'm a beginner in programming and I have been trying to make my 3 random generated numbers and the answer never to be the same, but no matter how I tried I didn't get the result that I wanted. I would be very thankful if someone would put me on the right path :)
This is a piece of code for the first randomly generated number, the other two are exactly the same.
//Random number 1
{
btnAns1.label = "" + random1;
if(mathOperationL1 == 1)
{
random1 = Math.floor(Math.random()* 24) + 1;
do
{
random1 = Math.floor(Math.random()* 24) + 1;
}
while((random1 > 24) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
btnAns1.label = "" + random1;
}
else if (mathOperationL1 == 2)
{
random1 = Math.floor(Math.random()* 11) + 1;
do
{
random1 = Math.floor(Math.random()* 11) + 1;
}
while((random1 > 11) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
btnAns1.label = "" + random1;
}
else if (mathOperationL1 == 3)
{
random1 = Math.floor(Math.random()* 144) + 1;
do
{
random1 = Math.floor(Math.random()* 144) + 1;
}
while((random1 > 144) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
btnAns1.label = "" + random1;
}
else if (mathOperationL1 == 4)
{
random1 = Math.floor(Math.random()* 12) + 1;
do
{
random1 = Math.floor(Math.random()* 12) + 1;
}
while((random1 > 12) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
btnAns1.label = "" + random1;
}
}
There are no errors in the code and everything else is working perfectly.It is just the line of code that is supposed to make the numbers never to be the same just doesn't work and after running the code for few times I eventually get numbers that are the same. while((random1 > 24) && (random1 === answerL1) && (random1 === random2) && (random1 === random3));
Thanks for your help in advance! :)
Your condition while((random1 > 24)... is always false because you generate numbers like 1 to 24 and they NEVER exceed 24.
Lets do it algorithmically.
var aList:Array = new Array;
// Put the user's input here. Don't forget that
// TextField.text contains String value rather than int.
aList[0] = 5;
// Each line adds a random element different from
// the elements that are already in the Array.
aList[1] = smartRandom(1, 10, aList);
aList[2] = smartRandom(4, 15, aList);
aList[3] = smartRandom(9, 20, aList);
// Let's see what we get this time.
trace(aList);
// Generates a random int from "min" to "max" inclusive,
// while avoiding all the numbers from the "avoid" Array.
// Note that it doesn't actually checks if it is possible
// to do so, thus smartRandom(1, 1, [1]) will result in the
// infinite loop because conditions will never be satisfied.
function smartRandom(min:int, max:int, avoid:Array):int
{
var result:int;
do
{
result = min + Math.random() * (max - min + 1);
}
// The Array.indexOf(...) method returns -1 if the argument
// is not on the given Array or it returns a 0-based
// index of the element that is equal to the given argument.
while (avoid.indexOf(result) > -1);
return result;
}
while((random1 > 24) || (random1 === answerL1) || (random1 === random2) || (random1 === random3));
The && operator insists that all the tests are true if it is to run again. The || is the logical OR, so any combination tested will cause the loop to run again.
Edit: I should also say, there seems to be alot of duplicated effort in this code.. perhaps once you are comfortable with your operator's behaviour you will be able to simplify the flow.
Related
I want to restrict decimal places up to 1. User shouldnt type multiple dots(1..99) and (1.99). I want 1.9 2.6 for ex. Not 2.66 then convert into 2.7 etc. I have to use pe:sheetcolumn. I tried to add p:inputnumber and other p: components than pe extension. But pe:sheetcolumn have to be. With below approach it just let user to type multiple dots and multiple decimal places. It just convert to 1 decimal after user entered value on screen with #0.0. But i want to restrict on input to type multiple decimal places than 1 and multiple dots. I thought about javascript keyup event but i think it would be bad approach. How can i achive that
<pe:sheetcolumn headerText="SOME" value="#{SOME.some}" colWidth="200"
colType="numeric" numericPattern="#0.0" >
</pe:sheetcolumn>
For example for p:inputNumber as you can see on image user cant type multiple dots and they cant add decimal places more than 6.
Example
I want to do same thing with pe:sheetColumn. How can i do that
My JSF VERSION : 2.2.1 PRÄ°MEFACES AND PRIMEFACES EXTENSION VERSION : 6.2
If you install this MonkeyPatch you can then tweak the output to do whatever your want. I am pretty sure you can get the current cell with var currentValue = this.getDataAtCell(row , col) If you add this JS to your app you can then tweak how it handles keypresses and validation.
I added this line for you
var currentValue = this.getDataAtCell(row , col); // VALUE HERE!
So you can validate whatever your want with your code and if there is already a "." don't accept another "." etc.
if (PrimeFaces.widget.ExtSheet) {
PrimeFaces.widget.ExtSheet.prototype.handleHotBeforeKeyDown = function(e) {
var selectedLast = this.getSelectedLast();
if (!selectedLast) {
return;
}
var row = selectedLast[0];
var col = selectedLast[1];
var celltype = this.getCellMeta(row, col).type;
var currentValue = this.getDataAtCell(row , col); // VALUE HERE!
var evt = e || window.event; // IE support
var key = evt.charCode || evt.keyCode || 0;
var shiftDown = e.shiftKey;
// #740 tab on last cell should focus this next component
if (this.allowTabOffSheet && key == 9) {
var lastRow = this.countRows() - 1;
var lastCol = this.countCols() - 1;
if ((!shiftDown && row === lastRow && col === lastCol) ||
(shiftDown && row === 0 && col === 0)) {
e.stopImmediatePropagation();
this.unlisten();
this.deselectCell();
//add all elements we want to include in our selection
var focusableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]):not([hidden]):not([aria-hidden="true"]), [tabindex]:not([disabled]):not([tabindex="-1"]):not([aria-hidden="true"])';
if (document.activeElement && document.activeElement.form) {
var focusable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focusableElements),
function(element) {
//check for visibility while always include the current activeElement
return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
});
var index = focusable.indexOf(document.activeElement);
if (index > -1) {
var nextElement = focusable[index + 1] || focusable[0];
nextElement.focus();
}
}
}
return;
}
// prevent Alpha chars in numeric sheet cells
if (celltype === "numeric") {
// #766 do not block if just CTRL or SHIFT key
if (key === 16 || key === 17) {
return;
}
// #739 allow navigation
var ctrlDown = evt.ctrlKey || evt.metaKey; // Mac support
if (shiftDown || ctrlDown) {
// navigation keys
if (key == 9 || (key >= 35 && key <= 40)) {
return;
}
}
// check for cut and paste
var isClipboard = false;
// Check for Alt+Gr (http://en.wikipedia.org/wiki/AltGr_key)
if (ctrlDown && evt.altKey) isClipboard = false;
// Check for ctrl+c, v and x
else if (ctrlDown && key == 65) isClipboard = true; // a (select all)
else if (ctrlDown && key == 67) isClipboard = true; // c
else if (ctrlDown && key == 86) isClipboard = true; // v
else if (ctrlDown && key == 88) isClipboard = true; // x
// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers
// ONLY home, end, F5, F12, minus (-), period (.)
// console.log('Key: ' + key + ' Shift: ' + e.shiftKey + ' Clipboard: ' + isClipboard);
var isNumeric = ((key == 8) || (key == 9) || (key == 13) ||
(key == 46) || (key == 110) || (key == 116) ||
(key == 123) || (key == 188) || (key == 189) ||
(key == 190) || ((key >= 35) && (key <= 40)) ||
((key >= 48) && (key <= 57)) || ((key >= 96) && (key <= 105)));
if ((!isNumeric && !isClipboard) || shiftDown) {
// prevent alpha characters
e.stopImmediatePropagation();
e.preventDefault();
}
}
}
}
I got a problem when filtering the age range in DataTables. I am using DataTables ver 1.10.10. I am confused because when I started to build the code it was working properly, but when I tested again, it's not working anymore.
I hope anyone could tell me where I am missing since it is a very noob question.
Here is my javascript
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var from = parseInt( $('#ageFrom').val(), 10 );
var to = parseInt( $('#ageTo').val(), 10);
var age = parseFloat( data[3] ) || 0;
if ( (isNaN(from) && isNaN(to)) ||
(isNaN(from) && age <= to) ||
(from <= age && isNaN(to)) ||
(from <= age && age <= to) )
{
return true;
}
return false;
}
);
$('#ageFrom, #ageTo').on('change keyup', function() {
if ($('#ageFrom').val() == "" || $('#ageTo').val() == "") {
table.draw()
}
else {
table.draw();
}
});
Thanks in advance!
Cheers
This problem is happening both in IE and Chrome.
This is an HTML 5 with Angular JS 4 application. I am using TypeScript. My main aim in a table row I need to make enter, right, and left arrows of keyboard work and set focus on corresponding table cells
I have a page which has a dropdown. It has names of students. I also have a table with single row like below with multiple columns
When I launch by default a student is selected in dropdown which populates students details in table. I made each cell in row as editable. So when user clicks on any cell in the row and presses enter key I move to next cell and so the functions for right arrow and left arrow are working fine on first load/launch of my application.
But when I change another student from my dropdown, I refresh the page to show new selected student details. From this point if I select a cell in the row my enter key, left,
and right arrows are not working. Please see below for my code
Thank you very much in advance.
<table>
<tr>
<td *ngFor="let item of student.classes " >
<!-- I need to use div to make cell editable in IE. -->
<div name='TotalDistributableQtyCell' [id]="item.cellId"
[contentEditable]='!isDisabled' [textContent]="item.value"
(keydown)="onKeydown($event, item)"
style="line-height:1.8em;">{{item.value}}</div>
</td>
</tr>
<table>
MyComponent.ts
totalDistributableQtyCells: HTMLElement[];
ngAfterViewChecked() {
const distCells = document.getElementsByName('TotalDistributableQtyCell');
if(distCells !== null && distCells !== undefined && distCells.length > 0) {
if(this.totalDistributableQtyCells === null || this.totalDistributableQtyCells === undefined) {
this.totalDistributableQtyCells = [];
}
for ( let i = 0 ; i < distCells.length; i++) {
const index = this.totalDistributableQtyCells.findIndex( x => x.id !== undefined && x.id === distCells[i].id);
if(index === -1) {
this.totalDistributableQtyCells.push(distCells[i]);
}
}
}
}
private onKeydown(event: any, item: ITotalDistributableQuantity) {
const key_code = (window.event) ? event.keyCode : event.which;
if (this.deviceInfo.browser === 'ie') {
console.log('ie: event.keyCode ' + event.keyCode);
switch(event.keyCode.toString()) {
case '13': //enter
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[1].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[0].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[item.sequenceNumber - 1].focus();
}
break;
case '39': //right
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[1].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[0].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[item.sequenceNumber - 1].focus();
}
break;
case '37': //left
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[this.totalDistributableQtyCells.length - 1 ].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[this.totalDistributableQtyCells.length - 2 ].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < 11) {
this.totalDistributableQtyCells[item.sequenceNumber - 3].focus();
}
break;
}
}else if ( this.deviceInfo.browser === 'chrome') {
console.log('chrome: event.key ' + event.key);
switch(event.key) {
case 'Enter':
event.preventDefault();
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[1].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[0].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[item.sequenceNumber - 1].focus();
}
break;
case 'ArrowRight':
event.preventDefault();
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[1].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[0].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[item.sequenceNumber - 1].focus();
}
break;
case 'ArrowLeft':
event.preventDefault();
if(item.sequenceNumber === 2) {
this.totalDistributableQtyCells[this.totalDistributableQtyCells.length - 1 ].focus();
} else if ( item.sequenceNumber === this.totalDistributableQtyCells.length + 1) {
this.totalDistributableQtyCells[this.totalDistributableQtyCells.length - 2 ].focus();
} else if (item.sequenceNumber > 2 && item.sequenceNumber < 11) {
this.totalDistributableQtyCells[item.sequenceNumber - 3].focus();
}
break;
}
}
}
Okay someone could really help me with this I've been working REALLY hard to get this working up until this point. One last thing is I need is the nextquestion1 function to bring me to the last from of my application.
I click on my button nextQuestion_btn to take me to one of the labled frames I have. I click on it and nothing happens. Also there is a lot of missing code in between the two Event Listener's , just so you know.
So...How can I make this code so I can trigger the next frame with the button?
stage.addEventListener(Event.CHANGE, checkTotal1000)
function checkTotal1000(e:Event){
var tech:Number = parseInt(tech_txt.text);
var med:Number = parseInt(med_txt.text);
var space:Number = parseInt(space_txt.text);
var genetic:Number = parseInt(ge_txt.text);
var worldComp:Number = parseInt(worldComp_txt.text);
var mars:Number = parseInt(mars_txt.text);
var worldColab:Number = parseInt(worldColab_txt.text);
var nothing:Number = parseInt(nothing_txt.text);
var zombieApocFinal:Number = zombieApoc + genetic;
var robotApocFinal:Number = robotApoc+ tech;
var plagueFinal:Number = plague + med;
var asteroidFinal:Number = asteroid + mars;
var iceAgeFinal:Number = iceAge + nothing;
var aliensFinal:Number = aliens + space;
var nukeWarFinal:Number = nukeWar + worldComp;
//var happyEverAfterFinal:Number = ;
trace(aliensFinal);
var total1000:Number = tech + med + space +
worldComp + mars + genetic + worldColab + nothing;
nextQuestion_btn.addEventListener(MouseEvent.MOUSE_DOWN, nextQuestion1)
function nextQuestion1(e:MouseEvent){
if(tech && med && space && genetic && worldComp
&& mars && worldColab && nothing == 125){
gotoAndStop(7);
}
if(robotApocFinal > zombieApocFinal && plagueFinal &&
asteroidFinal && iceAgeFinal && aliensFinal &&
nukeWarFinal){
gotoAndStop("Robot");
}
else if(zombieApocFinal > robotApocFinal && plagueFinal &&
asteroidFinal && iceAgeFinal && aliensFinal &&
nukeWarFinal){
gotoAndStop("Zombie");
}
else if( plagueFinal > zombieApocFinal && robotApocFinal &&
asteroidFinal && iceAgeFinal && aliensFinal &&
nukeWarFinal){
gotoAndStop("Plague");
}
else if( asteroidFinal > zombieApocFinal && robotApocFinal &&
plagueFinal && iceAgeFinal && aliensFinal &&
nukeWarFinal){
gotoAndStop("Asteroid");
}
else if( iceAgeFinal > zombieApocFinal && robotApocFinal &&
plagueFinal && asteroidFinal && aliensFinal &&
nukeWarFinal){
gotoAndStop("IceAge");
}
else if( aliensFinal > zombieApocFinal && robotApocFinal &&
plagueFinal && asteroidFinal && iceAgeFinal &&
nukeWarFinal){
gotoAndStop("Aliens");
}
else if( nukeWarFinal > zombieApocFinal && robotApocFinal &&
plagueFinal && asteroidFinal && iceAgeFinal &&
aliensFinal){
gotoAndStop("Nuke");
}
}
}
Apparently you are using binary flags, but you use && operator which only works with booleans. This way if either of your ints is 0, no condition is satisfied. You apparently want to trigger the gotoAndStop() if one of the ints is greater than others. For this you can use the following code:
var bestFinal:int=Math.max(asteroidFinal, zombieApocFinal, robotApocFinal,
plagueFinal, iceAgeFinal, aliensFinal, nukeWarFinal);
if (bestFinal==asteroidFinal) {...}
else if (bestFinal==zombieApocFinal) {...}
...
If you are about to test if one var is greater than all the others, you cannot use what you've written, instead you use either Math.max() and check for equality, or you write many comparations and unite them via &&, like this:
if ((asteroidFinal > zombieApocFinal) && (asteroidFinal > robotApocFinal) &&
(asteroidFinal > plagueFinal) && (asteroidFinal > iceAgeFinal) &&
(asteroidFinal > aliensFinal) && (asteroidFinal > nukeWarFinal))
Texbox restrict entering characters and symbols and only allow numeric values with only one decimal point.maximum length 4 and one value after decimal point.For eg: .2,12.3,1444
Here is the code in html to allow only one decimal point in a textbox:
<script type="text/javascript" language="javascript">
function isNumberKey(evt) {
var charCode = (evt.charCode) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57) && charCode != 46)
return false;
else {
var input = document.getElementById("txtChar").value;
var len = document.getElementById("txtChar").value.length;
var index = document.getElementById("txtChar").value.indexOf('.');
if (index > 0 && charCode == 46) {
return false;
}
if (index >0 || index==0) {
var CharAfterdot = (len + 1) - index;
if (CharAfterdot > 2) {
return false;
}
}
if (charCode == 46 && input.split('.').length >1) {
return false;
}
I want to done this in asp.net using c#.This code is not properly working in asp.net.
Please Check this Link - Validate Input Field which will allows Only Float...
$(function(){
$('.float-input').keyup(function(e){
var entered_value = $(this).val();
var regexPattern = /^\d{0,8}(\.\d{1,2})?$/;
//Allow only Number as well 0nly 2 digit after dot(.)
if(regexPattern.test(entered_value)) {
$(this).css('background-color', 'white');
$('.err-msg').html('');
} else {
$(this).css('background-color', 'red');
$('.err-msg').html('Enter a valid Decimal Number');
}
});
});