Reputation: 603
if you click any of 3 radio button in any time it will count the number of clicked if the number of clicked is greater than 3 in console it give message you win or else you lose ,but its not working
import React, { useState } from 'react';
export default function App() {
const [disable, setDisable] = useState(false);
const check = ({target}) => {
if (target.id==='one') {
setDisable(true);
}
else {
setDisable(false);
}
}
const handlechange=(e)=>{
let c=e.target.value;
if(c.length>3)
console.log('win')
else
console.log('lose')
}
return (
<>
<input type="radio" onChange={(e) => {check(e);handlechange(e)}} disabled={disable} name="one" />
<input type="radio" onChange={(e) => {check(e);handlechange(e)}} disabled={disable} name="one" />
<input type="radio" onChange={(e) => {check(e);handlechange(e)}} disabled={disable} name="one" id="one"/>
</>
);
}
Upvotes: 2
Views: 393
Reputation: 530
Here is the solution to your problem, Create a clickCount
state and update it on radio button change.
import React, { useState } from "react";
export default function App() {
const [disable, setDisable] = useState(false);
const [clickCount, setClickCount] = useState(1);
const handlechange = (e) => {
setClickCount(clickCount + 1);
if (clickCount > 3) {
console.log("win");
setDisable(true);
} else {
console.log("lose");
}
};
return (
<>
<input
type="radio"
onChange={handlechange}
disabled={disable}
name="one"
/>
<input
type="radio"
onChange={handlechange}
disabled={disable}
name="one"
/>
<input
type="radio"
onChange={handlechange}
disabled={disable}
name="one"
/>
</>
);
}
Sandbox link.
Upvotes: 2
Reputation: 208
Let the handlechange function know exactly whice input was checked: Please try this:
const handlechange=(e, number)=>{
if(number>=3)
console.log('win')
else
console.log('lose')
}
return (
<>
<input type="radio" onChange={(e) => {check(e, 1);handlechange(e, 1)}} disabled={disable} name="one" />
<input type="radio" onChange={(e) => {check(e, 2);handlechange(e, 2)}} disabled={disable} name="one" />
<input type="radio" onChange={(e) => {check(e, 3);handlechange(e, 3)}} disabled={disable} name="one" id="one"/>
</>
);
Upvotes: 2