Push elements in array from html form - javascript

I'm trying to get user input from an html form into an array, by using getElementsByClassName.
It works using getElementsById("...").value and then push it into the empty array. But when I try to do it with getElementsByClassName, I get a htmlcollection returned and something seems to go wrong. It doesn't register the user input.
Any help is strongly appreciated, I've been trying to find a solution all day...
<title>Word Input</title>
<form>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<button id="submit"> Submit </button>
</form>
<script>
document.getElementById("submit").addEventListener("click", handler9);
function handler9() {
let vocabEnglish = [];
let englishWords = document.getElementsByClassName("englishWord");
for (let i = 0; i < englishWords.length; i++) {
let englishWord = englishWords[i].innerText;
vocabEnglish.push(englishWord);
}
}
console.log(vocabEnglish);
</script>
I expect the words to be pushed into an array, but I get returned an empty one.

A few issues:
Your indentation is off, and putting it right reveals that the console.log happens outside of the function that has the local variable vocabEnglish. So obviously it is undefined outside the function.
The value of an input element is not retrieved via the innerText property, but value.
When you click the button the form is submitted, and a reload of the page happens, whereby you lose the output. Cancel the submission with e.preventDefault
Corrected code:
document.getElementById("submit").addEventListener("click", handler9);
function handler9(e) {
let vocabEnglish = [];
let englishWords = document.getElementsByClassName("englishWord");
for (let i = 0; i < englishWords.length; i++) {
let englishWord = englishWords[i].value;
vocabEnglish.push(englishWord);
}
console.log(vocabEnglish);
e.preventDefault()
}

use value instead of innerText
I've made an example here, it still prints to the console for you to view.
document.getElementById("submit").addEventListener("click", handler9);
function handler9() {
let vocabEnglish = [];
let englishWords = document.getElementsByClassName("englishWord");
for (let i = 0; i < englishWords.length; i++) {
let englishWord = englishWords[i].value;
vocabEnglish.push(englishWord);
}
console.log(vocabEnglish);
}
<form>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<button id="submit"> Submit </button>
</form>

<form>
<input type="text" class="englishWord"> <input type="text" class="spanishWord">
<br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord">
<br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord">
<br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord">
<br> <br>
<input type="text" class="englishWord"> <input type="text" class="spanishWord"> <br> <br>
<button id="submit"> Submit </button>
</form>
<script>
document.getElementById("submit").addEventListener("click", handler9);
function handler9() {
let vocabEnglish = [];
let englishWords = document.getElementsByClassName("englishWord");
for (let i = 0; i < englishWords.length; i++) {
let englishWord = englishWords[i].value;
vocabEnglish.push(englishWord);
}
}
console.log(vocabEnglish);
</script>

Related

Extract name attribute for multiple input fields and store in an array without using for loop

