Form element not sending its values - javascript

So I have a form:
<form name="htmlform" method="post" action="test.html">
<input type="text" id="first" placeholder="First Name" required>
<input type="text" id="last" placeholder="Last Name" required>
<input type="email" id="email" placeholder="Email" required>
<textarea id="comments" name="comments" placeholder="Message" required></textarea>
<button name="send" type="submit" class="submit">SEND</button>
</form>
and after the user submits the form, it is sent to test.html through POST method. And this is the code on test.html.
<div id="targetDiv"></div>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var first=$("#first").val();
var last=$("#last").val();
var email=$("#email").val();
var comments=$("#comments").val();
var txt1="Welcome " +first+" "+last;
var txt2="Your Email is " +email;
var txt3="Your Message is "+ comments;
$("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
</script>
but when the user submits, #targetDiv always prints out:
Welcome undefined undefined
Your Email is undefined
Your Message is undefined

Your form is indeed sending values to the server using a POST request. However, the page test.html is a different page from the page with the form, so the <input> elements no longer exist at that point.
You will need to write server-side code to handle the POST parameters and insert them into the test.html page.
Alternatively, you could send the parameters with a GET request, and inspect the window.location.queryString property to parse the values.

Your form and the div you are trying to append values to need to be in the same html file unless you are working with a server. Also give your submit an event listener to call all the code you already have. Like this:
$(".submit").on("click", function(e) {
e.preventDefault();
var first=$("#first").val();
var last=$("#last").val();
var email=$("#email").val();
var comments=$("#comments").val();
var txt1="Welcome " +first+" "+last;
var txt2="Your Email is " +email;
var txt3="Your Message is "+ comments;
$("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
});

Javascript or jquery is not a server side language .. use any serverside script like php,asp.
if you want to do the same using jquery use the following method..
<form name="htmlform" method="post" action="test.html">
<input type="text" id="first" placeholder="First Name" required>
<input type="text" id="last" placeholder="Last Name" required>
<input type="email" id="email" placeholder="Email" required>
<textarea id="comments" name="comments" placeholder="Message" required></textarea>
<button id="button" name="send" type="button" class="submit">SEND</button>
</form>
<div id="targetDiv">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('#button').click(function () {
var first=$("#first").val();
var last=$("#last").val();
var email=$("#email").val();
var comments=$("#comments").val();
var txt1="Welcome " +first+" "+last;
var txt2="Your Email is " +email;
var txt3="Your Message is "+ comments;
$("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
});
</script>

Wrap it inside the jQuerys document ready function and trigger the function when user clicks on the submit button.
$(document).ready(function() {
$(".submit").on("click", function() {
var first=$("#first").val();
var last=$("#last").val();
var email=$("#email").val();
var comments=$("#comments").val();
var txt1="Welcome " +first+" "+last;
var txt2="Your Email is " +email;
var txt3="Your Message is "+ comments;
$("#targetDiv").append(txt1+"<br>"+txt2+"<br>"+txt3);
});
});

Related

Getting value from a form input in a javascript variable here I am using jquery cdn. please review code

I tried to save value of form input into a javascript varible but value is always undefind...
here is sample code
<body>
<input type="text" name="name" id="name" placeholder="enter your name">
<input type="email" name="address" id="address" placeholder="enter your mail address">
<input type="submit" name="submit">
<div id="id0">
</div>
<script>
var a;
a =$('input');
var i=0;
var c;
var temp=document.getElementById("name").value;
var temp1=document.getElementById("address").value;
a.eq(2).on('click', function(){
alert(temp)
c=document.getElementById('id'+i);
i++;
c.innerHTML="<hr> Hi, "+temp+" Your address is "+temp1+"<div id='id"+i+"'></div>";
})
</script>
</body>
Result:
Shown in image.
Just value of temp and temp1 varibales.
The variables temp and temp1 Are taken as empty values since you are filling them from the text inputs before you enter some values in them, So to have the values from the inputs at the moment when you click your button you should fill the two variables temp and temp1 in the click function like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<input type="text" name="name" id="name" placeholder="enter your name">
<input type="email" name="address" id="address" placeholder="enter your mail address">
<input type="submit" name="submit">
<div id="id0"></div>
<script>
var a;
a = $('input');
var i=0;
var c;
a.eq(2).on('click', function(){
var temp=document.getElementById("name").value;
var temp1=document.getElementById("address").value;
alert(temp);
c=document.getElementById('id'+i);
i++;
c.innerHTML="<hr> Hi, "+temp+" Your address is "+temp1+"<div id='id"+i+"'></div>";
})
</script>
</body>

Set form field typed value to Javascript Variable and then using this value in another variable

I'm a javascript noobie. I'm creating a form for visitors to sign up to a webinar. I need to create a "unique code" or unique identifier for each visitor that submits the form.
For this I've created a hidden field called "Unique Code". This unique code is generated from a variable which concatenates a string, the email address value typed in the form and a webinar id that I assign from another variable. When I submit the form I just get the string and the webinar id concatenated by not the email address. The desired resulting value is something like this: GTW-visitor#emailaddress.com-12345. Here's my code:
<form action="/destination/" method="post" name="GTW_Test_Form">
<input type="hidden" name="gtwWebinarId" id="gtwWebinarId" value="">
<input type="hidden" name="uniqueCode" id="uniqueCode" value="">
<label for="email"><b>Email</b></label><br>
<input type="text" placeholder="Enter Email" name="emailAddress" id="emailAddress" required><br>
<label for="name"><b>First Name</b></label><br>
<input type="text" placeholder="Your First Name" name="firstName" id="firstName" required><br>
<label for="name"><b>Last Name</b></label><br>
<input type="text" placeholder="Your Last Name" name="lastName" id="lastName" required><br><br>
<input type="submit" value="Register to webinar">
</form>
And then, the javascript:
<SCRIPT LANGUAGE="JavaScript">
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
</script>
Thanks in advance,
Daniel
Your script runs even before the form fields have any value, you may have to write your script code inside a function which will be invoked by "onsubmit" event of the form.
<form onsubmit="foo(event)">
<script LANGUAGE="JavaScript">
const foo = (event)=>{
event.preventDefault();
var emailAddressInput = document.getElementById("emailAddress").value;
var webinarId = "12345678";
var uniqueCode = "GTW-" + emailAddressInput + "-" + webinarId;
document.querySelector("#gtwWebinarId").value = webinarId;
document.querySelector("#uniqueCode").value = uniqueCode;
}
</script>
Try to use var emailAddressInput = document.querySelector("#emailAddress").value;
That actually worked! Thank you, Sai!

jQuery form doesn't validate when button is outside of form tags

I can't seem to get my form to validate when the button is outside the <form></form> tag. Any ideas how I can achieve this? I can't place it inside the form for technical reasons (it's inside a sticky navbar).
My HTML markup:
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" onclick="nextStep();">Next</button>
And the jQuery code:
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
},
onSuccess : function() {
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
When I click the button, nothing happens. Simply nothing :( Any suggestions?
You can assign the button to the form with form attribute. See W3Schools example.
<button class="btn" form="frm-shipping" onclick="nextStep();">Next</button>
function nextStep()
{
$.validate({
form : '#frm-shipping',
borderColorOnError:"#FF0000",
onError : function() {
console.log('error')
},
onSuccess : function() {
console.log('te3st')
var params = $( "#frm-shipping").serialize();
// AJAX call here
}
});
}
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-form-validator/2.3.26/jquery.form-validator.min.js"></script>
<form id="frm-shipping" class="frm-shipping" method="post">
<input type="text" name="contact_phone" class="has_validation"
placeholder="Contact phone" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
<input type="text" name="first_name" class="has_validation"
placeholder="First Name" value="" data-validation="required"
data-validation-error-msg="this field is mandatory!" >
</form>
<button class="btn" form='frm-shipping' onclick="nextStep();">Next</button>
Try this
$('.btn').click(function(){
Validate method
});

Displaying user input from form using Javascript

I want to get the user filled form and display their output.
So I tried this:
<form name="testForm">
<input type="text" name="username" id="username">
<br>
<input type="text" name="password" id="password">
<br>
<input type="submit" value="Submit" onClick="myFunc()">
</form>
<div id="demo"></div>
<script>
function myFunc(){
var x = document.getElementById('username').value;
document.write(x);
}
</script>
This works as intended. Now, I just want to change the way it displays by making it display in the div with the id demo.
So this is what I tried:
<form name="testForm">
<input type="text" name="username" id="username">
<br>
<input type="text" name="password" id="password">
<br>
<input type="submit" value="Submit" onClick="myFunc()">
</form>
<div id="demo"></div>
<script>
function myFunc(){
var x = document.getElementById('username').value;
document.getElementById('demo').innerHTML =x;
}
</script>
Now as you can see, this doesn't work. It actually displays the results and then reloads a blank screen. I can't seem to understand why this is happening.
From my code, I can see that I've assigned x to the username value. So all I am doing is instead of using document.write (which worked), I am just wanting it to display in the div. However it displays and loads a blank screen.
Can someone please let me know what am I doing wrong? How can I display under the div demo of what the user typed in for username field. Is it a syntax error?
ps: I am self learning and practicing, so I just tried to play with username. Once I do that I will apply the same codes for password.
you can use preventDefault() to stop submit button from submitting.
<form name="testForm">
<input type="text" name="username" id="username">
<br>
<input type="text" name="password" id="password">
<br>
<input type="submit" value="Submit" onClick="myFunc(event)">
</form>
<div id="demo"></div>
<script>
function myFunc(event){
event.preventDefault();
var x = document.getElementById('username').value;
document.getElementById('demo').innerHTML =x;
}
</script>
You need to prevent form submission.
Change myFunc to:
function myFunc (evt) {
evt.preventDefault();
// everything else
}

How do I use document.getElementById from an input in a modal?

I have a homemade modal (not bootstrap) that I have inserted a form into that I need to use JS to retrieve the values of:
<div id="openModal" class="modalDialog">
<div>X
<h2>Please contact me with any questions or to request a Free Home Market Analysis</h2>
<!--<form id="contact_form">-->
<p id="fname" class="form_items">
<input type="text" name="fname" id="fname" placeholder="First Name" required />
</p>
<p id="lname" class="form_items">
<input type="text" name="lname" id="lname" placeholder="Last Name" required />
</p>
<p id="email" class="form_items">
<input type="email" name="email" id="email" placeholder="Email" required />
</p>
<p id="phone" class="form_items">
<input type="tel" name="phone" id="phone" placeholder="Telephone" />
</p>
<p id="comments" class="form_items">
<textarea rows="4" cols="50" name="message" placeholder="Comments" id="message"></textarea>
</p>
<p>
<button class="submit" type="submit" onclick="submitForm();">Submit</button>
</p>
<span id="status"></span>
<!--</form>-->
</div>
</div>
<input type="text" id="test"/>
<button onclick="submitForm()">Hi</button>
The test input and button is an example of what does work, when outside of the modal. Here is the JS:
function submitForm(){
var xmlhttp = new XMLHttpRequest();
var fn = document.getElementById('fname').value;
var ln = document.getElementById('lname').value;
var e = document.getElementById('email').value;
var p = document.getElementById('phone').value;
var m = document.getElementById('message').value;
alert(fn);
var test = document.getElementById('test').value;
alert(test);
}
The first alert(fn) alerts "undefined" while the second alert(test) alerts the value I enter into the test input box.
Why is this and what is the workaround? I tried making a jsfiddle: https://jsfiddle.net/k1g9dq7w/ but the Fiddle doesn't work, maybe someone knows more about JsFiddle and why this is.
Remove id from <p>. id is unique in the document.
id of <p> tag and <input> tag should be different.
In your case, getElementById('fname') method accessed the <p> tag because it is the first tag whose id is equal to 'fname'.
It is true that you need to remove the unique id attribute from the <p> element.
However if you test it with only that change it will still not work on the given jsFiddle sample. you need to change the jsFiddle javascript settings by clicking on the javascript button over the paragraph, and changing load type from 'onload' to 'No wrap ~In head' so it will treat the javascript as if it is in the <head> area of the html, Rather than their default which is executing the script onLoad.

Categories

Resources