JavaScript putting two variable's value into an array - javascript

i have two variables name and location which are provided by two <input type="text">. I need to get an outcome of Smith_California but I am getting an output of userName_userLoca in the console.
Any suggestions would help.
currently, I have:
HTML:
<form class="inputContainer" id="inputContainer" methed="post">
<label for="userNam">Your Name</label>
<input type="text" class="userNam" id="userNam" name="userNam" />
<label for="userLoca">Your Location</label>
<input type="text" class="userLoca" id="userLoca" name="userLoca" />
<button class="vButton" id="vButton" type="submit" onclick="testfun()">
Begin Test
</button>
</form>
Javascript:
var userName = document.getElementById('userNam');
var userLoca = document.getElementById('userLoca');
var userSID = ['userName', 'userLoca'];
console.log(userSID.join('_'));

Remove the quotes and use .value:
var userSID = [userName.value, userLoca.value];

You are accessing dom-element, using var userName = document.getElementById('userNam');.
Try with var userName = document.getElementById('userNam').value.
Also remove the quotes from var userSID = ['userName', 'userLoca']; and use it like below
var userSID = [userName, userLoca];

Related

JQuery select name array with unknown id

I have multiple inputs as an array like this:
<input name="data[extras][1][id]" value="1">
<input name="data[extras][1][netto]">
<input name="data[extras][1][tax]">
<input name="data[extras][1][brutto]">
<input name="data[extras][2][id]" value="2">
<input name="data[extras][2][netto]">
<input name="data[extras][2][tax]">
<input name="data[extras][2][brutto]">
i got all extras with:
let extras = $('input[name^=data\\[extras\\]]');
now i would like to iterate through all to create an array out of it but i need for the id for further actions (the 1 or the 2).
i would like to achive something like this:
let id = $('input[name^=data\\[extras\\]\\[UNKNOWN ID\\]\\[id\\]]').val();
i hope anybody can help me.
Greetings
you can receive all ids in jquery like this
$('document').ready(function(){
var values = $('input[name$=\\[id\\]]').map(function(){return $(this).val();}).get();
console.log(values); });
Maybe you could loop trough the inputs and in the loop get the id/index via regexp from the name attribute to query that [id] input?
data\[extras\]\[(\d)\]
Unclear what your expected output would be, but you can easily loop over the collection of elements and parse out the number and the string.
var inputs = document.querySelectorAll('[name^="data\[extras\]"]');
const grouped = Array.from(inputs).reduce(function(o, input) {
const parts = input.name.match(/^data\[extras\]\[(\d+)\]\[(.*)\]$/);
const index = parts[1];
const key = parts[2];
o[index] = o[index] || {};
o[index][key] = input.value;
return o;
}, {});
console.log(Object.values(grouped))
<input name="data[extras][1][id]" value="1-i">
<input name="data[extras][1][netto]" value="1-n">
<input name="data[extras][1][tax]" value="1-t">
<input name="data[extras][1][brutto]" value="1-b">
<input name="data[extras][2][id]" value="2-i">
<input name="data[extras][2][netto]" value="2-n">
<input name="data[extras][2][tax]" value="2-t">
<input name="data[extras][2][brutto]" value="2-b">

How can I access these form values?

