I want to save values from inputs in the form into variables Like this example.
<form action="test3" method="POST">
Activity name: <input type="text" name="fname" id='nm'><br>
input1: <input type="text" name="input1" id='in1'><br>
input2: <input type="text" name="input2" id='in2'><br>
output1: <input type="text" name="output1" id='out1'><br>
output2: <input type="text" name="output2" id='out2'><br>
<input type="submit" value="Submit">
</form>
var valname=document.getElementById("nm").value;
var valin1=document.getElementById("in1").value;
var valin2=document.getElementById("in2").value;
var valout1=document.getElementById("out1").value;
var valout2=document.getElementById("out2").value;
Now, how can i get value into a general variable like : var valeur=valin1;
You could use FormData
var form = document.querySelector('form');
var data = new FormData(form);
Best off adding an ID to the form though and getById as if you had multiple forms on a page, this wouldn't solve it.
Mozilla API Docs
Related
I have this simple code in the test0.html file, it sends data to test1.html :
<body>
<form action="test1.html">
<input type="text" name="array[0]" placeholder="val1" id="">
<input type="text" name="array[1]" placeholder="val2" id="">
<input type="submit" value="send">
</form>
</body>
Then i have this code on the test1.html, that is supposed to send some new data back to test0:
<body>
<form action="test0.html">
<input type="text" name="array[2]" placeholder="val3" id="">
<input type="text" name="array[3]" placeholder="val4" id="">
<input type="submit" value="send back">
</form>
When i send data back to test0, i just get the newest data typed in test1.html. I'd like to know how to keep track of the ones sent previously from test0.
Thanks!
As the default form method is GET, the form parameters will be passed using the query parameters
So you can add a hidden input field to your form for each query parameters.
<body>
<form action="test0.html">
<input type="text" name="array[2]" placeholder="val3">
<input type="text" name="array[3]" placeholder="val4">
<input type="submit" value="send back">
</form>
<script>
(function() {
var form = document.querySelector("form");
var queryParams = new URLSearchParams(location.search);
for (var key of params.keys()) {
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = queryParams.get(key);
form.insertBefore(input, form.firstChild);
}
})();
</script>
</body>
You take the sent data and store it temporarily, so you can then pass it on to the following pages. Input fields of type hidden are suitable here.
<form action="test0.html">
<input type="hidden" name="array[0]" value="SUBMITTED_DATA">
<input type="hidden" name="array[1]" value="SUBMITTED_DATA">
<input type="text" name="array[2]" placeholder="val3" id="">
<input type="text" name="array[3]" placeholder="val4" id="">
<input type="submit" value="send back">
</form>
With this approach, you can not determine whether the data were subsequently edited! Here a signature can provide remedy.
When i try to obtain the values of input type=text is empty even though they are not. Any idea why?
var form_data = new FormData(document.getElementById('box')); // Creating object of FormData class
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
$("#search").click(function(){
console.log(cust_name) //they are empty even though it's not
console.log(order_num) //they are empty even though it's not
$.ajax({
url: "search.php",
method: "POST",
data: {cust_name: cust_name, order_num: order_num},
error: function (request, status, error) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + request.responseText + "</div>")
}
}).done(function(msg) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + msg + "</div>")
});
});
});
and here is my html code:
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>
You need to attach an event listener to the submit event of your form to get the values when the user submits. Here's a stripped down working example.
The problem with your code is that it runs right away when the page loads, and because JavaScript is a runtime language, it doesn't go back and update those variables with the current value.
You could also put those two variable declarations INSIDE your click handler (Shown in bottom solution).
Solution (Preferred)
document.getElementById('box').addEventListener('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
var cust_name = document.getElementById("cust_name").value;
var order_num = document.getElementById("order_num").value;
console.log(cust_name, order_num);
});
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
<button type="submit">Search</button>
</form>
Notes
I used <button> instead of <input type="button">
I passed this to FormData because we have a reference to it from the event handler
I used e.preventDefault() to stop the page from refreshing by default.
Solution (Minimal Code Change)
$("#search").click(function(){
var form_data = new FormData(document.getElementById('box'));
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
console.log(cust_name);
console.log(order_num);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>
What I am trying to accomplish: When a user inputs dates, number of adults ect it would dynamically add the info via javascript to the URL within the url variables. This is what I have so far: ( I am a Noob but trying to make it work )
<script type="text/javascript">
$(function () {
$('#submit').click(function() {
$('#button').click(function(e) {
var checkInDate = document.getElementById('checkInDate').value;
var checkInMonthYear = document.getElementById('checkInMonthYear').value;
var checkOutDate = document.getElementById('checkOutDate').value;
var checkOutMonthYear = document.getElementById('checkOutMonthYear').value;
var numberOfAdults = document.getElementById('numberOfAdults').value;
var rateCode = document.getElementById('rateCode').value
window.location.replace("http://www.Link.com/redirect?path=hd&brandCode=cv&localeCode=en®ionCode=1&hotelCode=DISCV&checkInDate=27&checkInMonthYear=002016&checkOutDate=28&checkOutMonthYear=002016&numberOfAdults=2&rateCode=11223");
window.location = url;
});
});
Ok, so first things first: You probably don't need to do this at all. If you create a form and add a name attribute to each input, then the submission automatically creates the URL for you. Fixed value fields can be set to type="hidden".
For this to work you need to use the "GET" method.
<form action="http://www.Link.com/redirect" method="GET">
<input type="hidden" name="path" value="hd"><br>
<input type="hidden" name="brandCode" value="cv"><br>
<input type="hidden" name="localeCode" value="en"><br>
<input type="hidden" name="regionCode" value="1"><br>
<input type="hidden" name="hotelCode" value="DISCV"><br>
<input type="text" name="checkInDate"><br>
<input type="text" name="checkInMonthYear"><br>
<input type="text" name="checkOutDate"><br>
<input type="text" name="checkOutMonthYear"><br>
<input type="text" name="numberOfAdults"><br>
<input type="text" name="rateCode"><br>
<input type="submit">
</form>
Clicking "Submit" changes the URL to the desired one.
If this does not suit your needs, you can replace parameters in the URL by following the advice in this SO answer: Answer Link
This is much better than trying to re-implement URL manipulation on your own.
I am working on a simple ASP.NET project. I have HTML and a JS file. I am trying to send the values of the form inputs to the JS file, but it seems to be broken for some reason.
My form looks like:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter">
</form>
and my JS is:
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
and the function that meant to use it:
function setTheClockByButton() {
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
If I put a number to the value in the HTML form it works fine(like this)
<span>Hours: </span><input type="text" id="fhours" value="3"><br>
but it not accepting any data from the keyboard.
And of course I have the onclick function associated to the form:
document.getElementById("send").onclick = setTheClockByButton;
(otherwise it'd make no sense).
Move those assignment statements inside the function:
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
setTheClock(setHour, setMinute, setSecond);
alert(setHour);
}
Now each time the button is clicked (and note that I'm assuming that part works, since you say it does), the values of the input fields will be fetched so that the clock update function is working with up-to-date values.
You need an onclick event:
<div class="set-the-clock">
<form name="settheclock">
<span>Hours: </span><input type="text" id="fhours" value=""><br>
<span>Minutes: </span><input type="text" id="fminutes" value=""><br>
<span>Seconds: </span><input type="text" id="fseconds" value=""><br>
<input type="button" id="send" value="Enter" onclick="setTheClockByButton()">
</form>
</div>
<script>
function setTheClockByButton() {
var setHour = document.getElementById("fhours").value;
var setMinute = document.getElementById("fminutes").value;
var setSecond = document.getElementById("fseconds").value;
alert(setHour);
}
</script>
I have a simple form like this:
<form method="post" id="login">
Username: <input type="text" value="" name="usr" />
Password: <input type="password" value="" name="pw"/>
<input type="submit" id="log" name="log" value="Login" style="width:250px;"/><br/>
</form>
But i keep getting cannot read property for my javascript with this line:
var usr = login.usr.value;
var pw = login.pw.value;
What is the reason i get this error ?
Try to give your form a name and change your code like below :
<form method="post" id="login" name="login">
Username: <input type="text" value="" name="usr" />
Password: <input type="password" value="" name="pw"/>
<input type="submit" id="log" name="log" value="Login" style="width:250px;"/><br/>
</form>
and the in your javascript :
var usr = document.login.usr.value;
You can check here (jsfiddle link).
<input type="text" value="" name="usr" /> does not magically become the variable login.usr, you need to define the value based on the DOM.
var usr = document.login.usr.value;
Try using getElementsByName:
The getElementsByName() method accesses all elements with the specified name.
var usr = document.getElementsByName('usr')[0].value;
var pw = document.getElementsByName('pw')[0].value;
http://jsfiddle.net/L3RvL/
Method 1:
<form method="post" id="login">
Username: <input type="text" value="" name="usr" />
var form = document.getElementById("login"); //DOM access
var usr = form.elements["usr"]; // Forms access
Method 2 - not valid xhtml:
<form method="post" name="login">
Username: <input type="text" value="" name="usr" />
var form = document.login; // Forms access
var usr = form.elements["usr"]; // Forms access
Method 3:
<form method="post">
Username: <input type="text" value="" name="usr" />
var usr = document.getElementsByName("usr")[0]; // first field on page named this
Method 4: - preferred these days since ID MUST be unique - less useful if there are more forms with usr on the page that needs same validation
<form method="post">
Username: <input type="text" value="" id="usr" name="usr" />
var usr = document.getElementById("usr");
Works in every browser:
document.forms["login"].elements["usr"].value;
document.forms["login"].elements["pw"].value;