1

I have code for an auto-completing program, but I want to make it into a website search bar. What I need to know, is how to get access to the value of myCountry.

Here's the part with myCountry:

<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="Country">
</div>

Once I know how to do that, I think that I can just put an if else statement into a JavaScript code.

What I thought I should do is use the getElementById() function, but I'm new to html and JavaScript so I have no idea on what to do.

Here's a link to the full code=> link

Joey Phillips
  • 1,543
  • 2
  • 14
  • 22

2 Answers2

1

You can use document.getElementById(), and pass it a string. This will return information about the element, which you can use to do whatever you need with your application.

Here are some basic usage examples:

let myCountry = document.getElementById('myInput')

console.log(myCountry.placeholder)
console.log(myCountry.tagName)
console.log(myCountry.getAttribute('type'))

document.getElementById('submit').addEventListener('click', e => {
  console.log(myCountry.value)
  switch(myCountry.value.toLowerCase()) {
    case 'uganda': document.body.style.backgroundColor = 'yellow'; break;
    case 'canada': document.body.style.backgroundColor = 'red'; break;
    case 'china': document.body.style.backgroundColor = 'green'; break;
    default: document.body.style.backgroundColor = 'white'; break;
  }
})
<form autocomplete="off" action="/action_page.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="myCountry" placeholder="Country">
  </div>
  <div>
    <input type="button" id="submit" value="Get Input Value">
  </div>
</form>
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
  • I can't believe it! It works! thank you so much. I'm pretty sure from here I can make it take me to a different page just like a website search bar. Thank you! – Highvoltagemath May 02 '19 at 19:02
0

Yes, You can definitely use the getElementById. e.g.

let country = document.getElementById('myInput').value 

But I think you should also see this answer here to learn about various other methods

Rahul Saini
  • 216
  • 1
  • 16