I want to create a form where I will perform an operation with the values entered by the user, but when the function runs, I get NaN return. Thank you in advance for the help.
function test() {
var age = document.getElementsByName("person_age").value;
var weight = document.getElementsByName("person_weight").value;
var size = document.getElementsByName("person_size").value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>`
Output:
NaN
When I get the values from the user and run the function, I get NaN feedback. how can i solve this problem.
There are multiple errors that you have to correct
1) When you use getElementsByName, It will return NodeList array like collection. So you have to get the element by using index as:
var age = document.getElementsByName( "person_age" )[0].value;
2) If you need sum of all three value then you have to convert it into Number type because document.getElementsByName( "person_age" )[0] give you value in String type. So you can do as:
+document.getElementsByName( "person_age" )[0].value
function test() {
var age = +document.getElementsByName("person_age")[0].value;
var size = +document.getElementsByName("person_size")[0].value;
var weight = +document.getElementsByName("person_weight")[0].value;
document.getElementById("result").innerHTML = weight + size + age;
}
<form>
<input type="text" name="person_age">
<input type="text" name="person_size">
<input type="text" name="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
Just a Suggestion: You can use Document.getElementById if you want to directly access the value. Just add an ID property in your element. It will return a string value, convert that to int and you're good to go.
function test() {
var age = document.getElementById("person_age").value;
var weight = document.getElementById("person_weight").value;
var size = document.getElementById("person_size").value;
document.getElementById("result").innerHTML = parseInt(weight) + parseInt(size) + parseInt(age);
}
<form>
<input type="text" name="person_age" id="person_age">
<input type="text" name="person_size" id="person_size">
<input type="text" name="person_weight" id="person_weight">
<input type="button" value="calculate" onclick="test();">
</form>
<h3 id="result"></h3>
getElementsByName will always return an array-like nodelist so, if you were to use it you would need to access the first index [0]. Instead add a class to each input and use querySelector to target it.
The value of an input will always be a string (even if the input is type "number"), so you need to coerce it to a number, either by using Number or by prefixing the value with +.
So, in this example I've updated the HTML a little by adding classes to the inputs, and changing their type to "number", and removing the inline JS, and updated the JS so that the elements are cached outside of the function, an event listener is added to the button, and the values are correctly calculated.
// Cache all the elements using querySelector to target
// the classes, and add an event listener to the button
// that calls the function when it's clicked
const ageEl = document.querySelector('.age');
const weightEl = document.querySelector('.weight');
const sizeEl = document.querySelector('.size');
const result = document.querySelector('#result');
const button = document.querySelector('button');
button.addEventListener('click', test, false);
function test() {
// Coerce all the element values to numbers, and
// then display the result
const age = Number(ageEl.value);
const weight = Number(weightEl.value);
const size = Number(sizeEl.value);
// Use textContent rather than innerHTML
result.textContent = weight + size + age;
}
<form>
<input type="number" name="age" class="age" />
<input type="number" name="size" class="size" />
<input type="number" name="weight" class="weight" />
<button type="button">Calculate</button>
</form>
<h3 id="result"></h3>`

HTML Form input into Javascript array

My goal is to enter a single name into a html Text form. Each time I press submit
it will store that value into a javascript array. Currently, I am able to get
the first value I submit into the array but not the subsequent values. Hope I am
being clear enough, Any help would be great.
Here is my JavaScript
function getListOfNames() {
"use strict";
//Declare variables
var form;
var getNameValue;
var myArray = [];
var output;
//Assign values
output = document.getElementById("myTable");
form = document.getElementById("myForm");
getNameValue = form.getNameValue.value;
//Each time form is submited put the new value into array
myArray.push(getNameValue);
//output the results
output.innerHTML = myArray;
}
function project5Part2() {
"use strict";
// Your code goes in here.
getListOfNames();
return false;
}
Here is my HTML
<form id="myForm" action="#" onsubmit=" return project5Part2();" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<input type="submit" value="Enter Name" />
<input type="reset"  value="Clear form - DO NOT SEND" />
</form>
Remove the onsubmit from the form.
change the input type="submit" into a regular button and use the onclick to execute JavaScript.
<form id="myForm" action="#" >
<label for="firstName">Enter Name</label>
<input type="text" id="enteredName" name="getNameValue"/>
<button type="button" onclick="project5Part2();">Enter Name</button>
<input type="reset" value="Clear form - DO NOT SEND" />
</form>
Create or use a global array (cannot be enclosed in the method if you want to persist)
When the button is clicked, checked the value of the textbox and if not empty, add the value to the array.
var myArray = new Array();
function project5Part2() {
var name = document.getElementById('enteredName').value;
if (!(typeof name === 'undefined') && name!=null && name.trim()!='') {
myArray.push(name);
}
console.log(myArray);
document.getElementById('enteredName').value = '';
}
Will log the contents of the array each time the button is clicked.
For example: ["albert", "manny", "susan"]
The textbox value is being cleared each time the name is added.

HTML Form into Javascript Variable

I'm reasonably new to Javascript so sorry if this has a simple answer.
I would like to make the name that a user inputs in a form into a javascript variable. For example, If the user inputs the name 'James' into the form, I would like the variable 'ans1' to be equal to the string 'James'. Heres my code...
<form>
Name:
<input type="text" id="username" />
<input type="submit" value="Submit" onClick="makeans1()" />
</form>
<script>
function makeans1() {
var ans1 = document.getElementById.value('username');
alert(ans1);
}
</script>
The reason I have added an alert is to check to see if the code has worked. Any help would be very much appreciated. Thanks
The correct code should be:
var ans1 = document.getElementById('username').value;
And always put your alert() 's at the beginning of the function. if you want to test function-hit :)
Just replace below line
var ans1 = document.getElementById.value('username');
with
var ans1 = document.getElementById('username').value
Change: var ans1 = document.getElementById.value('username');.
To: var ans1 = document.getElementById("username").value;.
function makeans1() {
var ans1 = document.getElementById("username").value;
alert(ans1);
}
<form>
Name:
<input type="text" id="username" />
<input type="submit" value="Submit" onClick="makeans1()" />
</form>

getElementByName validation

I know how to get fields to validate with JavaScript using methods such as getElementById etc. For this instance I need to use the getElementByName method. I have the error 'Cannot read property 'nodeValue' of null in console.log.
Here is code that I used with the getElementByName method which worked
HTML
<button name="button1">Hello</button>
<div class="form-row">
<div class="field w100">
<label for="primary_phone">Primary phone (digits only) *</label>
<input type="text" name="primary_phone" id="primary_phone" placeholder="hello"></input>
</div>
</div>
<div class="form-row">
<label for="confirm_phone">Confirm phone (digits only) *</label>
<input type="text" name="confirm_phone" id="confirm_phone"></input>
</div>
</div>
JavaScript
var btn1 = document.getElementsByName('button1')[0];
var btn1Text = btn1.firstChild.nodeValue;
console.log(btn1Text);
Below is the code that is returning the error.
HTML
<button id="button">Button</button>
JavaScript
function validate() {
var primaryNo = document.getElementsByName('primary_phone')[0];
var confirmNo = document.getElementsByName('confirm_phone')[0];
var primaryValue = primaryNo.firstChild.nodeValue;
var confirmValue = confirmNo.firstChild.nodeValue;
if (primaryValue !== confirmValue) {
alert('Numbers do not match');
} else {
alert('congratulations')
}
};
var btn = document.getElementById('button');
btn.addEventListener('click', validate, false);
Any ideas?
Looks like you might be having input fields whose value you are trying to fetch.
In that case, they don't have any child elements, instead you need to get their value like
var primaryValue = primaryNo.value;
var confirmValue = confirmNo.value;
What is the result of
var btn1 = document.getElementsByName('button1')[0];
in console (console.log(btn1);) ?
Be careful with tag names: button, button1... maybe you have a syntax mistake.

Categories

Resources