Why output is showing on next click in Reactjs - javascript

I am new to ReactJS that is why my code might have few errors,but I don't want that for now.I am creating a tic-tac-toe,everything is working fine except for that the winner is updating on next onMouseUp event. I searched everywhere but I am not able to find the error.
Here is the code.
var Mycheck = React.createClass({
getInitialState: function() {
return {
disppp: "block",
disppp2: "none",
cnt: 0,
active: 1,
turnNum: 0
}
},
handleClick: function(event, key) {
this.setState({
cnt: this.state.cnt + 1
})
var divId = parseInt(event.target.id);
var valvar = [];
if (this.state.active) {
if (this.state.cnt < 9) {
this.setState({
turnNum: this.state.turnNum + 1
})
if (this.state.cnt % 2 == 0) {
valvar[key] = "X";
this.setState(valvar)
this.setState({
disppp: "none",
disppp2: "block"
})
} else {
valvar[key] = "O";
this.setState(valvar)
this.setState({
disppp: "block",
disppp2: "none"
})
}
} else {
alert("GAME DRAW");
}
}
this.Findvalue();
},
Findvalue: function() {
var arr = [];
var winner;
var resultant = {
r1: [1, 2, 3],
r2: [4, 5, 6],
r3: [7, 8, 9],
r4: [1, 4, 7],
r5: [2, 5, 8],
r6: [3, 6, 9],
r7: [1, 5, 9],
r8: [3, 5, 7]
};
for (var i = 1; i < 10; i++) {
arr[i] = document.getElementById(i).innerHTML;
}
if (arr[resultant.r1[0]] == arr[resultant.r1[1]] && arr[resultant.r1[0]] == arr[resultant.r1[2]] && arr[resultant.r1[0]] != "" && arr[resultant.r1[1]] != "" && arr[resultant.r1[2]] != "") {
winner = arr[resultant.r1[0]];
}
if (arr[resultant.r2[0]] == arr[resultant.r2[1]] && arr[resultant.r2[0]] == arr[resultant.r2[2]] && arr[resultant.r2[0]] != "" && arr[resultant.r2[1]] != "" && arr[resultant.r2[2]] != "") {
winner = arr[resultant.r2[0]];
}
if (arr[resultant.r3[0]] == arr[resultant.r3[1]] && arr[resultant.r3[0]] == arr[resultant.r3[2]] && arr[resultant.r3[0]] != "" && arr[resultant.r3[1]] != "" && arr[resultant.r3[2]] != "") {
winner = arr[resultant.r3[0]];
}
if (arr[resultant.r4[0]] == arr[resultant.r4[1]] && arr[resultant.r4[0]] == arr[resultant.r4[2]] && arr[resultant.r4[0]] != "" && arr[resultant.r4[1]] != "" && arr[resultant.r4[2]] != "") {
winner = arr[resultant.r4[0]];
}
if (arr[resultant.r5[0]] == arr[resultant.r5[1]] && arr[resultant.r5[0]] == arr[resultant.r5[2]] && arr[resultant.r5[0]] != "" && arr[resultant.r5[1]] != "" && arr[resultant.r5[2]] != "") {
winner = arr[resultant.r5[0]];
}
if (arr[resultant.r6[0]] == arr[resultant.r6[1]] && arr[resultant.r6[0]] == arr[resultant.r6[2]] && arr[resultant.r6[0]] != "" && arr[resultant.r6[1]] != "" && arr[resultant.r6[2]] != "") {
winner = arr[resultant.r6[0]];
}
if (arr[resultant.r7[0]] == arr[resultant.r7[1]] && arr[resultant.r7[0]] == arr[resultant.r7[2]] && arr[resultant.r7[0]] != "" && arr[resultant.r7[1]] != "" && arr[resultant.r7[2]] != "") {
winner = arr[resultant.r7[0]];
}
if (arr[resultant.r8[0]] == arr[resultant.r8[1]] && arr[resultant.r8[0]] == arr[resultant.r8[2]] && arr[resultant.r8[0]] != "" && arr[resultant.r8[1]] != "" && arr[resultant.r8[2]] != "") {
winner = arr[resultant.r8[0]];
}
if (winner == "X") {
this.setState({
active: 0
})
alert("WINNER IS PLAYER 1");
}
if (winner == "O") {
this.setState({
active: 0
})
alert("WINNER IS PLAYER 2");
}
},
render: function() {
var divVal = "";
var i = 0;
return ( < div >
< div className = "turn_num" > TURN NUMBER: {
this.state.turnNum + 1
} < /div>
<button style={{display:this.state.disppp}}>PLAYER 1 FOR X</button >
< button style = {
{
display: this.state.disppp2
}
} > PLAYER 2 FOR O < /button><br/ > < br / >
< button className = "square"
id = "1"
onMouseUp = {
e => this.handleClick(e, "valvar1")
}
disabled = {
this.state.valvar1
} > {
this.state.valvar1
} < /button>
<button className="square" id="2" onMouseUp={e => this.handleClick(e,"valvar2")} disabled={this.state.valvar2}>{this.state.valvar2}</button >
< button className = "square"
id = "3"
onMouseUp = {
e => this.handleClick(e, "valvar3")
}
disabled = {
this.state.valvar3
} > {
this.state.valvar3
} < /button>
<button className="square clearB" id="4" onMouseUp={e => this.handleClick(e,"valvar4")} disabled={this.state.valvar4}>{this.state.valvar4}</button >
< button className = "square"
id = "5"
onMouseUp = {
e => this.handleClick(e, "valvar5")
}
disabled = {
this.state.valvar5
} > {
this.state.valvar5
} < /button>
<button className="square"id="6" onMouseUp={e => this.handleClick(e,"valvar6")} disabled={this.state.valvar6}>{this.state.valvar6}</button >
< button className = "square clearB"
id = "7"
onMouseUp = {
e => this.handleClick(e, "valvar7")
}
disabled = {
this.state.valvar7
} > {
this.state.valvar7
} < /button>
<button className="square" id="8" onMouseUp={e => this.handleClick(e,"valvar8")} disabled={this.state.valvar8}>{this.state.valvar8}</button >
< button className = "square"
id = "9"
onMouseUp = {
e => this.handleClick(e, "valvar9")
}
disabled = {
this.state.valvar9
} > {
this.state.valvar9
} < /button><br/ > < br / > < br / >
< /div>
);
}
});
ReactDOM.render(<Mycheck></Mycheck > , document.getElementById("container"));
.square {
height: 50px;
width: 50px;
border: 1px solid black;
background: none;
float: left;
padding: 10px;
text-align: center;
font-size: 25px;
font-weight: bold;
color: #146fbe;
}
.clearB {
clear: both;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>

Related

Tic Tac Toe: X go first

I took this code from the internet and want to modify it so that regardless of which symbol I select, the x starts first (the computer in this case).
If I select to play with X, I will start first and the computer will play with O.
If I select to play with O, the computer will receive X and make the first move.
const selectBox = document.querySelector(".select-box"),
selectBtnX = selectBox.querySelector(".options .playerX"),
selectBtnO = selectBox.querySelector(".options .playerO"),
playBoard = document.querySelector(".play-board"),
players = document.querySelector(".players"),
allBox = document.querySelectorAll("section span"),
resultBox = document.querySelector(".result-box"),
wonText = resultBox.querySelector(".won-text"),
replayBtn = resultBox.querySelector("button");
let x = 'x';
let O = 'O';
window.onload = () => {
for (let i = 0; i < allBox.length; i++) {
allBox[i].setAttribute("onclick", "clickedBox(this)");
}
}
selectBtnX.onclick = () => {
selectBox.classList.add("hide");
playBoard.classList.add("show");
}
selectBtnO.onclick = () => {
selectBox.classList.add("hide");
playBoard.classList.add("show");
players.setAttribute("class", "players active player");
}
let playerXIcon = "fas fa-times",
playerOIcon = "far fa-circle",
playerSign = "X",
runBot = true;
function clickedBox(element) {
if (players.classList.contains("player")) {
playerSign = "O";
element.innerHTML = `<i class="${playerOIcon}"></i>`;
players.classList.remove("active");
element.setAttribute("id", playerSign);
} else {
element.innerHTML = `<i class="${playerXIcon}"></i>`;
element.setAttribute("id", playerSign);
players.classList.add("active");
}
selectWinner();
element.style.pointerEvents = "none";
playBoard.style.pointerEvents = "none";
let randomTimeDelay = ((Math.random() * 1000) + 200).toFixed();
setTimeout(() => {
bot(runBot);
}, randomTimeDelay);
}
function bot() {
let array = [];
if (runBot) {
playerSign = "O";
for (let i = 0; i < allBox.length; i++) {
if (allBox[i].childElementCount == 0) {
array.push(i);
}
}
let randomBox = array[Math.floor(Math.random() * array.length)];
if (array.length > 0) {
if (players.classList.contains("player")) {
playerSign = "X";
allBox[randomBox].innerHTML = `<i class="${playerXIcon}"></i>`;
allBox[randomBox].setAttribute("id", playerSign);
players.classList.add("active");
} else {
allBox[randomBox].innerHTML = `<i class="${playerOIcon}"></i>`;
players.classList.remove("active");
allBox[randomBox].setAttribute("id", playerSign);
}
selectWinner();
}
allBox[randomBox].style.pointerEvents = "none";
playBoard.style.pointerEvents = "auto";
playerSign = "X";
}
}
function getIdVal(classname) {
return document.querySelector(".box" + classname).id;
}
function checkIdSign(val1, val2, val3, sign) {
if (getIdVal(val1) == sign && getIdVal(val2) == sign && getIdVal(val3) == sign) {
return true;
}
}
function selectWinner() {
if (checkIdSign(1, 2, 3, playerSign) || checkIdSign(4, 5, 6, playerSign) || checkIdSign(7, 8, 9, playerSign) || checkIdSign(1, 4, 7, playerSign) || checkIdSign(2, 5, 8, playerSign) || checkIdSign(3, 6, 9, playerSign) || checkIdSign(1, 5, 9, playerSign) || checkIdSign(3, 5, 7, playerSign)) {
runBot = false;
bot(runBot);
setTimeout(() => {
resultBox.classList.add("show");
playBoard.classList.remove("show");
}, 700);
wonText.innerHTML = `<p>${playerSign}</p> wins!`;
} else {
if (getIdVal(1) != "" && getIdVal(2) != "" && getIdVal(3) != "" && getIdVal(4) != "" && getIdVal(5) != "" && getIdVal(6) != "" && getIdVal(7) != "" && getIdVal(8) != "" && getIdVal(9) != "") {
runBot = false;
bot(runBot);
setTimeout(() => {
resultBox.classList.add("show");
playBoard.classList.remove("show");
}, 700);
wonText.textContent = "It's a draw!";
}
}
}
replayBtn.onclick = () => {
window.location.reload();
}
I think when you select to play with 0, you should call bot to make a first move.
You can refer
selectBtnO.onclick = () => {
selectBox.classList.add("hide");
playBoard.classList.add("show");
players.setAttribute("class", "players active player");
bot(true); // call bot when you selet to play with O
}

How i can optimize this code, whithout creating variable `a`?

Help to optimize below functions, whithout creating variable a
getFieldsGroups(){
let a = [];
if(this.activeTab.fieldsGroupName === ''){
this.activeTab = {
groupIndex: 0,
subgroupIndex: 0,
fieldsGroupName: this.groups[0][0].name
}
}
this.groups.forEach((group, groupIndex) => {
group.forEach((fieldsGroup, fieldsGroupIndex) => {
if(
groupIndex == this.activeTab.groupIndex &&
fieldsGroup.name == this.activeTab.fieldsGroupName
){
a.push(fieldsGroup);
}
})
})
return a.length == 1 ? [] : a;
}
getFields(){
let a;
this.groups.forEach((group, groupIndex) => {
group.forEach((fieldsGroup, fieldsGroupIndex) => {
if(
groupIndex == this.activeTab.groupIndex &&
fieldsGroup.name == this.activeTab.fieldsGroupName
){
if(this.activeFieldsGroup.name === '' && fieldsGroup.name === this.activeTab.fieldsGroupName){
a = group.filter(_fieldsGroup => _fieldsGroup.name === this.activeTab.fieldsGroupName)[0];
}else if(fieldsGroup.label == this.activeFieldsGroup.label){
a = fieldsGroup;
}
}
})
})
return a.fields.length == 1 ? [] : a.fields;
},

Variable only works locally

I wrote some functions involving prime factorization and I noticed that when I identified my test paragraph (for testing the results of functions and such) as document.getElementById("text"), it worked fine. However, when I declared a global variable text as var text = document.getElementById("text"), and then substituted in text for the longer version, it no longer worked. I did, however, notice that it worked when I locally declared text. Why is this and how can I fix it? My JSFiddle is here: https://jsfiddle.net/MCBlastoise/3ehcz214/
And this is my code:
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
}
else if (num === 2) {
return true;
}
else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
}
else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
}
else if (dig === 2) {
return undefined;
}
else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
}
else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
}
else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
}
else if (isPrime(int) === true) {
return false;
}
else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
}
else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
//text.innerHTML = isPrime(6);
<div onclick="listPrimes()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
The text is global, you just need to make sure the whole script file is included in the html. Here's an example of what I mean
Here in code snippets stackoverflow does this for us already.
var text = document.getElementById("text");
function isPrime(num) {
var lastDigit = parseInt((num + "").split("").reverse()[0]);
if (typeof num !== "number" || num <= 1 || num % 1 !== 0) {
return undefined;
} else if (num === 2) {
return true;
} else if (lastDigit === 0 || lastDigit === 2 || lastDigit === 4 || lastDigit === 5 || lastDigit === 6 || lastDigit === 8) {
return false;
} else {
for (var i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}
}
function factorSplit(dig) {
if (typeof dig !== "number" || dig <= 1 || dig % 1 !== 0) {
return undefined;
} else if (dig === 2) {
return undefined;
} else {
var factor;
for (var i = 2; i < dig; i++) {
if (dig % i === 0) {
factor = i;
break;
}
}
if (factor === undefined) {
return undefined;
} else {
return [factor, (dig / factor)];
}
}
}
function allPrimes(arr) {
if (Array.isArray(arr) === false || arr.length < 1) {
return undefined;
} else {
for (var i = 0; i < arr.length; i++) {
if (isPrime(arr[i]) !== true) {
return false;
}
}
return true;
}
}
function primeFactors(int) {
if (typeof int !== "number" || int <= 1) {
return undefined;
} else if (isPrime(int) === true) {
return false;
} else {
var initFactors = factorSplit(int);
while (allPrimes(initFactors) !== true) {
initFactors = initFactors.concat(factorSplit(initFactors[initFactors.length - 1]));
initFactors.splice((initFactors.length - 3), 1);
}
return initFactors;
}
}
function listPrimes() {
repeat = setInterval(findPrime, 1);
}
var primeInts = [2];
var check;
function findPrime() {
var i = primeInts[primeInts.length - 1] + 1;
if (check === undefined) {
check = true;
text.innerHTML = primeInts[0];
} else {
while (isPrime(i) !== true) {
i++;
}
primeInts.push(i);
text.innerHTML += ", " + primeInts[primeInts.length - 1];
}
}
function test() {
console.log("inside test1")
console.log(text);
text.innerHTML = "testtt"
}
function test2() {
console.log("inside test2")
console.log(text);
text.innerHTML = "testtt2"
}
text.innerHTML = isPrime(6);
<div onclick="test()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
<p id="text"></p>
<div onclick="test2()" style="cursor:pointer; background-color:black; width:30px; height:30px"></div>
In the head the script runs/loads first and because you don't have the var's in a function they are never re-used they remain with the original value which is null since the document didn't exist at that time, then when the page loads all it has is access to the functions a call to the global var is null. This is why the code previously only worked when text = document.getElementById('text') was in a function.

Why is the output showing on next onMouseUp event in Reactjs

I am new to ReactJS that is why my code might have few errors,but I don't want that for now.I am creating a tic-tac-toe,everything is working fine except for that the winner is updating on next onMouseUp event. I searched everywhere but I am not able to find the error.
What I am trying to say that when we play tic-tac-toe the player who wins will be alerted as he wins but in my code its not happening.It comes after I do onMouseUp event on the className="square".
Here is the code.
var Mycheck = React.createClass({
getInitialState: function() {
return {
disppp: "block",
disppp2: "none",
cnt: 0,
active: 1,
turnNum: 0,
player: "",
showWinner: "none"
}
},
handleClick: function(event, key) {
this.setState({
cnt: this.state.cnt + 1
})
var divId = parseInt(event.target.id);
var valvar = [];
if (this.state.active) {
if (this.state.cnt < 9) {
this.setState({
turnNum: this.state.turnNum + 1
})
if (this.state.cnt % 2 == 0) {
valvar[key] = "X";
this.setState(valvar)
this.setState({
disppp: "none",
disppp2: "block"
})
} else {
valvar[key] = "O";
this.setState(valvar)
this.setState({
disppp: "block",
disppp2: "none"
})
}
} else {
alert("GAME DRAW");
}
}
this.Findvalue();
},
Findvalue: function() {
var arr = [];
var winner;
var resultant = {
r1: [1, 2, 3],
r2: [4, 5, 6],
r3: [7, 8, 9],
r4: [1, 4, 7],
r5: [2, 5, 8],
r6: [3, 6, 9],
r7: [1, 5, 9],
r8: [3, 5, 7]
};
for (var i = 1; i < 10; i++) {
arr[i] = document.getElementById(i).innerHTML;
}
if (arr[resultant.r1[0]] == arr[resultant.r1[1]] && arr[resultant.r1[0]] == arr[resultant.r1[2]] && arr[resultant.r1[0]] != "" && arr[resultant.r1[1]] != "" && arr[resultant.r1[2]] != "") {
winner = arr[resultant.r1[0]];
}
if (arr[resultant.r2[0]] == arr[resultant.r2[1]] && arr[resultant.r2[0]] == arr[resultant.r2[2]] && arr[resultant.r2[0]] != "" && arr[resultant.r2[1]] != "" && arr[resultant.r2[2]] != "") {
winner = arr[resultant.r2[0]];
}
if (arr[resultant.r3[0]] == arr[resultant.r3[1]] && arr[resultant.r3[0]] == arr[resultant.r3[2]] && arr[resultant.r3[0]] != "" && arr[resultant.r3[1]] != "" && arr[resultant.r3[2]] != "") {
winner = arr[resultant.r3[0]];
}
if (arr[resultant.r4[0]] == arr[resultant.r4[1]] && arr[resultant.r4[0]] == arr[resultant.r4[2]] && arr[resultant.r4[0]] != "" && arr[resultant.r4[1]] != "" && arr[resultant.r4[2]] != "") {
winner = arr[resultant.r4[0]];
}
if (arr[resultant.r5[0]] == arr[resultant.r5[1]] && arr[resultant.r5[0]] == arr[resultant.r5[2]] && arr[resultant.r5[0]] != "" && arr[resultant.r5[1]] != "" && arr[resultant.r5[2]] != "") {
winner = arr[resultant.r5[0]];
}
if (arr[resultant.r6[0]] == arr[resultant.r6[1]] && arr[resultant.r6[0]] == arr[resultant.r6[2]] && arr[resultant.r6[0]] != "" && arr[resultant.r6[1]] != "" && arr[resultant.r6[2]] != "") {
winner = arr[resultant.r6[0]];
}
if (arr[resultant.r7[0]] == arr[resultant.r7[1]] && arr[resultant.r7[0]] == arr[resultant.r7[2]] && arr[resultant.r7[0]] != "" && arr[resultant.r7[1]] != "" && arr[resultant.r7[2]] != "") {
winner = arr[resultant.r7[0]];
}
if (arr[resultant.r8[0]] == arr[resultant.r8[1]] && arr[resultant.r8[0]] == arr[resultant.r8[2]] && arr[resultant.r8[0]] != "" && arr[resultant.r8[1]] != "" && arr[resultant.r8[2]] != "") {
winner = arr[resultant.r8[0]];
}
if (winner == "X") {
this.setState({
active: 0,
player: "X",
showWinner: "block"
})
alert("WINNER IS PLAYER 1");
}
if (winner == "O") {
this.setState({
active: 0,
player: "O",
showWinner: "block"
})
alert("WINNER IS PLAYER 2");
}
},
render: function() {
var divVal = "";
var i = 0;
return ( < div >
< div className = "turn_num" > TURN NUMBER: {
this.state.turnNum + 1
} < /div>
<button style={{display:this.state.disppp}}>PLAYER 1 FOR X</button >
< button style = {
{
display: this.state.disppp2
}
} > PLAYER 2 FOR O < /button><br/ > < br / >
< button className = "square"
id = "1"
onMouseUp = {
e => this.handleClick(e, "valvar1")
}
disabled = {
this.state.valvar1
} > {
this.state.valvar1
} < /button>
<button className="square" id="2" onMouseUp={e => this.handleClick(e,"valvar2")} disabled={this.state.valvar2}>{this.state.valvar2}</button >
< button className = "square"
id = "3"
onMouseUp = {
e => this.handleClick(e, "valvar3")
}
disabled = {
this.state.valvar3
} > {
this.state.valvar3
} < /button>
<button className="square clearB" id="4" onMouseUp={e => this.handleClick(e,"valvar4")} disabled={this.state.valvar4}>{this.state.valvar4}</button >
< button className = "square"
id = "5"
onMouseUp = {
e => this.handleClick(e, "valvar5")
}
disabled = {
this.state.valvar5
} > {
this.state.valvar5
} < /button>
<button className="square"id="6" onMouseUp={e => this.handleClick(e,"valvar6")} disabled={this.state.valvar6}>{this.state.valvar6}</button >
< button className = "square clearB"
id = "7"
onMouseUp = {
e => this.handleClick(e, "valvar7")
}
disabled = {
this.state.valvar7
} > {
this.state.valvar7
} < /button>
<button className="square" id="8" onMouseUp={e => this.handleClick(e,"valvar8")} disabled={this.state.valvar8}>{this.state.valvar8}</button >
< button className = "square"
id = "9"
onMouseUp = {
e => this.handleClick(e, "valvar9")
}
disabled = {
this.state.valvar9
} > {
this.state.valvar9
} < /button><br/ > < br / > < br / >
< /div>
<div className="winnerDetail" style={{display:this.state.showWinner}}>WINNER IS : {this.state.player}</div >
);
}
});
ReactDOM.render( < Mycheck / > , document.getElementById("container"));
.square {
height: 50px;
width: 50px;
border: 1px solid black;
background: none;
float: left;
padding: 10px;
text-align: center;
font-size: 25px;
font-weight: bold;
color: #146fbe;
}
.clearB {
clear: both;
}
.winnerDetail {
font-size: 30px;
font-weight: bold;
margin-top: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
The problem is the way you use setState function. The setState() actions are asynchronous and are batched for performance gains. This is explained in the docs:
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
The value of this.state.cnt will hold previous value right after this.setState() call:
handleClick: function(event, key) {
// if this.state.cnt == 0
this.setState({
cnt: this.state.cnt + 1
})
console.log(this.state.cnt); // this.state.cnt is still 0
}
You should rewrite your handleClick to perform some logic and then change state in the end:
handleClick: function(event, key) {
var cnt = this.state.cnt;
cnt++;
var turnNum = this.state.turnNum;
var divId = parseInt(event.target.id);
var valvar = {};
if (this.state.active) {
if (cnt < 9) {
turnNum++;
if (cnt % 2 == 0) {
valvar[key] = "X";
disppp = "none";
disppp2 = "block";
} else {
valvar[key] = "O";
disppp = "block";
disppp2 = "none";
}
} else {
alert("GAME DRAW");
}
}
this.setState({
cnt: cnt,
turnNum: turnNum,
disppp: disppp,
disppp2: disppp2
})
this.Findvalue();
}
Also I noticed that the valvar variable is an array. It should be an object instead.

How to change TextBox input language to Persian as you type in

I am working on a website in which users should fill some fields in different languages.
I don't want the users to change their writing language using Alt+Shift key combination but rather i want the input language to be changed automatically to either Persian or English.
Is there any way to do that?
Use the following script:
if (typeof HTMLElement!="undefined" && ! HTMLElement.prototype.insertAdjacentElement) {
HTMLElement.prototype.insertAdjacentElement = function (where,parsedNode) {
switch (where) {
case 'beforeBegin':
this.parentNode.insertBefore(parsedNode,this)
break;
case 'afterBegin':
this.insertBefore(parsedNode,this.firstChild);
break;
case 'beforeEnd':
this.appendChild(parsedNode);
break;
case 'afterEnd':
if (this.nextSibling)
this.parentNode.insertBefore(parsedNode,this.nextSibling);
else
this.parentNode.appendChild(parsedNode);
break;
}
}
HTMLElement.prototype.insertAdjacentHTML = function (where,htmlStr) {
var r = this.ownerDocument.createRange();
r.setStartBefore(this);
var parsedHTML = r.createContextualFragment(htmlStr);
this.insertAdjacentElement(where,parsedHTML)
}
HTMLElement.prototype.insertAdjacentText = function (where,txtStr) {
var parsedText = document.createTextNode(txtStr)
this.insertAdjacentElement(where,parsedText)
}
}
var FarsiType = {
// Farsi keyboard map based on Iran Popular Keyboard Layout
farsiKey: [
32, 33, 34, 35, 36, 37, 1548, 1711,
41, 40, 215, 43, 1608, 45, 46, 47,
48, 49, 50, 51, 52, 53, 54, 55,
56, 57, 58, 1705, 44, 61, 46, 1567,
64, 1616, 1584, 125, 1609, 1615, 1609, 1604,
1570, 247, 1600, 1548, 47, 8217, 1583, 215,
1563, 1614, 1569, 1613, 1601, 8216, 123, 1611,
1618, 1573, 126, 1580, 1688, 1670, 94, 95,
1662, 1588, 1584, 1586, 1740, 1579, 1576, 1604,
1575, 1607, 1578, 1606, 1605, 1574, 1583, 1582,
1581, 1590, 1602, 1587, 1601, 1593, 1585, 1589,
1591, 1594, 1592, 60, 124, 62, 1617
],
Type: true,
counter: 0,
ShowChangeLangButton: 1, // 0: Hidden / 1: Visible
KeyBoardError: 0, // 0: Disable FarsiType / 1: Show Error
ChangeDir: 2, // 0: No Action / 1: Do Rtl-Ltr / 2: Rtl-Ltr button
UnSupportedAction: 0 //0: Disable FarsiType / 1: Low Support
}
FarsiType.enable_disable = function(Dis) {
var invis, obj;
if (!Dis.checked) {
FarsiType.Type = true;
disable = false;
color = 'darkblue';
} else {
FarsiType.Type = false;
disable = true;
color = '#ECE9D8';
}
if (FarsiType.ShowChangeLangButton == 1) {
for (var i=1; i<= FarsiType.counter; i++) {
obj = document.getElementById('FarsiType_button_' + i);
obj.disabled = disable;
obj.style.backgroundColor = color;
}
}
}
FarsiType.Disable = function() {
FarsiType.Type = false;
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
Dis.checked = true;
}
if (FarsiType.ShowChangeLangButton == 1) {
for (var i=1; i<= FarsiType.counter; i++) {
obj = document.getElementById('FarsiType_button_' + i);
obj.disabled = true;
obj.style.backgroundColor = '#ECE9D8';
}
}
}
FarsiType.init = function() {
var Inputs = document.getElementsByTagName('INPUT');
for (var i=0; i<Inputs.length; i++) {
if (Inputs[i].type.toLowerCase() == 'text' && (Inputs[i].lang.toLowerCase() == 'fa' || Inputs[i].lang.toLowerCase() == 'fa-ir')) {
FarsiType.counter++;
new FarsiType.KeyObject(Inputs[i], FarsiType.counter);
}
}
var Areas = document.getElementsByTagName('TEXTAREA');
for (var i=0; i<Areas.length; i++) {
if (Areas[i].lang.toLowerCase() == 'fa' || Areas[i].lang.toLowerCase() == 'fa-ir') {
FarsiType.counter++;
new FarsiType.KeyObject(Areas[i], FarsiType.counter);
}
}
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
FarsiType.enable_disable (Dis);
Dis.onclick = new Function( "FarsiType.enable_disable (this);" )
}
}
FarsiType.KeyObject = function(z,x) {
GenerateStr = "";
if (FarsiType.ShowChangeLangButton == 1) {
GenerateStr = GenerateStr + "<input type='button' id=FarsiType_button_"+x+" style='border: none; background-color:darkblue; font-size:11; color:white; font-family:tahoma; padding: 1px; margin: 1px; width: auto; height: auto;' value='FA' /> ";
}
if (FarsiType.ChangeDir == 2) {
GenerateStr = GenerateStr + "<input type='button' id=FarsiType_ChangeDir_"+x+" style='border: none; background-color:darkblue; font-size:11; color:white; font-family:tahoma; padding: 1px; margin: 1px; width: auto; height: auto;' value='RTL' />"
}
z.insertAdjacentHTML("afterEnd", GenerateStr);
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm = document.getElementById ('FarsiType_button_' + x);
z.bottelm.title = 'Change lang to english';
}
if (FarsiType.ChangeDir == 2) {
z.Direlm = document.getElementById ('FarsiType_ChangeDir_' + x);
}
z.farsi = true;
z.dir = "rtl";
z.align = "right";
z.style.textAlign = z.align;
z.style.direction = z.dir;
setSelectionRange = function(input, selectionStart, selectionEnd) {
input.focus()
input.setSelectionRange(selectionStart, selectionEnd)
}
ChangeDirection = function() {
if (z.dir == "rtl") {
z.dir = "ltr";
z.align = "left";
z.Direlm.value = "LTR";
z.Direlm.title = "Change direction: Right to Left"
} else {
z.dir = "rtl";
z.align = "right";
z.Direlm.value = "RTL";
z.Direlm.title = "Change direction: Left to Right"
}
z.style.textAlign = z.align;
z.style.direction = z.dir;
z.focus();
}
ChangeLang = function(e, ze) {
if(ze)
z = ze;
if (FarsiType.Type) {
if (z.farsi) {
z.farsi = false;
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm.value = "EN";
z.bottelm.title = 'Change lang to persian';
}
if (FarsiType.ChangeDir == 1) {
z.style.textAlign = "left";
z.style.direction = "ltr";
}
} else {
z.farsi = true;
if (FarsiType.ShowChangeLangButton == 1) {
z.bottelm.value = "FA";
z.bottelm.title = 'Change lang to english';
}
if (FarsiType.ChangeDir == 1) {
z.style.textAlign = "right";
z.style.direction = "rtl";
}
}
z.focus();
}
if (e.preventDefault) e.preventDefault();
e.returnValue = false;
return false;
}
Convert = function(e) {
if (e == null)
e = window.event;
var key = e.which || e.charCode || e.keyCode;
var eElement = e.target || e.originalTarget || e.srcElement;
if (e.ctrlKey && key == 32) {
ChangeLang(e, z);
}
if (FarsiType.Type) {
if (
(e.charCode != null && e.charCode != key) ||
(e.which != null && e.which != key) ||
(e.ctrlKey || e.altKey || e.metaKey) ||
(key == 13 || key == 27 || key == 8)
) return true;
//check windows lang
if (key > 128) {
if (FarsiType.KeyBoardError == 0) {
FarsiType.Disable();
} else {
alert("Please change your windows language to English");
return false;
}
}
// If Farsi
if (FarsiType.Type && z.farsi) {
//check CpasLock
if ((key >= 65 && key <= 90&& !e.shiftKey) || (key >= 97 && key <= 122 ) && e.shiftKey) {
alert("Caps Lock is On. To prevent entering farsi incorrectly, you should press Caps Lock to turn it off.");
return false;
}
// Shift-space -> ZWNJ
if (key == 32 && e.shiftKey)
key = 8204;
else
key = FarsiType.farsiKey[key-32];
key = typeof key == 'string' ? key : String.fromCharCode(key);
// to farsi
try {
var docSelection = document.selection;
var selectionStart = eElement.selectionStart;
var selectionEnd = eElement.selectionEnd;
if (typeof selectionStart == 'number') {
//FOR W3C STANDARD BROWSERS
var nScrollTop = eElement.scrollTop;
var nScrollLeft = eElement.scrollLeft;
var nScrollWidth = eElement.scrollWidth;
eElement.value = eElement.value.substring(0, selectionStart) + key + eElement.value.substring(selectionEnd);
setSelectionRange(eElement, selectionStart + key.length, selectionStart + key.length);
var nW = eElement.scrollWidth - nScrollWidth;
if (eElement.scrollTop == 0) { eElement.scrollTop = nScrollTop }
} else if (docSelection) {
var nRange = docSelection.createRange();
nRange.text = key;
nRange.setEndPoint('StartToEnd', nRange);
nRange.select();
}
} catch(error) {
try {
// IE
e.keyCode = key
} catch(error) {
try {
// OLD GECKO
e.initKeyEvent("keypress", true, true, document.defaultView, false, false, true, false, 0, key, eElement);
} catch(error) {
//OTHERWISE
if (FarsiType.UnSupportedAction == 0) {
alert('Sorry! no FarsiType support')
FarsiType.Disable();
var Dis = document.getElementById('disableFarsiType')
if (Dis != null) {
Dis.disabled = true;
}
return false;
} else {
eElement.value += key;
}
}
}
}
if (e.preventDefault)
e.preventDefault();
e.returnValue = false;
}
}
return true;
}
if (FarsiType.ShowChangeLangButton == 1) { z.bottelm.onmouseup = ChangeLang; }
if (FarsiType.ChangeDir == 2) { z.Direlm.onmouseup = ChangeDirection; }
z.onkeypress = Convert;
}
if (window.attachEvent) {
window.attachEvent('onload', FarsiType.init)
} else if (window.addEventListener) {
window.addEventListener('load', FarsiType.init, false)
}
Now all you have to do is to create a text box and set its Lang attribute to "fa-IR".
<input type="textbox" name="text1" Lang="fa-IR" />
or
<asp:TextBox ID="txt_name" runat="Server" Lang="fa-IR" />
Load your page and it's done!

Categories

Resources