Nodejs + html evt.target value is undefined - javascript

Okay so here's my html code
document.getElementById('comment-form').addEventListener('submit', async (evt) => {
evt.preventDefault();
const userID = evt.target.userid.value;
const comment = evt.target.comment.value;
console.log(userID, comment);
if(!userID) return alert('Input User ID');
if(!comment) return alert('Input Comment');
})
<div>
<form id="comment-form">
<fieldset>
<legend>Comment</legend>
<div><input id="userid" type="text" placeholder="User ID"></div>
<div><input id="comment" type="text" placeholder="Comment"></div>
<button type="submit">Submit</button>
</fieldset>
</form>
</div>
and the console.log result is
undefined (Whatever comment I input)
And so my question is
why????? why I am getting comment's value while not getting userid's value? I thought for 2 hours still don't know why
If so, how can this not trigger my return alert? So for js undefined is not null? If so isn't that alert code don't work at all?
Here is what I've tried
Changing input id's value to something else.
Changing target to currentTarget
changing evt.target.userid to evt.target.getAttribute()
Edited - code snippet is added, and in the snippet it works. So it must be some kind of issue of callback or timing of js?? how can it be fixed??
It was timing issue at all. Use await.

Related

How can I get the input of a button on a website using Javascript?

I'm a bloody beginner at this,so please don't judge me,ok?
So I made a Website with this text field:
Text: <input type="text" name="text" value="" id="input1"/>
And I made a button,used to get the input of the Text field:
<input type="submit" onclick=getinput>
and this is the getinput()-function:
<script>
function getinput(){
const val = document.querySelector('input1').value;
console.log(val);
console.log("No error in function implement.");
}
</script>
but I generated the following error:
VM195:3 Uncaught TypeError: Cannot read properties of null (reading 'value')
at <anonymous>:3:45
I don't know what this error means,and how to fix it,could someone please help me?
You have some small mistake / bugs in your code. i refeactor it.
1.) the querySelector was wrong. For Ids use '#slectorName'.
2.) onclick="getinput()" instead onclick=getinput
function getinput(){
const val = document.querySelector('#input1').value;
console.log(val);
console.log("No error in function implement.");
}
<input type="text" name="text" value="" id="input1"/>
<input type="submit" onclick="getinput()">
The problem is with the selector. To select an id with document.querySelector, you have to prefix it with a hashtag. Like:
function getinput(){
const val = document.querySelector('#input1').value;
console.log(val);
console.log("No error in function implement.");
}
Alternatively, you can use document.getElementById. For example:
function getinput(){
const val = document.getElementById('input1').value;
console.log(val);
console.log("No error in function implement.");
}
Also, in the submit button, you have to wrap the attribute value in double quotes. You have to write this:
<input type="submit" onclick="getinput()">
instead of this:
<input type="submit" onclick=getinput>

JavaScript function() is not a function

I have a strange error Or I'm being dumb and when I search for my error I don't get the answer I need.
I am trying to have some javascript run if a certain key "/" is pressed in a text box.
Here is the Code:
function ClockIn(){
var kb_press = event.keyCode;
if(kb_press == 47)
{
alert("you are clocking in");
if(document.ClockIn.status.value === "IN"){
alert("You Cant Clock in wile you are already Clocked in\n Please try again!")
document.ClockIn.tx_Barcode.value, document.ClockIn.status.value, document.ClockIn.name.value = "";
}
}
}
<form method="POST" name="ClockIn">
<lable>Type your BarCode <input type="text" name="tx_Barcode" id="tx_Barcode" class="tx_Barcode" onkeypress="ClockIn()" ></lable><br>
<lable>Is your Name? <input type="text" name="name"></lable><br>
<lable>You are currently Signed <input type="text" name="status"></lable><br>
</form>
My result is: ClockIn is not a function
The problem here is you've named your "ClockIn" form, so due to age-old quirks in how HTML interacts with JavaScript, the ClockIn form overwrites your global ClockIn function.
Maybe rename the form "ClockInForm"? Better yet, though, you might want to use document.getElementById("...") to refer to elements.

Cannot re-enable Submit button in Javascript after it has been clicked. ".querySelector().disabled = false" does not seem to work

I am trying to create a simple google search bar in my website. It works fine. However, I am accounting for user error, and for some reason I cannot re-enable my submit button once it is clicked, under the condition that no input is provided. Please see Javascript code below.
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
setTimeout(() => msg.remove(), 3000);
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
As you can see, if no text is input, it will let the user know they will need to enter an actual search query. However, after that point, the submit button just wont work again.
I tried using .querySelector().disabled = false; , as well as .removeAttribute("disabled"), but nothing is working. What exactly am I missing here, to re-activate the submit button once it was clicked with no input?
Your button works just fine. You just remove the complete element and then the msg = document.querySelector(".msg"); doesn't find anything. In addition i would leave the timeout out and let the message there until the user writes something.
You should do it like that:
const text = document.querySelector("#search");
const msg = document.querySelector(".msg");
document.querySelector(".google-form").addEventListener('submit', onclick)
function onclick(e) {
msg.innerHTML= '';
if (text.value === '' || text.value === null) {
e.preventDefault();
msg.classList.add('error');
msg.innerHTML = 'Please enter a proper search query';
document.querySelector("#button").disabled = false; // <-- This method doesn't seem to work.
}
}
<div class="google-form">
<div class="msg"></div>
<form id="my-form" action="https://www.google.com/search">
<input id="search" type="text" name="q" placeholder="Enter Search">
<button id="button" type="submit">Submit</button>
</form>
</div>
When button type is set on submit value, it will send the information to the server anyway. (not if you use preventDefault() method!)
My suggestion is to change button type to button and then write an onclick event for it and check the validation there , if everything was right then call for form submit event!
This is how you can prevent incorrect information from being sent into the server side and avoid the errors that it can cause.

