radio input still true after unchecked - reactjs

I have filter section with checkbox and radio when user unchecked for checkbox the content is hidding, but for radio I can't hidden the content he still true.
Any help please
const inputChecked = (e) => {
const updatedList = [...checked];
if (e.target.checked) {
updatedList = [...checked, e.target.value];
}
else {
updatedList.splice(checked.indexOf(e.target.value),1)
}
setChecked(updatedList);
};
return (
<form>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='radio' id="most_recent" name="sort_by" value='Most recent' />
<label htmlFor='most_recent'>Most recent</label>
</div>
<div className='flex items-center'>
<input type='radio' id="most_relevent" name="sort_by" value='Most relevent' />
<label htmlFor='most_relevent'>Most relevent</label>
</div>
</div>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='checkbox' id="intership" name="intership" value='intership' />
<label htmlFor='intership'>intership</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Director" name="director" value='Director' />
<label htmlFor='Director'>Director</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Associate" name="associate" value='Associate' />
<label htmlFor='Associate'>Associate</label>
</div>
</div>
</form>
)

Separate into two types of handle: handle for radio checked and handle for checkbox checked.
Have to put onChange into each radio input <input type="radio" onChange={}... />. Try this below code:
const [prevRadio, setPrevRadio] = useState("")
const radioChecked = (e) => {
setPrevRadio(e.target.value)
let updatedList = [...checked, e.target.value];
updatedList.splice((prevRadio ? checked.indexOf(prevRadio) : (checked.length + 99)),1)
setChecked(updatedList)
}
const inputChecked = (e) => {
let updatedList = [...checked];
if (e.target.checked) {
updatedList = [...checked, e.target.value];
}
else {
updatedList.splice(checked.indexOf(e.target.value),1)
}
setChecked(updatedList);
};
return (
<form>
<div>
<div className='flex items-center'>
<input type='radio' id="most_recent" name="sort_by" value='Most recent'
onChange={inputChecked}/> //<== Put onChange in here
<label htmlFor='most_recent'>Most recent</label>
</div>
<div className='flex items-center'>
<input type='radio' id="most_relevent" name="sort_by" value='Most relevent'
onChange={inputChecked}/> //<== Put onChange in here
<label htmlFor='most_relevent'>Most relevent</label>
</div>
</div>
<div onChange={inputChecked}>
<div className='flex items-center'>
<input type='checkbox' id="intership" name="intership" value='intership' />
<label htmlFor='intership'>intership</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Director" name="director" value='Director' />
<label htmlFor='Director'>Director</label>
</div>
<div className='flex items-center'>
<input type='checkbox' id="Associate" name="associate" value='Associate' />
<label htmlFor='Associate'>Associate</label>
</div>
</div>
</form>
)

Related

How calculate the marks using switch in react?

