2017-08-27 14 views
1
countries() 
{ 
    return [{"name":"Afghanistan","code":"AF"},{"name":"Albania","code":"AL"},...]; 
} 

handleCountryChange(e) 
{ 
    console.log('NAME -> ' + e.target.value, ', CODE -> ' + e.target.id); 
    // Outputs: NAME -> Afghanistan, CODE -> country  
} 

render() 
{ 
    return (
     <select className="form-control country-name" id="country" 
     onChange={e => this.handleCountryChange(e)} > 

      {countries().map((country, i) => { return ( 
       <option id={country.code} value={country.name} key={i} > 
        {country.name} 
       </option> 
      )})} 
     </select> 
    ); 
} 

select要素のonChangeハンドラを使用して、オプションのプロパティを取得しようとしています。 country codecountry nameはそれぞれidプロパティとvalueプロパティに格納されます。私は、次のような結果になっています選択フィールドの選択されたオプションのプロパティを取得します。

出力:NAME - >アフガニスタン、CODE - >国

これは私が選択したオプションから選択要素と値のIDを取得しています意味します。アクティブな<option>要素のプロパティを、select要素自体ではなく、その要素で発生したイベントから取得するにはどうすればよいですか?

答えて

0

選択した項目の属性を取得するには、このようにそれを書く:

handleCountryChange(e){ 
    let index = e.target.selectedIndex; 
    let el = e.target.childNodes[index] 
    let option = el.getAttribute('id'); 
    console.log('Name, Code', e.target.value, option); 
} 

チェックこの例:

let data = [{a:1, b:'a'}, {a:2, b:'b'}, {a:3, b:'c'}]; 
 

 
class App extends React.Component{ 
 

 
\t handleCountryChange(e){ 
 
\t  let index = e.target.selectedIndex; 
 
\t  let el = e.target.childNodes[index] 
 
\t  let option = el.getAttribute('id'); 
 
\t  console.log('Name, Code', e.target.value, option); 
 
\t } 
 

 
\t render(){ 
 
\t  return (
 
\t   <select 
 
\t   \t id="country" 
 
\t   \t onChange={e => this.handleCountryChange(e)} > 
 
\t    \t { 
 
          data.map((country, i) => <option id={country.b} value={country.a} key={i} > {country.a} </option>) 
 
\t    \t } 
 
\t   </select> 
 
\t ); 
 
\t } 
 
} 
 

 
ReactDOM.render(<App/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 

 
<div id='app'/>

2

をあなたがの値でオブジェクト全体を送信することができます選択されたオブジェクトのすべてのプロパティを使用するオプション。

getValue(e) { 
 
    console.log(JSON.parse(e.target.value)); 
 
    } 
 

 
    render() { 
 

 
    let cc = [{ 
 
    value: '1st', 
 
    id: 1 
 
    }, 
 
    { 
 
    value: '2nd', 
 
    id: 2 
 
    }] 
 
    
 
    <select onChange={e => this.getValue(e)}> 
 
      <option value={JSON.stringify(cc[0])}>One</option> 
 
      <option value={JSON.stringify(cc[1])}>Two</option> 
 
</select> 
 
}

これは素晴らしいです同様の問題

+0

と将来に役立つことを願っています。要素全体の値を要素の値で送信することは間違いありません。おかげで、Kochar。 – anonym

関連する問題