get value of input using javascript - javascript

I am trying to get value of input using js but it doesn't work. Where is my mistake?
Alert doesn't work.
<body>
<form name="inputform" id="form1" action="html_form_action.asp" method="get" style="visibility:hidden">
Email: <input type="text" name="email" ></input>
<input type="button" value="Gönder" onclick="CreateU()"></input>
</form>
</body>
js file:
var xmail="";
CreateU = function(){
var xx = "";
xmail=document.getElementById('email').value;
alert(xmail);
xx= myAddress + xmail + ans + tf;
window.location.assign(xx);
}

Your email input doesn't have an ID:
<input type="text" name="email" id="email" />

Add id to your "Email" input: <input type="text" name="email" id="email" ></input>
Have a look: http://jsfiddle.net/K8kp9/
Note that now you possibly see nothing because of style="visibility:hidden" at your form tag..
Have some reading: Difference between id and name attributes in HTML

email is a name, just change 'name' to 'id' ^^

please set the id in email
<body>
<form name="inputform" id="form1" action="html_form_action.asp" method="get" style="visibility:hidden">
Email: <input type="text" name="email" id="email" ></input>
<input type="button" value="Gönder" onclick="CreateU()"></input>

use id attribute in the input to get the value by using document.getElementById().
<input type="text" name="email" id="email" ></input>

you forgot to mention id='email' in your input element.

Related

how to get values from a form and put them into global variables

for example
this is our form
<form action="test1" method="GET" name="frm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<input type="submit" value="Submit" >
</form>
and here I want to put the content of the values from the form and put them into global variables I've tried this code. But it doesn't display the content of "a"
<script>
var a=document.frm.lname.value;
console.log(a);
</script>
you access the form value and it returns the correct value.
your input fields are empty and your get an empty result.
assign an initial value to your form fields and you will get them.
<form action="test1" method="GET" name="frm">
First name: <input type="text" name="fname" value="sdfsd"><br>
Last name: <input type="text" name="lname" value="sdfsd"><br>
<input type="submit" value="Submit" >
</form>
if you want to get the value your user entered, run your
var a=document.frm.lname.value;
after an event like onsubmit event of your form
Look at the example below which logs the value of last name after a user clicks on submit button
var a=document.frm.lname;
function aFunction(){
console.log(a.value);
}
<form action="#" method="GET" name="frm" onsubmit="aFunction()" >
First name: <input type="text" name="fname" ><br>
Last name: <input type="text" name="lname" ><br>
<input type="submit" value="Submit" >
</form>

How to validate multiple inputs in a form

Please take a look at this code, I want to know how to validate all these input elements in this single form using JavaScript.
I know they look the same but i have the names in a separate div. Your corrections and contributions to my form will be very much appreciated.
<form name="myForm">
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="text" name="fname"><br><br>
<input type="password" name="fname"><br><br>
<input type="submit" value="Submit">
</form>
Yes, You can. Try this to Validate data in Java Script
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
Then You have to create a javaScript Function to Validate the data as above validateDate(), for this, now your code is
<script>
function validateData() {
var fname = document.getElementById("fname").value;
var username = document.getElementById("username").value;
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
//if name is empty
if(fname == "" || username == "" || email == "" || password == "") {
//SOme Error Code here
alert("Please Fill All the Form Data.");
}
if(username.length < 4 || username.length > 20) {
//SOme Error Code here
alert("username must be less than 20 but more than 4 Characters.");
}
// You can add more filters like password length, and so on by using more if conditions
}
</script>
<body>
<form name="myForm" onsubmit="return validateData()">
<input type="text" id="name" name="fname"><br><br>
<input type="text" id="username" name="username"><br><br>
<input type="text" id="email" name="email"><br><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
</body>
That's all. :)
Even though this requires jQuery, it can solve your problem:
To use jQuery Validate you just need to include in your code a version of the jQuery library equal or more recent than 1.7 and a file with the plugin.
See an example:
jQuery('form').validate();
After calling the jQuery.fn.validate method, you can validate your fields using data attributes, that are valid to the HTML5, according to the W3C.
See a example to required field:
<form>
<input type="text" data-required />
</form>
https://plugins.jquery.com/validate/

Add multiple fields to form