I created the few questions page I want calculate marks when click the submit button but when I click submit button marks didn't show.
This my code code . In this code I get the values from the checkbox and input to switch case and calculate the marks but marks doesn't show and not redirect to '/questions/markspage/${marks}' this page.
code
function InAnswers() {
const history = useHistory();
const [answers, setAnswers] = useState('');
const [question, setQuestion] = useState('');
const [dayWord, setDayWord] = useState(''); //1
const [seeObject, setSeeObject] = useState(''); //2
const [identifyObject, setIdentifyObject] = useState(''); //3
const [identifyColor, setIdentifyColor] = useState(''); //4
const [firstWord, setFirstWord] = useState(''); //5
const [marks, setMarks] = useState(''); //5
async function submitMarks(event) {
event.preventDefault();
var marks = 0;
switch (marks) {
case 'wordday' == 'wordmore5':
setMarks(marks + 10);
return setMarks;
break;
case 'see' == 'yessee ':
setMarks(marks + 10);
return setMarks;
break;
case 'identify' == 'yesidentify':
setMarks(marks + 10);
return setMarks;
break;
case 'colors' == 'colorsyes ':
setMarks(marks + 10);
return setMarks;
break;
case 'firstword' == 'firstword18 ':
setMarks(marks + 10);
return setMarks;
break;
default:
setMarks(marks + 10);
return setMarks;
history.push(`/questions/markspage/${marks}`);
}
}
// // calculate marks
return (
<div className='container'>
<div className='row'>
<div className='col-4'>
<div className='pb-2 px-3 d-flex flex-wrap align-items-center justify-content-between'>
<h2>Questions </h2>
</div>
</div>
<div className='col-3'></div>
</div>
{/* </div> */}
<div className='row'>
<h4 className='mb-4'> Questions </h4>
<form onSubmit={submitMarks}>
<div>
<div className='progressCard'>
<div className='p-3'>
<h2>1. how many words child talk in a day?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordless5'
value='wordless5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordless5'>
less 5
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='wordday'
id='wordmore5'
value='wordmore5'
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='wordmore5'>
more than 5
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>
2. when you show some thing to child then is child watch
there?
</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='nosee'
value='nosee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='see'
id='yessee'
value='yessee'
required
onChange={(e) => setSeeObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>3.When you show some thing then is child identify that </h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='noidentify'
value='noidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='identify'
id='yesidentify'
value='yesidentify'
required
onChange={(e) => setIdentifyObject(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>4. child can identify more than 5 colors</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsno'
value='colorsno'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='PUBLISH'>
no
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='colors'
id='colorsyes'
value='colorsyes'
required
onChange={(e) => setDayWord(e.target.value)}
/>
<label className='form-check-label' for='UNPUBLISH'>
yes
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
<br></br>
<div className='progressCard'>
<div className='p-3'>
<h2>5.The first word child told?</h2>
<div align='right'>
<span>
<div className='col-md-8 mb-4'>
<div className='form-name'>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword19'
value='firstword19'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword19'>
after 18 months
</label>
</div>
<div className='form-check form-check-inline'>
<input
className='form-check-input'
type='radio'
name='firstword'
id='firstword18'
value='firstword18'
required
onChange={(e) => setFirstWord(e.target.value)}
/>
<label className='form-check-label' for='firstword18'>
before 18 months
</label>
</div>
</div>
</div>
</span>
</div>
</div>
</div>
</div>
</form>
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</div>
</div>
);
}
export default InAnswers;
You should define the submit input inside the <form> tag:
<form onSubmit={submitMarks}>
...
<div className='col-xl-6 mb-4'></div>
<div>
<input
type='submit'
value='SUBMIT ANSWERS '
className='form-submit-btn'
/>
</div>
</form>
If you need to calculate the total for marks given the responses you should rewrite the submitMarks function as:
function submitMarks(event) {
event.preventDefault();
var marks = 0;
if (dayWord === 'wordmore5') marks += 10;
if (seeObject === 'yessee') marks += 10;
if (identifyObject === 'yesidentify') marks += 10;
if (identifyColor === 'colorsyes') marks += 10;
if (firstWord === 'firstword18') marks += 10;
history.push(`/questions/markspage/${marks}`);
}
No need to declare it async nor declare a separate marks state variable.

state is not updating in react form validation

I am working with simple form validation in react. The problem here is error message is not displaying in while it is showing in console.log! I am quite new to react and stucked here for quite some time. How can I solve this?
I've seen many youtube videos but nothing is working properly.
const [logindata, setLogindata] = useState({
customeremail: '',
customerpass: ''
})
const [err, seterr] = useState({
Email: '',
Passwordnew: ''
});
const handlechange = event => {
const val = event.target.value
const name = event.target.name
setLogindata({ ...logindata, [name]: val })
console.log(val)
}
function login() {
const NewErr = {...err};
if (logindata.customeremail == "") {
NewErr.Email = "Email should not be empty";
alert(NewErr.Email)
console.log(NewErr)
}
}
return (
<>
<div className="container">
<div className="row">
<div className="col-12 col-sm-12 col-md-6 col-lg-6 main-col offset-md-3">
<div className="mb-4">
<form method="post" action="home" id="CustomerLoginForm" acceptCharset="UTF-8" className="contact-form">
<div className="row">
<div className="col-12 col-sm-12 col-md-12 col-lg-12">
<div className="form-group">
<label htmlFor="CustomerEmail">Email</label>
<input type="email" name="customeremail" placeholder="" id="CustomerEmail" className="" autoCorrect="off" autoCapitalize="off" autoFocus="" onChange={handlechange} value={logindata.customeremail} required = {true} />
</div>
<div className="alert alert-danger" role="alert">
{seterr.Email}
</div>
</div>
<div className="col-12 col-sm-12 col-md-12 col-lg-12">
<div className="form-group">
<label htmlFor="CustomerPassword">Password</label>
<input type="password" name="customerpass" placeholder="" id="CustomerPassword" className="" onChange={handlechange} value={logindata.customerpass} />
</div>
</div>
</div>
<div className="row">
<div className="text-center col-12 col-sm-12 col-md-12 col-lg-12">
<input type="button" style={{ backgroundColor: '#000', color: '#fff' }} className="btn mb-3" value="Sign In" onClick={login} />
<p className="mb-4">
Forgot your password? |
Create account
</p>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</>
There are 2 problem in your code
1. Not setting state
You are not setting state for err using seterr as:
if (logindata.customeremail == '') {
NewErr.Email = 'Email should not be empty';
alert(NewErr.Email);
console.log(NewErr);
seterr(NewErr); // MISSING
}
CODESANDBOX LINK
2. Showing error message with wrong way
When you use useState then it will give you an array of value and function through which you can update the value and on change of the value it will re-render it. You have to use err obj not the function seterr.
You should use {err.Email}} instead of {seterr.Email}}
<div className='alert alert-danger' role='alert'>
{/* {seterr.Email} */}
{err.Email}
</div>;

Unsuccessful Rerender of Nested Component with JEST/Enzyme React Testing

I have a Parent component, App, and a nested component, SearchByForm. SearchByForm contains a radio buttons' group and I am attempting to modifying the third button's value to become checked (true). It can be identified by its className, .workstationRadioBtn.
SearchByForm Class
import React from 'react';
class SearchByForm extends React.Component {
constructor(props) {
super(props);
this.state = { which: 'order' };
}
buttonChange = (e) => {
if (e.target.checked) {
this.setState({ which: e.target.value });
this.props.updateFromSearchByForm(e.target.value);
}
}
render() {
return (
<form className="SearchByForm">
<div className="form-check">
<label>
<input
type="radio"
name="searchBy"
value="order"
checked={this.state.which === 'order'}
onChange={this.buttonChange}
className="orderRadioBtn"
/>
Order
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="searchBy"
value="employee"
checked={this.state.which === 'employee'}
onChange={this.buttonChange}
className="employeeRadioBtn"
/>
Employee
</label>
</div>
<div className="form-check">
<label>
<input
type="radio"
name="searchBy"
value="workstation"
checked={this.state.which === 'workstation'}
onChange={this.buttonChange}
className="workstationRadioBtn"
/>
Work Station
</label>
</div>
</form>
);
}
}
export default SearchByForm;
Search Component class:
class Search extends React.Component {
constructor(props) {
super(props);
this.state = { searchKey: '_id', searchBy: 'order', searchResults: null };
this.updateFromSearchByForm = this.updateFromSearchByForm.bind(this);
this.updateFromKeysForm = this.updateFromKeysForm.bind(this);
this.clearSearchResults = this.clearSearchResults.bind(this);
this.populateSearchResults = this.populateSearchResults.bind(this);
}
updateFromSearchByForm(value) {
this.setState({ searchBy: value });
}
updateFromKeysForm(value) {
this.setState({ searchKey: value });
}
keyToSearchBy = () => {
switch (this.state.searchBy) {
case 'order':
return (
<KeysForm which='order' updateFromKeysForm={this.updateFromKeysForm}></KeysForm>
);
case 'employee':
return (
<KeysForm which='employee' updateFromKeysForm={this.updateFromKeysForm}></KeysForm>
);
case 'workstation':
return (
<KeysForm which='workstation' updateFromKeysForm={this.updateFromKeysForm}></KeysForm>
);
default:
return (
<KeysForm which='order' updateFromKeysForm={this.updateFromKeysForm}></KeysForm>
);
}
}
clearSearchResults = () => {
this.setState({ searchResults: null });
}
populateSearchResults = (results) => {
this.setState({ searchResults: results });
}
displayOrderResults = () => {
let list = [];
let count = 0;
list.push(<label> Orders found that match your search criteria:</label>)
for (let result of this.state.searchResults) {
list.push(
<ListGroupItem key={count}>ID: {result._id}, OrderID: {result.OrderID}, CustomerID: {result.CustomerID}, DateRequired: {result.DateRequired}, Status: {result.Status}, PriorityFlag: {result.PriorityFlag}</ListGroupItem>
)
count++;
}
return list;
}
displayEmployeeResults = () => {
let list = [];
let count = 0;
list.push(<label> Employees found that match your search criteria:</label>)
for (let result of this.state.searchResults) {
list.push(
<ListGroupItem key={count}>ID: {result._id}, Staff Name: {result.WorkerName}</ListGroupItem>
)
count++;
}
return list;
}
displayWorkStationResults = () => {
let list = [];
let count = 0;
list.push(<label> Stations found that match your search criteria:</label>)
for (let result of this.state.searchResults) {
list.push(
<ListGroupItem key={count}>ID: {result._id}, Work Station Name: {result.StationName}</ListGroupItem>
)
count++;
}
return list;
}
showSearchResults = () => {
//Know how to display based on searchBy type.
switch (this.state.searchBy) {
case 'order':
return (this.displayOrderResults());
case 'employee':
return (this.displayEmployeeResults());
case 'workstation':
return (this.displayWorkStationResults());
default:
break;
}
for (let result of this.state.searchResults) {
console.log(result);
}
}
render() {
return (
<Jumbotron>
<div className="App">
<div className='header'>
<div className='header-space1'>
<div className='button-header'>
<Link to='/menu'>
<Button id='menu'>Back to Menu</Button>
</Link>
</div>
</div>
<div className='header-space2'>
<h2>Search</h2>
</div>
<div className='header-space3'>
<div className='button-header'>
</div>
</div>
</div>
<div className='Search'>
<div className='Row'>
<div className='SearchForm'>
<p>What would you like to search by?</p>
<SearchByForm updateFromSearchByForm={this.updateFromSearchByForm}></SearchByForm>
{this.keyToSearchBy()}
</div>
</div>
<ValueForm searchKey={this.state.searchKey} searchBy={this.state.searchBy} clearSearchResults={this.clearSearchResults} populateSearchResults={this.populateSearchResults}></ValueForm>
<br></br>
<div className='Row'>
<div className='SearchResults'>
<p>Search Results</p>
{this.state.searchResults ?
<ListGroup>
{this.showSearchResults()}
</ListGroup>
:
null}
</div>
</div>
</div>
</div>
</Jumbotron>
);
}
}
The test currently creates a full tree copy and successfully checks the .workstationRadioBtn's checked value to true. It also successfully changes the 'which' state field of SearchByForm to 'workstation'.
My test's current state is as follows
describe('Work Station Search', () => {
it(' successfully selects order radio button', () => {
const wrapper = mount(
<Router>
<Search />
</Router>
);
console.log(wrapper.debug());
const wrapperSearchByForm = wrapper.find(SearchByForm);
wrapperSearchByForm.find('input').filter('.workstationRadioBtn').simulate('change', {target: {checked: true}});
wrapperSearchByForm.setState({ which: 'workstation' });
wrapper.update();
console.log(wrapper.debug());
})
});
The debug code of the test shows the above to be true, however the update() doesn't appear to have successfully rerendered the second nested component, KeysForm, whose returned render is dependent upon the SearchByForm. It is still acting as though the Order radio button is checked.
Here is the test's full debug output:
console.log src/__tests__/Search/Search.test.js:84
<BrowserRouter>
<Router history={{...}}>
<Search>
<Jumbotron fluid={false}>
<div className="jumbotron">
<div className="App">
<div className="header">
<div className="header-space1">
<div className="button-header">
<Link to="/menu">
<LinkAnchor href="/menu" navigate={[Function: navigate]}>
<a href="/menu" onClick={[Function: onClick]}>
<Button id="menu" variant="primary" active={false} disabled={false} type="button">
<button id="menu" disabled={false} type="button" className="btn btn-primary">
Back to Menu
</button>
</Button>
</a>
</LinkAnchor>
</Link>
</div>
</div>
<div className="header-space2">
<h2>
Search
</h2>
</div>
<div className="header-space3">
<div className="button-header" />
</div>
</div>
<div className="Search">
<div className="Row">
<div className="SearchForm">
<p>
What would you like to search by?
</p>
<SearchByForm updateFromSearchByForm={[Function: bound updateFromSearchByForm]}>
<form className="SearchByForm">
<div className="form-check">
<label>
<input type="radio" name="searchBy" value="order" checked={true} onChange={[Function]} className="orderRadioBtn" />
Order
</label>
</div>
<div className="form-check">
<label>
<input type="radio" name="searchBy" value="employee" checked={false} onChange={[Function]} className="employeeRadioBtn" />
Employee
</label>
</div>
<div className="form-check">
<label>
<input type="radio" name="searchBy" value="workstation" checked={false} onChange={[Function]} className="workstationRadioBtn" />
Work Station
</label>
</div>
</form>
</SearchByForm>
<KeysForm which="order" updateFromKeysForm={[Function: bound updateFromKeysForm]}>
<div className="KeysForm">
<div className="OrderKeys">
<p>
Which Order Key would you like to search by?
</p>
<form>
<div className="form-check">
<label>
<input type="radio" name="orderKey" value="_id" checked={true} onChange={[Function]} className="form-check-input" />
Id
</label>
</div>
<div className="form-check">
<label>
<input type="radio" name="orderKey" value="DateRequired" checked={false} onChange={[Function]} className="form-check-input" />
Date Required
</label>
</div>
<div className="form-check">
<label>
<input type="radio" name="orderKey" value="Status" checked={false} onChange={[Function]} className="form-check-input" />
Status
</label>
</div>
<div className="form-check">
<label>
<input type="radio" name="orderKey" value="PriorityFlag" checked={false} onChange={[Function]} className="form-check-input" />
Priority Flag
</label>
</div>
</form>
</div>
</div>
</KeysForm>
</div>
</div>
<ValueForm searchKey="_id" searchBy="order" clearSearchResults={[Function: bound ]} populateSearchResults={[Function: bound ]}>
<form className="ValueForm">
<label>
<input type="text" name="value" value="" onChange={[Function]} />
</label>
<Button onClick={[Function]} variant="primary" active={false} disabled={false} type="button">
<button onClick={[Function]} disabled={false} type="button" className="btn btn-primary">
Search
</button>
</Button>
</form>
</ValueForm>
<br />
<div className="Row">
<div className="SearchResults">
<p>
Search Results
</p>
</div>
</div>
</div>
</div>
</div>
</Jumbotron>
</Search>
</Router>
</BrowserRouter>

How to add multiple checkboxes to a state

How to save multiple checkboxes to a single state and add each checkbox to its previous state?
These are my states:
Operators : '',
TypeStatus : '',
RegistrationStatus : '',
This is my function:
changeHandle = (event) => {
this.setState({
[event.target.name]: event.target.value
});
};
This is my input:
I want to click on each of these checkboxes to add the value to the state
and add the RegisterButtonsActivated class to its parent label
<div className="container-fluid">
<div className="row flex-row-reverse">
<div className="col" data-toggle="buttons">
<label className="RegisterButtons">
<input
type="checkbox"
name="Operators"
id="MCI"
value="MCI"
checked={this.state.operations}
onChange={this.changeHandle}
onClick={this.props.handleFilterOperatorMCI}
/>
همراه اول
</label>
</div>
<div className="col" data-toggle="buttons">
<label className="RegisterButtons">
<input
type="checkbox"
name="Operators"
id="irancell"
value="irancell"
checked={true}
onChange={this.changeHandle}
onClick={this.props.handleFilterOperatorIrancell}
/>
ایرانسل
</label>
</div>
<div className="col" data-toggle="buttons">
<label className="RegisterButtons">
<input
type="checkbox"
name="Operators"
id="rightel"
value="rightel"
checked={this.state.operations}
onChange={this.changeHandle}
onClick={this.handleFilterOperatorRightel}
/>
رایتل
</label>
</div>
</div>
<div className="row justify-content-center">
<div className="col">
<hr className="hr-Filterbox" />
</div>
</div>
<div className="row flex-row-reverse">
<div className="col">
<label className={`RegisterButtons ${this.state.TypeStatus ===
"Justice" ? 'RegisterButtonsActivated' : ''}`}>
<input
type="checkbox"
name="TypeStatus"
id="Justice"
value="Justice"
onChange={this.changeHandle}
onClick={this.props.handleFilterTypeJustice}
/>
دائمی
</label>
</div>
<div className="col">
<label className={`RegisterButtons ${this.state.TypeStatus ===
"Credit" ? 'RegisterButtonsActivated' : ''}`}>
<input
type="checkbox"
name="TypeStatus"
id="Credit"
value="Credit"
onChange={this.changeHandle}
onClick={this.props.handleFilterTypeCredit}
/>
اعتباری
</label>
</div>
</div>
<div className="row justify-content-center">
<div className="col">
<hr className="hr-Filterbox" />
</div>
</div>
<div className="row flex-row-reverse">
<div className="col" data-toggle="buttons">
<label className={`RegisterButtons ${this.state.OperatingStatus
=== "New" ? 'RegisterButtonsActivated' : ''}`}>
<input
type="checkbox"
name="OperatingStatus"
id="New"
value="New"
onChange={this.changeHandle}
onClick={this.props.handleFilterWorkStatusNew}
/>
صفر
</label>
</div>
<div className="col" data-toggle="buttons">
<label className={`RegisterButtons ${this.state.OperatingStatus
=== "LowPerformance" ? 'RegisterButtonsActivated' : ''}`}>
<input
type="checkbox"
name="OperatingStatus"
id="LowPerformance"
value="LowPerformance"
onChange={this.changeHandle}
onClick={this.props.handleFilterWorkStatusOld}
/>
کم کارکرد
</label>
</div>
<div className="col" data-toggle="buttons">
<label className={`RegisterButtons ${this.state.OperatingStatus
=== "Old" ? 'RegisterButtonsActivated' : ''}`}>
<input
type="checkbox"
name="OperatingStatus"
id="Old"
value="Old"
onChange={this.changeHandle}
onClick={this.props.handleFilterWorkStatusLowPerformance}
/>
کارکرده
</label>
</div>
</div>
</div>
I want to click on each of these checkboxes to add the value to the state and add the RegisterButtonsActivated class to its parent label
You can do like this.....
this.state = {
checkboxes: {
Operators: null,
TypeStatus: null,
RegistrationStatus: null,
}
}
Below will handle the change in existing state and if you will pass new checkbox it will add new key to the state object.
changeHandle = (event) => {
this.setState((prevState) => ({
checkboxes: {...prevState.checkboxes, [event.target.name]: event.target.value }
}))
};
You can do this with your state;
this.state = {
checkboxes: {
Operators: {
currentValue: null,
previousValues:[]
},
TypeStatus: {
currentValue: null,
previousValues:[]
},
RegistrationStatus: {
currentValue: null,
previousValues:[]
},
}
}
Now your handler will look something like this;
changeHandle = (event) => {
const checkboxes = this.state.checkboxes;
checkboxes[event.target.name].currentValue = event.target.value;
checkboxes[event.target.name].previousValues.push(event.target.value); // last element will be the latest value.
this.setState({
checkboxes
});
};

Showing input value in the url link (ReactJs Laravel)

I created laravel project with the reactjs framework and I'm new for this framework. I have problem and why It happens every time i submit the form.
Goal: users can register through online
Problem:
Why it happens when i submit the button the input value of user shown in the url link?
The data that I input is not inserted to the database.
Code:
constructor() {
super();
this.state = {
f_name:'',
l_name:'',
m_name:'',
email:'',
home_num:'',
contact_num:'',
Job_name:[],
employ_status:'',
employ_relocate:'',
employ_start_date:'',
employ_file:''
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handle_fname = this.handle_fname.bind(this);
this.handle_lname = this.handle_lname.bind(this);
this.handle_mname = this.handle_mname.bind(this);
this.handle_email = this.handle_email.bind(this);
this.handle_homenum = this.handle_homenum.bind(this);
this.handle_contactnum = this.handle_contactnum.bind(this);
this.handle_employ_status = this.handle_employ_status.bind(this);
this.handle_employ_relocate = this.handle_employ_relocate.bind(this);
this.handle_employ_start_date = this.handle_employ_start_date.bind(this);
this.handle_employ_file = this.handle_employ_file.bind(this);
}
componentDidMount() {
const id = this.props.match.params.id;
axios.get('/api/online_application_job_title/' +id).then(response => {
this.setState({
Job_name:response.data
})
})
}
handleSubmit(e)
{
const data = {
firstname: this.state.f_name,
lastname : this.state.l_name,
middlename : this.state.m_name,
email : this.state.email,
home_number : this.state.home_num,
contact_num : this.state.contact_num,
job : this.state.Job_name[0].position_name,
employ_status : this.state.employ_status,
employ_relocate : this.state.employ_relocate,
employ_start_date : this.state.employ_start_date,
employ_file : this.state.employ_file
}
axios.post('/api/save_application',data).then(response => {
console.log(response);
}).catch(error => console.log(error));
}
handle_fname(e)
{
this.setState({
f_name:e.target.value,
})
}
handle_lname(e){
this.setState({
l_name:e.target.value,
})
}
handle_mname(e){
this.setState({
m_name:e.target.value,
})
}
handle_email(e){
this.setState({
email:e.target.value,
})
}
handle_homenum(e){
this.setState({
home_num:e.target.value
})
}
handle_contactnum(e){
this.setState({
contact_num:e.target.value
})
}
handle_employ_status(e){
this.setState({
employ_status:e.target.value
});
}
handle_employ_relocate(e){
this.setState({
employ_relocate:e.target.value,
})
}
handle_employ_start_date(e){
this.setState({
employ_start_date:e.target.value,
})
}
handle_employ_file(e){
this.setState({
employ_file: e.target.files[0].extension
})
}
renderName() {
return (
this.state.Job_name.map(name => (
<input placeholder="" value={name.position_name} type="text" className="form-control"/>
))
)
}
render() {
return (
<div>
<div className="header">
<div className="jumbotron">
<h1>Online Application</h1>
</div>
</div>
<form onSubmit={this.handleSubmit}>
<div className="container">
<h5><b>Personal Info</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="First Name*"
value={this.state.f_name}
onChange={this.handle_fname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Last Name*"
value={this.state.l_name}
onChange={this.handle_lname}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Middle Name*"
value={this.state.m_name}
onChange={this.handle_mname}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Email Address*"
type="email"
value={this.state.email}
onChange={this.handle_email}
className="form-control"/>
</div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
placeholder="Home Number*"
type="number"
value={this.state.home_num}
onChange={this.handle_homenum}
className="form-control"/>
</div>
<div className="col-md-6">
<input
placeholder="Contact Number*"
type="number"
value={this.state.contact_num}
onChange={this.handle_contactnum}
className="form-control"/>
</div>
</div>
<br/><br/>
<h5><b>Employment Application</b></h5>
<br/>
<div className="row">
<div className="col-md-6">
<p>Position Applying For</p>
{this.renderName()}
</div>
<div className="col-md-6">
</div>
</div>
<br/><br/>
<div className="row">
<div className="col-md-6">
<p>1. What is your current employment status?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Unemployed"/>Unemployed
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Employed"/>Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Self-Employed"/>Self-Employed
</label>
</div>
<div className="form-check-inline disabled">
<label className="form-check-label">
<input
type="radio"
className="form-check-input"
name="employmentstatus"
onChange={this.handle_employ_status}
defaultChecked={false}
value="Student"/>Student
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>2. Are you willing to relocate?</p>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="Yes"/>Yes
</label>
</div>
<div className="form-check-inline">
<label className="form-check-label">
<input type="radio"
name="relocate"
onChange={this.handle_employ_relocate}
className="form-check-input"
value="No"/>No
</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>3. When is your available start date?</p>
<input
name="startdate"
type="date"
onChange={this.handle_employ_start_date}
value={this.state.employ_start_date}
required=""
className="form-control"/>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<p>4. Kindly attach a copy of your resume (PDF,docx files only).</p>
<div className="custom-file">
<input
type="file"
name="file"
accept="application/msword,application/pdf"
onChange={this.handle_employ_file}
className="custom-file-input"
id="inputGroupFile04"/>
<label className="custom-file-label" htmlFor="inputGroupFile04">Choose file</label>
</div>
</div>
<div className="col-md-6"></div>
</div>
<br/>
<div className="row">
<div className="col-md-6">
<input
className="btn btn-outline-primary btn-large form-control col-md-5"
type="submit"
value="Send Application"/>
</div>
<div className="col-md-6"></div>
</div>
</div>
</form>
</div>
)
}
Controller:
public function save_application(Request $request)
{
$firstname = $request->get('firstname');
$lastname = $request->get('lastname');
$middlename = $request->get('middlename');
$email = $request->get('email');
$home_number = $request->get('home_number');
$contact_num = $request->get('contact_num');
$job = $request->get('job');
$employ_status = $request->get('employ_status');
$employ_relocate = $request->get('employ_relocate');
$employ_start_date = $request->get('employ_start_date');
$employ_file = $request->get('employ_file');
$now = new DateTime();
DB::insert('INSERT INTO onlineapplication
(position_name,firstname,middlename,lastname,email,homenumber,phonenumber,employmentstatus,relocate,starting_date,destination,file_img_name,Status)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',[
$firstname,
$lastname,
$middlename,
$email,
$home_number,
$contact_num,
$job,
$employ_status,
$employ_relocate,
$employ_start_date,
$employ_file
]);
return response()->json('Successfully inserted');
}
When form tag is used, the submit will trigger the default behaviour that is based on the method provided and the action url.
as in your example you are handling the data explicitly you should prevent the default behaviour.
add the below code in handle submit
handleSubmit(e) {
e.preventDefault();
...
...
}
this will prevent the default behaviour.
Improvement for state update:
you don't need individual functions to update the input value to state this can be combined in one function.
to combine, provide the input name same as state name.
this.state ={
"f_name": '',
"l_name": '',
...
}
<input name="f_name" ... onChange={this.handleInputChange}/>
<input name="l_name" .. onChange={this.handleInputChange}/>
handleInputChange(e){
let target = e.target;
let name = target.name;
let value = target.value
this.setState({[name]: value})
}
for more info refer this link.
First, I just want to introduce to you to the arrow function in JavaScript (ES6). Declaring private methods like this:
handle_fname = (e) =>
{
this.setState({
f_name:e.target.value,
})
}
will save you time from unnecessary binding in the constructor.
Regarding your question, you missed to show the content of your this.handleSubmit(). Without this, I can assume that the form submit fired a get call since you failed to put method attribute in your <form/> tag, and without indicating your method attribute will result to default get method. Get method when used, data submitted will be visible in the page address field of your browser.
EDIT
You already added your handleSubmit() in your question, and it looks okay. If data is still shown in the address field of your browser, try adding method="post" in your form tag like this:
<form onSubmit={this.handleSubmit} method="post">

Resources