Jonathan Spencer
Jonathan Spencer

Reputation: 11

ReactJS: Unable to get the value from a select dropdown because the value is undefined

I just wanted to make a proof of concept that based on the person's search text and the option they select from the dropdown it will redirect them to the search engine of their choice.

const options = [
  { value: 'http://www.google.com/search?q=', label: 'Google' },
  { value: 'http://search.yahoo.com/search?p=', label: 'Yahoo' },
  { value: 'https://www.bing.com/search?q=', label: 'Bing' },
  { value: 'https://duckduckgo.com/?q=', label: 'DuckDuckGo' }
]

//const [selection, setSearch] = useState("");


const doSearch = event => {
  event.preventDefault();
  var sf=document.searchform;
  var submitto = sf.sengines[sf.sengines.selectedIndex].value + (sf.searchterms.value);
  console.log("log: " + submitto);
  window.location.href = submitto;
  //window.location.replace(submitto)
  return null;
}

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>Search:</p>
        <form name="searchform" onSubmit={doSearch}>
        <Select id="sengines" options={options}/>
        For:
        <input type="text" name='searchTerms'/>
        <input type="submit" name="SearchSubmit" value="Search"></input>
        </form>
      </header>
    </div>
  );
}

When I hit search it throws an error saying that the selectedIndex is undefined. Is there a syntax mistake I am making that I am unaware of?

Upvotes: 0

Views: 38

Answers (2)

Jonathan Spencer
Jonathan Spencer

Reputation: 11

The problem was easier to solve than I realized.

sf.searchTerms.value 

Needs to be camel cased

Upvotes: 1

Ben Watson
Ben Watson

Reputation: 31

I think the mistake might be the line where you're doing

var sf=document.searchform;

To get a form element by its name, try doing

var sf = document.getElementsByName("searchForm")[0];

Upvotes: 0

Related Questions