I would like to add a function that generates multiple fields to my form.
This is how my form looks like:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
In my case I want 3 new fields (name, phone, email) when clicking on "Add more fields".
How can I do this?
https://jsfiddle.net/374cxt5s/
Try this: https://jsfiddle.net/Twisty/q8zj00s0/1/
HTML
<form action="form_sent.php" method="post">
<ul id="fieldList">
<li>
<input name="name[]" type="text" placeholder="Name" />
</li>
<li>
<input name="phone[]" type="text" placeholder="Phone" />
</li>
<li>
<input name="email[]" type="text" placeholder="E-Mail">
</li>
</ul>
<button id="addMore">Add more fields</button>
<br>
<br>
<input type="submit">
</form>
CSS
ul {
padding: 0;
margin: 0;
}
ul li {
list-style: none;
}
JQuery
$(function() {
$("#addMore").click(function(e) {
e.preventDefault();
$("#fieldList").append("<li> </li>");
$("#fieldList").append("<li><input type='text' name='name[]' placeholder='Name' /></li>");
$("#fieldList").append("<li><input type='text' name='phone[]' placeholder='Phone' /></li>");
$("#fieldList").append("<li><input type='text' name='email[]' placeholder='E-Mail' /></li>");
});
});
This allows you to store the results in array when you submit the form. Since you could have 5 names, phones, and emails, an array is the best way to address that. Then in PHP, you would have $_POST['name'][0] as the first one.
I'm assuming you probably want to create a dynamic form that allows you to add multiple contacts, etc.
CodePen Example
http://codepen.io/anon/pen/yeVRgw
The Basic HTML Setup
So that you can loop through things, and for sake of your own sanity, you'll probably want to segment out each chunk within the form. We'll also set up a hidden input to track how many partitions of name,phone,email have been created. We'll default at 1
<form action="form_sent.php" method="POST">
<input type="hidden" name="contacts" id="contacts" value="1">
<div class="form-contacts-container">
<div class="form-contact" id="form-contact-1">
<input type="text" name="name-1" id="name-1" placeholder="Name">
<input type="text" name="email-1" id="email-1" placeholder="E-mail">
<input type="text" name="phone-1" id="phone-1" placeholder="Phone">
</div>
<!-- We'll be adding additional inputs here -->
</div>
<div class="form-contacts-add">
<input type="button" value="Add More Fields" id="add-fields">
</div>
<div class="form-contacts-submit">
<input type="submit" name="submit" id="submit" value="Submit">
</div>
</form>
The JavaScript
This assumes you are using jQuery, so ensure that this is in your <head>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
Now we need to do a few things - firstly, attach an event listener to our button and secondly, add a new <div class="form-contact"> with included fields to our form. We'll also need to ensure that we're counting up to make sure each section has a unique name/id, and we'll increase the hidden input value to count how many contacts have been added in total.
<script type="text/javascript">
var total = 1; // Our default for how many contacts we have
$( document ).on( 'click', '#add-fields', function() {
var addBlockId = total = total + 1;
var addBlock = document.createElement('div');
$(addBlock).addClass('form-contact');
$(addBlock).attr('id','form-contact-' + addBlockId);
var inputName = document.createElement('input');
$(inputName).attr('type','text');
$(inputName).attr('name','name-' + addBlockId);
$(inputName).attr('id','name-' + addBlockId);
$(inputName).attr('placeholder','Name');
$(inputName).appendTo($(addBlock));
var inputEmail = document.createElement('input');
$(inputEmail).attr('type','text');
$(inputEmail).attr('name','email-' + addBlockId);
$(inputEmail).attr('id','email-' + addBlockId);
$(inputEmail).attr('placeholder','E-mail');
$(inputEmail).appendTo($(addBlock));
var inputPhone = document.createElement('input');
$(inputPhone).attr('type','text');
$(inputPhone).attr('name','phone-' + addBlockId);
$(inputPhone).attr('id','phone-' + addBlockId);
$(inputPhone).attr('placeholder','Phone');
$(inputPhone).appendTo($(addBlock));
$(addBlock).appendTo($('.form-contacts-container'));
$('#contacts').val(total);
});
</script>
Processing your Form
The last piece of the puzzle is to process your form properly. Not goign to give you all the answers here, but the basic logic would be to grab the $_POST['contacts'] value we've been updated and run a loop through to grab all of your inputs and associated values. For instance in PHP:
$total = $_POST['contacts'];
$contacts = array();
for( $i = 1; $i < $total; $i++ ) {
$this_contact = $array(
'Name' => $_POST['name-' . $i],
'Email' => $_POST['email-' . $i],
'Phone' => $_POST['phone-' . $i]
);
array_push($contacts, $this_contact);
}
var_dump( $contacts );
try something like this :
(function() {
var button=document.getElementById("add-user");
button.addEventListener('click', function(event) {
event.preventDefault();
var cln = document.getElementsByClassName("user")[0].cloneNode(true);
document.getElementById("users").insertBefore(cln,this);
return false;
});
})();
<form id="users" action="form_sent.php" method="post">
<div class="user">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id='add-user'>Add more fields</button><br><br>
<input type="submit">
</form>
https://jsfiddle.net/9955n4fo/
It might not be a bad idea to wrap your input fields in a div just so when you append the other inputs they appear consecutively. Try something like this in your html
<form action="form_sent.php" method="post">
<div id="fields">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
and then your javascript can be completed as so
$(function() {
$('button').click(function() { addFields(); });
});
function addFields() {
var html = "<input name='name' type='text' placeholder='Name'><br>
<input name='phone' type='text' placeholder='Phone'><br>
<input name='email' type='text' placeholder='E-Mail'><br><br>";
$('#fields').append(html);
}
You need to implement jQuery to change the HTMLs DOM.
So, you add this in your <head></head> tags:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
You need to modify your HTML like this:
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button extra="0">Add more fields</button><br><br>
<input type="submit">
</form>
Then you need to use this jQuery code:
<script>
$("button").on("click",function(){
var extra = $(this).attr("extra") + 1;
$("form").append("<input type='text' placeholder='Other Field' name='field' />");
$(this).attr("extra",extra);
}
</script>
This is the end!! :)
Try This :
Jquery append() function seems to sort out your answer
HTML Code should be as follow :
<form action="form_sent.php" method="post">
<div class = 'xyz'>
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button>Add more fields</button><br><br>
<input type="submit">
</form>
you JS should be as follow :
$(button).click(function(event){
$('.xyz').append("<input type ='text' class ='name' placeholder = 'Enter name'/><br/>");
$('.xyz').append("<input type='text' class='phone' placeholder='Enter phone'/><br/>");
$('.xyz').append("<input type='mail' class='phone' placeholder='Enter e-mail'/><br/>");
event.preventDefault();
});
This is how I would solve it.
HTML:
<form action="form_sent.php" method="post">
<div id="inputHolder">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
</div>
<button id="addMoreFields">Add more fields</button><br><br>
<input type="submit">
</form>
JS:
$( document ).ready(function() {
$("#addMoreFields").click(function(event) {
event.preventDefault();
$("#inputHolder").append('<input name="name" type="text" placeholder="Name"><br>');
$("#inputHolder").append('<input name="phone" type="text" placeholder="Phone"><br>');
$("#inputHolder").append('<input name="email" type="text" placeholder="E-Mail"><br><br>');
});
});
https://jsfiddle.net/r71odb7t/
First you want to clone the elements you want to be adding. Do that when the page loads. Then when the button is clicked, clone the copy and add a copy to the page. And, you could either add type="button" to the button or use e.preventDefault() so your form does not get submitted when the button is clicked.
$(function() {
var inputs = $('form > button').prev().prev().prevUntil().clone().add('<br><br>');
$('form > button').on('click', function(e) {
e.preventDefault();
$(this).before(inputs.clone());
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="form_sent.php" method="post">
<input name="name" type="text" placeholder="Name"><br>
<input name="phone" type="text" placeholder="Phone"><br>
<input name="email" type="text" placeholder="E-Mail"><br><br>
<button>Add more fields</button><br><br>
<input type="submit">
</form>

Add to cart without refreshing using JavaScript

When I press the add to cart button, data should be inserted into the database and should be displayed immediately above the form without redirecting to the query page. In this code the first form is working correctly, but the next two forms which are duplicates of the first form are not working. The problem is that the next two forms, when submitted, get redirected to the query page. The index page code is:
<html>
<head>
<title>fetch</title>
</head>
<body>
<ul></ul>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button id="sub">save</button>
</form>
<span id="result1"></span>
<script type="text/javascript" src="http://localhost/json/jquery.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script.js"></script>
<script type="text/javascript" src="http://localhost/json/my_script2.js"></script>
</body>
</html>
The query code is:
<?php
include_once('http://loaclhost/json/conn.php');
$name = $_POST['name'];
$age = $_POST['age'];
if(mysql_query("INSERT INTO users VALUES('$name','$age')"))
echo "successfully";
else
echo "failed";
The JavaScript code is:
$("#sub").click(function(){
$.post($("#myform").attr("action"),$("#myform :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$("#myform").submit(function(){
return false;
});
function clearinput()
{
$("#myform :input").each(function(){
$(this).val('');
});
}
You are submitting form by id : $("#myform").submit(function(){}
and the issue here is that you have given same ids for all the three forms here, make sure that each form will have different id.
also Button ids should be unique
As #asim has mentioned duplicated ids are the problem.try following code.
working js fiddle.http://jsfiddle.net/gw84j7hg/. (Using id selecters)
Updated fiddle using class selecters http://jsfiddle.net/gw84j7hg/2/
Form Code.
<form action="userInfo.php" method="post" id="myform" class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub">save</button>
</form>
<form action="userInfo.php" method="post" id="myform2"
class="formSelecterClass" >
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub1">save</button>
</form>
<form action="userInfo.php" method="post" id="myform3"
class="formSelecterClass">
name: <input type="text" name="name" /><br>
age: <input type="text" name="age" /><br>
<button class="formSubmitButtonClass" id="sub2">save</button>
</form>
<span id="result1"></span>
JS Code
$(".formSubmitButtonClass").click(function(){
$.post($(".formSelecterClass").attr("action"),$(".formSelecterClass :input").serializeArray(), function(info){$("#result1").html(info); });
clearinput();
});
$(".formSelecterClass").submit(function(){
return false;
});
function clearinput()
{
$(".formSelecterClass :input").each(function(){
$(this).val('');
});
}
ID on single HTML files can not repeated. If repeated, the first ID will work out and rest IDs will be invalid. That's why $("#myform") will only apply to the first form.

Pre-fill form field via URL in html

I am looking for a simple way to pre-fill a field in my contact form when ever a user clicks on a link that is given in some other page.
This is my contact form in html :
<form method="post" action="submit.php" >
<p>Your name:
<br /><input name="name" /></p>
<p>Your email:
<br /><input name="email" /></p>
<p>Your message:
<br /><textarea name="message" id="message" rows="10" cols="50"></textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
I want to fill the "message" field with "some text" when a user clicks on a url like www.xyz.com/contact.html?setmessagefield=some_text
A more modern way would be to use the URL() constructor and the searchParams property. Let the browser engine do the work!
(new URL(window.location.href)).searchParams.forEach((x, y) =>
document.getElementById(y).value = x)
Try it online! or on Stack Overflow:
const hash = '?name=some_text&email=more%20text';
const example = "http://example.com/" + hash;
(new URL(example)).searchParams.forEach((x, y) =>
document.getElementById(y).value = x);
<p>Your name:
<br /><input name="name" id="name" /></p>
<p>Your email:
<br /><input name="email" id="email" /></p>
JavaScript has no built-in functions to parse url parameters like that (Since those GET parameters are usually used to send data to the server).
I'd suggest using a hash instead (A hash is purely client-side):
www.xyz.com/contact.html#name=some_text&email=more%20text
Now, add some id's to your fields:
<p>Your name:
<br /><input name="name" id="name" /></p>
<p>Your email:
<br /><input name="email" id="email" /></p>
Then set the values like this, on load:
var hashParams = window.location.hash.substr(1).split('&'); // substr(1) to remove the `#`
for(var i = 0; i < hashParams.length; i++){
var p = hashParams[i].split('=');
document.getElementById(p[0]).value = decodeURIComponent(p[1]);;
}
Working example
The big advantage of this is that it's flexible. If you want to set the values of 2 fields, you supply those 2 fields' id's in the hash:
www.xyz.com/contact.html#name=some_text&email=more%20text
4 fields? 4 id's:
www.xyz.com/contact.html#name=some_text&email=more%20text&username=john&age=23
No need to edit the code, then.
Don't bother with JavaScript if you're using PHP.
Just add a little something to the HTML:
<form method="post" action="submit.php" >
<p>Your name:<br />
<input name="name" value="<?php echo htmlspecialchars($_GET['name']) ?>" /></p>
<p>Your email:<br />
<input name="email" value="<?php echo htmlspecialchars($_GET['email']) ?>"/></p>
<p>Your message:<br />
<textarea name="message" id="message" rows="10" cols="50">
<?php echo htmlspecialchars($_GET['message']) ?>
</textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
You can retrieve your current url with window.location.href and then get the default message via a regular expression :
var msg = window.location.href.match(/\?setmessagefield=(.*)/);
document.getElementById("message").value = msg[1];

Categories

Resources