I have a form with multiple fields each has a name attribute, how can I extract these name attributes and store in an array or something for future use?
var inputs = $("input[type='text']"),
outputs = [];
$("#submit").click(function() {
inputs.each(function() {
outputs.push(inputs.attr("name"));
});
console.log(outputs)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="Forename">
Forename
</label>
<input type="text" id="Forename" name="forename">
</div>
<div>
<label for="Middlename">
Middle Names
</label>
<input type="text" id="Middlename" name="middlename">
</div>
<div>
<label for="Lastname">
Lastname
</label>
<input type="text" id="Lastname" name="lastname">
</div>
<p id="message"></p>
<input type="button" id="submit" value="submit">
outputs is still empty after clicking the button, why are the strings not being pushed into the empty array?
inputs is a jQuery collection. You will get the first element of that collection every time you only access inputs But if you loop over inputs with each, then $(this).attr("name) or this.name will return the attribute of each element
PS: .each IS a for loop - here is some of the code from the jQuery.js file
if ( isArrayLike( obj ) ) {
length = obj.length;
for ( ; i < length; i++ ) {
if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) {
break;
}
}
}
You have several possibilities
$(this).attr("name") or this.name
var $inputs = $("input[type='text']"),
outputs = [];
$("#submit").click(function() {
$inputs.each(function() {
outputs.push($(this).attr("name")); // $(this) is the input; this.name works too
});
console.log(outputs)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="Forename">
Forename
</label>
<input type="text" id="Forename" name="forename">
</div>
<div>
<label for="Middlename">
Middle Names
</label>
<input type="text" id="Middlename" name="middlename">
</div>
<div>
<label for="Lastname">
Lastname
</label>
<input type="text" id="Lastname" name="lastname">
</div>
<p id="message"></p>
<input type="button" id="submit" value="submit">
accessing the input's DOM node using the parameters passed to the function
var inputs = $("input[type='text']"),
outputs = [];
$("#submit").click(function() {
inputs.each(function(_,inp) { // inp is the DOM node
outputs.push(inp.name);
});
console.log(outputs)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="Forename">
Forename
</label>
<input type="text" id="Forename" name="forename">
</div>
<div>
<label for="Middlename">
Middle Names
</label>
<input type="text" id="Middlename" name="middlename">
</div>
<div>
<label for="Lastname">
Lastname
</label>
<input type="text" id="Lastname" name="lastname">
</div>
<p id="message"></p>
<input type="button" id="submit" value="submit">
Use a map:
let outputs;
$("#submit").click(function() {
outputs = $("input[type='text']").map((_,inp) => inp.name).get()
console.log(outputs)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<label for="Forename">
Forename
</label>
<input type="text" id="Forename" name="forename">
</div>
<div>
<label for="Middlename">
Middle Names
</label>
<input type="text" id="Middlename" name="middlename">
</div>
<div>
<label for="Lastname">
Lastname
</label>
<input type="text" id="Lastname" name="lastname">
</div>
<p id="message"></p>
<input type="button" id="submit" value="submit">

Calculate Text box values of form after submit html

I am trying to design a form. which takes input and after clicking on calculate gives output.
text field 'State' accepts only 2 uppercase letters
I am stuck in creating Calculate button.
The calculate button needs to determine the number of miles traveled by the customer and the total charge due from the customer.
below is my form:
function ValidateData() {
var InputText = document.getElementById('state').value;
var Expression = /^[zA-Z]*$/
if (InputText.search(Expression) == -1) {
alert("Must contain only A-Z");
return false;
}
}
body {
background-color: powderblue;
}
.upper {
text-transform: uppercase;
}
<!DOCTYPE html>
<html>
<head><b>Calculate Rental Charges</b></head><br>
<body>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="">
<br> Address:
<br>
<input type="text" name="address" value="">
<br> city:
<br>
<input type="text" name="city" value="">
<br> State:
<br>
<input type="text" id="state" name="State" cssclass="upper" value="">
<br> Zip code:<br>
<input type="text" name="zipcode" value="">
<br> Beginning odometer reading(in miles):<br>
<input type="text" name="zipcode" value="">
<br> Ending odometer reading(in miles):<br>
<input type="text" name="zipcode" value="" maxlength="10">
<br>
<br>
<input type="submit" value="Submit" OnClientClick="return ValidateData()">
</form>
I have designed one script which validates that state should have only upper case letters.
I want to calculate no. of miles driven which can be done by getting difference of starting miles and ending miles.
For calculating the total charge due from the customer.:
i have to use a constant for the $15 per day charge and the $0.12 mileage rate.
IS there any way to get all this result on single click of submit button.
I created 2 input fields, one to store the total distance and other one is to store the cost. Both are disabled.
Add a button to calculate.
Then add a function like this and call it on button click.
function calc(){
var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
document.getElementById("result").value=totalMile;
var cost=(totalMile*0.12)+15
document.getElementById("cost").value='$'+cost;
}
function ValidateData() {
var InputText = document.getElementById('state').value;
var Expression = /^[A-Z]*$/
if (InputText.search(Expression) == -1) {
alert("Must contain only A-Z");
return false;
}
}
function calc(){
var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
document.getElementById("result").value=totalMile;
var cost=(totalMile*0.12)+15
document.getElementById("cost").value='$'+cost;
}
body {
background-color: powderblue;
}
.upper {
text-transform: uppercase;
}
<!DOCTYPE html>
<html>
<head><b>Calculate Rental Charges</b></head><br>
<body>
<form method="post" action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="">
<br> Address:
<br>
<input type="text" name="address" value="">
<br> city:
<br>
<input type="text" name="city" value="">
<br> State:
<br>
<input type="text" id="state" name="State" cssclass="upper" value="">
<br> Zip code:<br>
<input type="text" name="zipcode" value="">
<br> Beginning odometer reading(in miles):<br>
<input type="text" name="startMile" value="">
<br> Ending odometer reading(in miles):<br>
<input type="text" name="endMile" value="" maxlength="10">
<br>
<button type="button" onclick="calc();">Calc</button>
<br />
Total Miles : <br />
<input disabled id="result" />
<br />
Total Cost <br />
<input disabled id="cost" />
<br />
<br>
<input type="submit" value="Submit" Onclick="return ValidateData();">
</form>

Form input ng-value seems filled but is empty

I am building an AngularJS app. I have a problem with a form that is filled with ng-value.
The input field is filled in, the user can see text but when the user presses the 'change' button it becomes undefined. Any thoughts?
My controller code:
// Fictional data it wineById will be a JSON object.
$scope.wineById = {"id":"4","name":"fdfvs1","percentage":"vcxz1"}
$scope.edit = function () {
var wine = {
id:$scope.wineById.id,
name:$scope.name,
percentage:$scope.percentage
};
console.log($scope.name, $scope.percentage);
};
HTML:
<form novalidate ng-submit="edit()">
<label>ID wine: <input type="text" ng-value="wineById.id" ng-model="id" ng-disabled="true"></label> <br>
<label>Name wine: <input type="text" ng-value="wineById.name" ng-model="name"></label> <br>
<label>Percentage wine: <input type="text" ng-value="wineById.percentage" ng-model="percentage"></label> <br>
<input type="submit" value="Change">
</form>
Case 1:
Got existing input in my fields. Pressing the button without changing the input data in the fields. Everything becomes undefined.
Case 2 (the one that works):
Got existing input in my fields. Changing all the fields with different data and pressing the button. Everything is changed.
How can I fix case 1?
Change your html as following if you still want to use ng-value for whatever reason:
<form novalidate ng-submit="edit()">
<label>ID wine:
<input type="text" ng-init="id=wineById.id" ng-model="id" ng-value="wineById.id" ng-disabled="true">
</label>
<br>
<label>Name wine:
<input ng-init="name=wineById.name" type="text" ng-value="wineById.name" ng-model="name">
</label>
<br>
<label>Percentage wine:
<input ng-init="percentage=wineById.percentage" type="text" ng-value="wineById.percentage" ng-model="percentage">
</label>
<br>
<input type="submit" value="Change">
</form>
Better approach would be to use just ng-model (unless you don't want two way binding)
<form novalidate ng-submit="edit()">
<label>ID wine:
<input type="text" ng-model="wineById.id" ng-disabled="true">
</label>
<br>
<label>Name wine:
<input type="text" ng-model="wineById.name">
</label>
<br>
<label>Percentage wine:
<input type="text" ng-model="wineById.percentage">
</label>
<br>
<input type="submit" value="Change">
</form>
Live Demo
Why you are using ng-value, angular supports two way binding, ng-model is enough for binding data.
<form novalidate ng-submit="edit()">
<label>ID wine: <input type="text" ng-model="id" ng-disabled="true"></label> <br>
<label>Name wine: <input type="text" ng-model="name"></label> <br>
<label>Percentage wine: <input type="text" ng-model="percentage"></label> <br>
<input type="submit" value="Change">
</form>

undefined field javascript loop

I'm trying to use ajax with a form I'm working on, and to do so I am building a post string,
Which looks like this: field_name=field_value&field_name=field_value and so on..
I am having trouble with figuring out where "undefined" is coming from. Take a look at this screenshot
If you look carefully, you'll see the loop I am using, outputs "undefinedemail=Emailpassword=Password" instead of "email=Email&password=Password"
Here is the stripped version of the form & javascript I am using:
<form id="signup_form" enctype="multipart/form-data" action="register.php" method="post">
<input name="email" type="text" value="Email"/>
<input name="password" type="text" value="Password"/>
<input name="email_confirm" type="text" value="Confirm Email"/>
<input name="password_confirm" type="text" value="Confirm Password"/>
<input name="first_name" type="text" value="First Name"/>
<input name="country" type="text" value="Country"/>
<input name="birthday" type="text" value="Birthday DD/MM/YYYY"/>
<input name="last_name" type="text" value="Last Name"/>
<input name="city" type="text" value="City"/>
<input name="profession" type="text" value="Profession"/>
<input type="radio" name="gender" value="Male"><span>Male</span>
<input type="radio" name="gender" value="Female"><span>Female</span>
<input type="checkbox" name="user_type" value="User type" /><span>Checkbox</span>
<button type="submit" name="submit" class="" id="submit">Sign up</button>
</form>
javascript:
var post_string;
var input = document.forms["signup_form"].getElementsByTagName("input");
for(var i = 0; i < input.length; i++) {
post_string += input[i].name + "=" + input[i].value;
if(i > 0 && i < input.length) { post_string += "&"; }
}
Thanks for helping !
You did forget to initialize your accumulator variable with the empty string, so the first time you appended something it evaluated to undefined. Use
var post_string = "";
It looks as if you're declaring post_string as an undefined variable, instead of declaring it as an empty string e.g. var post_string = "".
That means, for the first look-up of post_string, it's returning the undefined variable instead.

Form field quantity up/down buttons, don't allow negative numbers?

http://jsfiddle.net/KYDPd
Is there a way to make the minimum number be 0, and not allow the user to go below 0 when clicking down?
<form>
<input type="text" name="name" value="0" />
<input type="button" value="up" onclick="this.form.name.value++;" >
<input type="button" value="down" onclick="this.form.name.value--;">
</form>
If separate buttons are not necessary and HTML5 is an option you could just use this:
<form>
<input type="number" min="0" name="name" value="0" />
</form>
This should do the trick. Check what the value is before you allow each operation. Also added an onchange to the text input to inforce your minimum 0 requirement. Agree with other answer that this should be in a function though.
http://jsfiddle.net/xqV6V/1/
<form>
<input type="text" name="name" value="0" onchange="if(this.value<0){this.value=0;}" />
<input type="button" value="up" onclick="if(this.form.name.value>=0){this.form.name.value++;}" >
<input type="button" value="down" onclick="if(this.form.name.value>0){this.form.name.value--};">
</form>
You should probably put this JavaScript in a function.
<form>
<input type="text" name="name" value="0" />
<input type="button" value="up" onclick="this.form.name.value++;" >
<input type="button" value="down" onclick="if(this.form.name.value>0)this.form.name.value--;">
</form>
Additional Answer with functions.
<script>
function ud_find_text(self) {
var children = self.parentNode.getElementsByTagName('input');
for (var i = 0; i < children.length; i++) {
if (children[i].getAttribute('type') == 'text') {
return children[i];
}
}
}
function ud_inc(self) {
var text = ud_find_text(self);
text.value++;
}
function ud_dec(self) {
var text = ud_find_text(self);
if (text.value > 0) text.value--;
}
</script>
<form>
<input type="text" name="name" value="0" />
<input type="button" value="up" onclick="ud_inc(this)" >
<input type="button" value="down" onclick="ud_dec(this)">
</form>

Categories