Why is the value of the input element undefined? [duplicate]

This question already has answers here:
HTML class not being recognized [closed]
(4 answers)
Closed 3 years ago.
I have a simple form:
<form name="demoForm" id="demoForm">
<label id=”givenNameLabel” class =blueText>Please enter your given name:
<input type = “text” name = “givenName” id= “givenName” value ="nn">
</label>
<button onclick = validate("givenName");>Validate this entry</button>
</form>
But when I try to get the value it is undefined.
I am getting the value either with vanilla JS or with jQuery:
<script type="text/javascript">
function validate(someTextID){
alert("In validate()") //Works
var thisElement = "#"+someTextID; //the text element;
var thisLabel = thisElement + "Label"; //the label for the text element;
var thisValue = $(thisElement).val(); //The value stored in the text box
alert("thisElement is " +thisElement); //Works
alert("thisLabel is " +thisLabel); //Works
alert("thisValue is " +thisValue); //Why is the value undefined?
//more code to take actions depending on thisValue
}
</script>
After straightening out your HTML a bit by replacing your "smart" quotation marks with "normal" ones (as Sebastian Simon mentioned in his comment)
I simplified your code a bit and added a significant part:
return validate(...) in your onclick part makes sure that the return value from your validation function is used to determine whether to submit the form or not.
return falseinside your function will cause the form not to be transmitted (if you return true the form will be submitted)
function validate(textid){
console.log(document.querySelector('#'+textid).value); //Works
//more code to take actions depending on thisValue
return false; // if you don't want to submit the form yet
}
<form name="demoForm" id="demoForm">
<label id="givenNameLabel" class ="blueText">Please enter your given name:
<input type="text" name = "givenName" id= "givenName" value ="nn">
</label>
<button onclick ='return validate("givenName")'>Validate this entry</button>
</form>
Here is an alternative version. I suspect, that you can probably do without the ids of the individual elements and you can re-use your validation function for other input fields, if you address the input fields in a "relative" way, i.e. by looking for a previousElementSibling of the clicked button.
The Array.prototype.forEach.call() is a clumsy looking construct that applies the Array method forEach() to the nodelist returned by document.querySelectorAll() (this version should even work in the Internet Explorer). Inside the forEach() function the click-event is bound to the validate(ev) function for each button with class "validate".
Array.prototype.forEach.call(document.querySelectorAll('.validate'),
function(el){el.addEventListener('click',validate)});
function validate(ev){
var el=ev.target.previousElementSibling;
console.log('validating element '+el.name+', the value is: '+el.value);
//more code to take actions depending on el.name and el.value
ev.preventDefault(); // in case you DON'T want to submit the form yet ...
}
<form name="demoForm" id="demoForm">
<label class ="blueText">Please enter your given name:
<input type="text" name="givenName" value="Carsten">
<button class="validate">Validate this entry</button></label><br>
<label class ="blueText">Where do you live?
<input type="text" name="myhome" value="Hanover">
<button class="validate">Validate this entry</button></label><br>
<label class ="blueText">What are your hobbies?
<input type="text" name="myhobbies" value="coding">
<button class="validate">Validate this entry</button></label>
</form>

javascript undefined input value despite of writing in it

I have a strange problem: I am getting a undefined alert window by running this code. I looked up all the entrys here but I couldn't find a solution.
I've checked, there is no identical id except this one
running the php file the result of var_dump($user_id) shows the right value
this is why I don't understand why the value in javascript is undefined all the time...
HTML:
<form action="?atn=surveyCode" method="post" class="form mg_top">
<label id="entersID" for="usersID">Enter your prolific ID:</label>
<input id="usersID" value="" type='text' class="form-control talign_center input" name="usersID">
<button id="survey" class="btn btn-primary form-control">Go to questions</button>
</form>
JavaScript: every alert is returning "undefined". I never get in the else part. This is really strange. I've many parts like this in my code and they are working perfectly.
$("#survey").click(function(e){
var prolific = $("usersID").val();
alert(prolific);
if(prolific==undefined){
alert(prolific);
$("#entersID").addClass("error-msg");
$("#entersID").parent().addClass("has-error");
e.preventDefault();
}
else{
alert(prolific);
window.open("http://www.w3schools.com");
}
});
PHP:
private function surveyCode(){
$userID = $_POST["usersID"];
var_dump($userID); //shows a value
}
Please help me, maybe this is a silly bug but I can't find it....
Change the line into
var prolific = $("#usersID").val();
You have to add the "#" sign before the id selector like below :
var prolific = $("#usersID").val();

Categories

Resources