the input.value is not working, same with the previous input - javascript

I'm working with React and I'm trying to get a value entered by the user, but the value is returning empty, and for some reason the input is being filled, in a matter of one line of difference it's like the command .value did not work or exist
mudaTela = async () => {
var escolha = document.querySelector("#campo-tipo-relatorio");
console.log(escolha);
console.log(escolha.value);
}
when I run the above command the result is for the first console.log is as follows
<input aria-invalid="false" autocomplete="off" id="campo-tipo-relatorio" required="" type="text" class="MuiOutlinedInput-input MuiInputBase-input MuiInputBase-inputAdornedEnd MuiAutocomplete-input MuiAutocomplete-inputFocused css-1xqu1wk-MuiInputBase-input-MuiOutlinedInput-input" aria-autocomplete="list" autocapitalize="none" spellcheck="false" value="Detalhado">
however for the second console.log it is simply an empty field
and to do the input I'm doing it as follows
<Autocomplete
className="width-20"
id="campo-tipo-relatorio"
options={ret1}
getOptionLabel={(option) => option}
filterOptions={filterOptions}
onChange={this.mudaTela}
renderInput={(params) => <TextField {...params} label="Tipo de Relatório" required />}
/>
where the variable ret1 has two strings, with the text “Consolidado” and “Detalhado”

Related

How to reach all input field values and submit with button in form?

What I want to do is simple, just take input field values and do something with them by clicking button.
function TableFooterPanel() {
const [firstName, setFirstName] = useState('');
const [lastName, setLastName] = useState('');
const sampleMethod = (x, y) => {
console.log(x + y)
}
return (
<>
<Card className='buttonFooter'>
<Form className='buttonFooter'>
<input type="text" placeholder="First Name" defaultValue={firstName} onClick={setFirstName}></input>
<input type="text" placeholder="Last Name" defaultValue={lastName} onClick={setLastName}></input>
<Button onClick={() => sampleMethod(firstName, lastName)}>Add</Button>
</Form>
</Card>
</>
);
}
export default TableFooterPanel;
Generally examples for that is done with separate handleChange() methods for each input field but I don't want to make separate functions for each so I though to use useState. How can I call the sampleMethod with these parameters ? I could not update values properly with useState.
if you use input field as text, you need onChange :
<input type="text" placeholder="First Name" defaultValue={firstName} onChange={e => setFirstName(e.target.value)}></input>
That way the text that you typing in the input will save in the state.
You can use FormData.
Another suggestion from me is to add an onSubmit event to the form. It's more convenient.
The button should be type="submit". When the user clicks on it the form's onSubmit event will fire.

React - hook state not updating

I'm trying to copy one form input value to another using state but the state isn't updating
I create a form, with a button, where the value from the left form input should be copied to the right form input. This is my code:
const ReviewContactForm = (props) => {
const contact = props.currentContact;
const dbContact = useDbContact(contact.Group);
const [dbSecName, setDbSecName] = useState("");
async function getDbContact() {
let secName = await dbContact.SecretaryName;
setDbSecName(secName);
}
getDbContact();
function acceptSecName(e) {
e.preventDefault();
setDbSecName(contact.SecretaryName);
}
return (
<>
<Form>
<Form.Row>Secretary's Name</Form.Row>
<Form.Row>
<Form.Group as={Col} className="mb-2">
<Form.Control type="input" name="1secname" value={contact.SecretaryName} readOnly />
</Form.Group>
<Form.Group as={Col} className="mb-2">
<Form.Control type="input" name="2secname" value={dbSecName || ""} readOnly />
</Form.Group>
<Button className="PrimaryButton" onClick={acceptSecName}>
Accept proposed
</Button>
<div className="divider" />
<Button className="SecondaryButton" size="sm">
Revert
</Button>
</Form.Row>
</Form>
</>
);
};
No matter what I do, the state of dbSecName doesn't change. I've tried setting a new const. I've tried making the onClick function async and await. If I add console.log for the value of the variable I'm trying to set to, I see it correctly, but the console.log of dbSecName always shows the original value.
I've not really an idea of what to do next. I'm thinking perhaps my approach to setting the form input in the first place is wrong.
So what I'm trying to achieve is that when the 'Accept proposed' button is clicked, the "2secname" form input is re-rendered with the value from "1secname".
Any help greatly appreciated
In the below code snippet
<Form.Control type="input" name="2secname" value={dbSecName || ""} readOnly />
replace value with just dbSecName instead of dbSecName || ""
See if that works

