I am trying to get the value from a simple html textfield but whenever i write something and press enter no value is saved. i tried comparing the input from the textfield with a simple == but nothing works. I don't even get any value for console.log(textervalue). Does anyone know what i am doing wrong?
<div class="splitscreen" >
<div class="left">
<video class="input_video"></video>
<canvas class="output_canvas" width="960" height="540" id="rand"></canvas>
</div>
<div class="right">
<canvas class="chat_canvas" width="250" height="500" id="rundrand" ></canvas>
<form action="/url" method="GET" id="rand_text">
<input type="text" id ='texter' value='Guess here' autocomplete ='off'>
</form>
</div>
</div>
var read = 'car';
textervalue = document.getElementById("texter").value;
//just to test if i get a value
if (textervalue == read)
{
canchat.fillStyle="#FFFFF";
canchat.fillRect(0,0, canvasChat.width, canvasChat.height);
}
console.log(textervalue);
You don't get any value because you need an event listener so JS knows to pull data once the field has been filled.
In the HTML form, add a button and then use an event listener to check when the button was clicked. Then, JS will know to grab the value of the input field.
Without preventDefault()
let btn = document.getElementById('submitBtn');
btn.addEventListener('click', function() {
textervalue = document.getElementById("texter").value;
console.log(textervalue);
});
<div class="splitscreen" >
<div class="left">
<video class="input_video"></video>
<canvas class="output_canvas" width="960" height="540" id="rand"></canvas>
</div>
<div class="right">
<canvas class="chat_canvas" width="250" height="500" id="rundrand" ></canvas>
<form action="/url" method="GET" id="rand_text">
<input type="text" id ='texter' value='Guess here' autocomplete ='off'>
<button id="submitBtn">Submit</button>
</form>
</div>
</div>
With preventdefault()
let btn = document.getElementById('submitBtn');
btn.addEventListener('click', function(e) {
e.preventDefault();
textervalue = document.getElementById("texter").value;
console.log(textervalue);
});
<div class="splitscreen" >
<div class="left">
<video class="input_video"></video>
<canvas class="output_canvas" width="960" height="540" id="rand"></canvas>
</div>
<div class="right">
<canvas class="chat_canvas" width="250" height="500" id="rundrand" ></canvas>
<form action="/url" method="GET" id="rand_text">
<input type="text" id ='texter' value='Guess here' autocomplete ='off'>
<button id="submitBtn">Submit</button>
</form>
</div>
</div>
<form action="/url" method="GET" id="rand_text">
<input type="submit" onclick="fonctionHere(this)" id ='texter' value='Guess here' autocomplete ='off'>
</form>
function fonctionHere(e) {
console.log(e.value);
}
submit is form action input directly.. and with an onclick, we have "this" it something like this same codes "getElementById" was send to the function directly