Home > Software engineering >  How can I retrieve an HTML form value and put it in a JavaScript object?
How can I retrieve an HTML form value and put it in a JavaScript object?

Time:11-25

so I'm kind of a beginner at JavaScript and APIs, things like that. I want to implement an API into my website that can detect whether an article is fake news or not based on the title. I already found the API, which is this, but I'm a bit confused with how to retrieve the form value from my HTML code, shown below:

<input type="text" name="check" id="check">
    <button onClick="checkFakeNews" id="btn">Check</button>

    <p id="result"></p>

I already tried typing up this function:

function checkFakeNews() {
    document.getElementById('check') = text
    console.log(text)
}

to try to print out the value, but I didn't get anything.

I also want to get the result, stored in 'data' in the API I believe, and display it in the paragraph. I'd be very grateful to anyone who can help me!

CodePudding user response:

Firstly, You are you writing document.getElementById('check') = text which doesn't do anything.

Second thing that in HTML onClick need to be equal to Function Call you are passing just the Name. You need checkFakeNews() instead of checkFakeNews

This should work as required.

function checkFakeNews() {
  const input = document.getElementById('check');
  const text = check.value;
  console.log(text);
}
<input type="text" name="check" id="check">
<button onClick="checkFakeNews()" id="btn">Check</button>

<p id="result"></p>

CodePudding user response:

https://www.javatpoint.com/document-getElementById()-method , and see https://www.w3schools.com/jsref/prop_text_value.asp

var s = document.getElementById("element").innerHTML; //to set

document.getElementById("myText").value = "Johnny Bravo"; to set

  • Related