I am trying to auto focus to the next text input on submit

I am rendering text inputs for player names by mapping the components and passing down the player number. I want the user to hit enter and the screen to focus on the next input.
I've tried this
<TextInput style={styles.nameBox} placeholder="Enter Name" onChangeText={(text) => this.setState({text})} ref={`input-${this.props.number}`}
onSubmitEditing={value => {
this.setState({ value })
if (value) this.refs.input_2.focus();
}} />
The problem is that I cant hardcode input_2 because it will then be that way for all of my inputs. I want it to focus on "input-this.props.number++", Basically the following input.
You could develop a function to be triggered on return, and pass the id of the input type that you want to get focus as an argument.
The following sample code is written by Aung Myint Thein from medium.com:
//sample text fields
<TextField
label={"Field 1"}
blurOnSubmit={ false }
returnKeyType={ 'next' }
onSubmitEditing={() => { this.focusTheField('field2'); }}
/>
<TextField
ref={input => { this.inputs['field2'] = input }}
label={"Field 2"}
/>
//function
// variable to hold the references of the textfields
inputs = {};
// function to focus the field
focusTheField = (id) => {
this.inputs[id].focus();
}
Hope this helps

How can I validate 'double' type within From Validation

I'm POSTing new product into my RESTful API and everything is being validated perfectly except doubles.
If I pass a double type for example '2.3' alert says that's incorrect and should be 2 or 3 instead.
const [isValidated, setIsValidated] = useState(false)
const handleSubmit = async event => {
const form = event.currentTarget
event.preventDefault()
if (form.checkValidity() === false) {
event.stopPropagation()
} else {
setIsValidated(true)
await ProductsApiService.postProduct(product)
props.onModalClose()
props.onRefreshList()
setIsValidated(false)
}
}
<Form onSubmit={handleSubmit} validated={isValidated}>
<Form.Group as={Col} controlId="productPrice">
<Form.Label>EUR</Form.Label>
<Form.Control
onChange={handleChange}
type="number"
name="eur"
placeholder="Price EUR"
required />
</Form.Group>
<Form.Row>
<Button variant="primary" type="submit">
Confirm
</Button>
</Form.Row>
</Form>
and this is working properly with '2.0' for example
You can use a pattern that Javascript validator API understands what type of number should deal with. so, for instance, the following pattern indicates the number input must start with a number and use either comma or a dot as a decimal character.
<Form.Control
onChange={handleChange}
type="number"
pattern="[0-9]+([,\.][0-9]+)?" // the Regex for having
name="eur"
placeholder="Price EUR"
required />
you can search for "decimal validation regex" to see all possible types of creating a pattern

How to show error message when field is required and it's value is empty?

I am using this plugin to validate my form. I want to show error message on button when .click happens. In my form all fields are required so I need to validate my form.
I tried with below code but doesn't work
<FormControl className={classes.formControl}>
<TextValidator
required
InputLabelProps={{
shrink: true
}}
id="name"
label="search value"
name="searchValue"
value={searchValue}
onChange={event => handleInput(event, "searchValue")}
validators={["required"]}
errorMessages={["this field is required"]}
margin="normal"
/>
</FormControl>
here is my code
https://codesandbox.io/s/l40l795vx7
<SearchForm
handleInput={this.handleInputFieldChange}
submitClick={this.submitButtonClickHandle}
form={form}
/>
I'm not sure what you are tying to validate in there, since I'm not familiar with the plugin. However, its quite easy to display an error in case of the form not being valid.
You are already saving the values from the inputs in the state, so all you have to do in the submitButtonClickHandle function is something like:
if(this.state.form.searchValue !== '**some conditions**' &&
this.state.form.circle !== '**some condition**'){
//
alert('You did not meet the search criteria')
} else {
// DO WHAT YOU WANT IF ON THE SUBMIT
alert('everything is fine, here is your result')
}

Categories

Resources