Reactjs input keeps another input's value on toggle - javascript

I have two inputs, first phone second code and you can toggle between those. if you click on toggle button it works good, but there is problem, if you type something in first input, this value show on second input too! any idea how to fix this??
function Example() {
const [confirm, setConfirm] = useState(false);
return (
<div>
{!confirm ? <input placeholder="phone" type="number" name="phone"/>
:
<input placeholder="code" type="number" name="confirm"/>}
<button onClick={() => setConfirm(!confirm)}>
Click me
</button>
</div>
);
}
Demo

You need to set key for each input. to make the inputs totally replaced.
function Example() {
const [confirm, setConfirm] = useState(false);
return (
<div>
{!confirm ? <input key="1" placeholder="phone" type="number" name="phone"/>
:
<input key="2" placeholder="code" type="number" name="confirm"/>}
<button onClick={() => setConfirm(!confirm)}>
Click me
</button>
</div>
);
}

Related

How to validate and get data of a radio button with input box in reactjs?

I am new to react. I have got a scenario where I have multiple radio button and few of the radio buttons have an input box associated with it. Like in the below image:
What I want is:
If the user checked any radio button which has an input box
associated with it, then that input box will become required field.
(display validation message "input is required" on button click.
otherwise display data on the console).
If everything is okay then On click of save button show data on the
console.
I have written some code. This code validates if none of the radio button is checked on button click (obvious case). But I am not understanding how to achieve the above requirement.
import React from "react";
const ContactUsForm = () => {
const isFormValid = () => {
var radios = document.getElementsByName("myRadio");
var isValid = false;
var i = 0;
while (!isValid && i < radios.length) {
if (radios[i].checked) isValid = true;
i++;
}
return isValid;
};
const handleButtonClick = () => {
if (!isFormValid()) {
alert("Select atleast one radio button");
} else {
alert("Success");
}
};
return (
<div>
{" "}
<br />
<label>
<input type="radio" name="myRadio" value="Graduate" /> I am graduate
</label>{" "}
<br />
<label>
<input type="radio" name="myRadio" value="Something" /> Some radio button
</label>{" "}
<br />
<label>
<input type="radio" name="myRadio" />I am graduate from university name
</label>{" "}
<input type="text" id="other" />
<br />
<label>
<input type="radio" name="myRadio" />
Other
</label>
<input type="text" id="other2" />
<br />
<button onClick={handleButtonClick} type="submit">
Save
</button>{" "}
<br />
</div>
);
};
export default ContactUsForm;
Can anybody help me in achieving the above requirement in react? Thank You
So you should use React State hook.
For every input, you need to add onClick event.
Declare state:
const [radioBtn, setRadioBtn] = useState(null);
Change state for each button click:
<input type="radio" name="myRadio" value="Graduate" onClick={() => setRadioBtn('Graduate')}/> I am graduate
In the end, all you need to do is to click Save and you can manage all the stuff you need in handleButtonClick
<button onClick={handleButtonClick} type="submit">
Save
</button>
Here you can validate all you need. Instead of alert you can use console.log(radioBtn) so you would get output to console.
const handleButtonClick = () => {
if (radioBtn) {
alert(radioBtn);
} else {
alert(radioBtn + ' fail');
}
}

My function doesn't display the alert (preventDefault)

I am working on a to-do list app (React.js) and trying to make use of the preventDefault function. I've added an onSubmit attribute to my form element and want it to display an alert when the add button is clicked. Problem is it doesn't seem to work, here's my code
function Form (props) {
function handleSubmit(e) {
e.preventDefault();
alert('Added')
}
return (
<form onSubmit={handleSubmit}>
<h2 className="label-wrapper">
<label htmlFor="new-todo-input" className="label-lg">
What needs to be done?
</label>
</h2>
<input
type="text"
id="new-todo-input"
className="input input-lg"
name="text"
autoComplete="off"
></input>
<button type="submit" className="btn btn-primary btn__lg">
Add
</button>
</form>
)
}
export default Form;

How do I enable/disable an input textbox when a checkbox is checked?

