itsOnly1_Jah
itsOnly1_Jah

Reputation: 231

How can I pass a variable in a form to to a onclick function in React.js?

What I am trying to achieve is to have an input box's value set once a percentage is selected. But to calculate that value I need the value of the purchasePrice. I've tried accessing the purchasePrice property in the function of onDownPaymentPercentChange but that didn't work. How I do accomplish this?

export default class PurchaseInfo extends Component{
constructor(props){
    super(props);
    this.state ={
        purchasePrice:'',
        downPayment:'',
    }
}

onPurchasePriceChange = (e) => {
        this.setState({
            purchasePrice: e.target.value
        })
    }

onDownPaymentPercentChange = (e) => {
        console.log(e.target.value)
        this.setState({
            downPayment: e.target.value * this.purchasePrice
        })
    }
render(){
  return(
  <div>
     <label>Purchase Price</label>
     <br/>
     <input id='PurchasePrice' required placeholder='$' onChange={this.onPurchasePriceChange}></input>
     <br/>
      <br/>
     <label>Percentage of purchase price</label>      
     <br/>
     <select onChange={this.onDownPaymentPercentChange}>
                    <option value='.035'>3.5%</option>
                    <option value='.05'>.5%</option>
     </select>
     <br/>
     <br>
    <label> Down Payment <label />
      <br/>
     <input required placeholder='$' value={this.state.downPayment}> 
     </input>
 </div>

Upvotes: 0

Views: 78

Answers (2)

HS NANDEESH GOWDA
HS NANDEESH GOWDA

Reputation: 131

You are trying to access a class property called purchasePrice instead of a state value.

onDownPaymentPercentChange = (e) => {
  this.setState({
    downPayment: e.target.value * this.purchasePrice // Problem is here
  })
}

Access purchasePrice through the state object like this: this.state.purchasePrice.

Upvotes: 2

Eric
Eric

Reputation: 11

You a not accessing correctly your state. Also, check the purchasedPrice state beforehand

onDownPaymentPercentChange = (e) => {
   console.log(e.target.value);
   if(this.state.purchasePrice === ''){
      return;
   }
   this.setState({
        downPayment: e.target.value * this.state.purchasePrice
   });
}

Upvotes: 0

Related Questions