I mapped a list of dependents which was fetched from an API. Each dependent has a corresponding checkbox and input box.
const [depInput, setDepInput]= useState({disable:"true", checked:"false"});
<div>
{items.dependents?.map((item, key) => {
return (
<p key={key}> Name: {item.name} </p>
<div>
<input
type="checkbox"
value={!depInput.checked}
onChange={() => setDepInput(!depInput.disable)}
disable={!depInput.disable} />
</div>
<div>
<input type="text"
placeholder="Enter correct detail"
disabled={!depInput.disable}
onChange={() => setDepInput(!depInput.checked)} />
</div>
<div>
<select defaultValue={item.type_of_dependent}>
<option>Primary</option>
<option>Secondary</option>
<option> NA</option>
</select>
</div>
</>
);
})}
</div>
When I click the checkbox of the first dependent, it disables the other input textboxes. I intend to have each checkbox and corresponding input text box have a toggle state.
I have added a demo for you it should help you out. What you need is separate state for each checkbox. I have added comments let me know if this helps you
https://codesandbox.io/s/elegant-northcutt-growt?file=/src/App.js

How do i get the value of the checked radio button on react,js

I am making an organized todo list and i would love to have it that if i select any of the radio buttons i can put the input in either of the three options array (array not added in code, in a parent component).
I need a function which can tell me which radio button is checked and how to get the id or value of the checked.
const AddTodo = ({ submit, textColor }) => {
return (
<div className="displayFlex justCenter">
<form onSubmit={submit}>
<div>
<input
type="text"
name="newTask"
id="inp"
placeholder="Enter New Task..."
/>
<input
style={{ color: textColor }}
className="btn"
type="submit"
value="Add Task"
/>
</div>
<div>
<span>
<input type="radio" id="todo" name="radioButton" value="toDo" />
<label>To do</label>
</span>
<span>
<input
type="radio"
id="progress"
name="radioButton"
value="inProgress"
/>
<label>In Progress</label>
</span>
<span>
<input type="radio" id="done" name="radioButton" value="done" />
<label>Done</label>
</span>
</div>
</form>
</div>
);
};
export default AddTodo;
Inside your submit function, or another function which you call inside submit, you can get the value of checked radio button.
function submit(event) {
[].forEach.call(event.target.elements, function(ele) {
if (ele.checked) {
console.log(ele.value); // get the checked radio button's value
}
});
event.preventDefault();
}
Here is a working stackblitz url

How to disable a checkbox after executing onChange method?

I want to be able to disable a checkbox once I check on the checkbox and execute the onChange method.
I was able to find a way to do this, but once multiple items are checked only the recently checked checkbox is disabled.
The disable method is inside a component class before the render method
Disable = id => {
document.getElementById(id).disabled = true;
//another method to execute onchange
};
<span>
<input
type="checkbox"
className="form-check-input"
onChange={this.Disable}
value=""
/>
</span>;
The checkbox is inside the render method.
One the user checks the checkbox the checkbox needs to check and disable it self
Some notice points:
use camelCase for function name
use props value to make the checkbox fully controlled
use props disabled to disable input element
set the related state inside the handler function
no need for document.getElementById in your current situation
handler event is not id, if you just need id, pass it as a param this.handler(id)
Demo:
const App = () => {
const [checked, setChecked] = React.useState(false);
const [status, setStatus] = React.useState(true);
const onChangeHandler = () => {
setChecked(!checked);
setStatus(false);
};
return (
<div className="App">
<input
type="checkbox"
value={checked}
disabled={!status}
onChange={onChangeHandler}
/>
</div>
);
};
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
you should have to attach id on element .
let Disable=(id)=>{
if(id){
document.getElementById(id).disabled = true
}
}
<span>
<input type="checkbox" className="form-check-input" onChange="Disable(this.id)" id="one" value=""/>
<input type="checkbox" className="form-check-input" onChange="Disable(this.id)" id="two" value=""/>
<input type="checkbox" className="form-check-input" onChange="Disable(this.id)" id="three" value=""/>
</span>
passing the event in an anonymous arrow function and accepting it as an argument in the eventHandler(component method) and using the event.target there is the appropriate way of doing this in such situations that you need to access the caller.
class Stack extends Component {
Disable = event => {
event.target.disabled = true;
//another method to execute onChange
};
render() {
return (
<span>
<input
type="checkbox"
className="form-check-input"
onChange={event => this.Disable(event)}
value=""
/>
<input
type="checkbox"
className="form-check-input"
onChange={event => this.Disable(event)}
value=""
/>
<input
type="checkbox"
className="form-check-input"
onChange={event => this.Disable(event)}
value=""
/>
</span>
);
}
}

Categories

Resources