Reputation: 88
so I've tried this very hard but can't figure it out,
I have a button like this
<button onclick="signUp(document.getElementById('username').value,document.getElementById('email').value)">Sign up</button>
and I want to pass the values it's requesting from some inputs into a variable or variable array so I can handle them like this (example)
var signUp = function(e){
alert(e);
}
(This is just simplified but it proves my point!) Does anyone know how to do this though, I've been having a hard time figuring it out!
Thanks in advance, Magn0053
Upvotes: 1
Views: 3356
Reputation: 773
You can achieve this as such:
<button onclick="signUp({username:document.getElementById('username').value,email:document.getElementById('email').value})">Sign up</button>
In js, you can access them like:
var signUp = function(e){
console.log(e.username, e.email);
}
Upvotes: 0
Reputation: 58405
The most basic modification is to use []
around the values you are passing to signUp
.
var signUp = function(e) {
alert ("username:" + e[0]);
alert ("email:" + e[1]);
}
<input type="text" id="username">
<input type="text" id="email">
<button onclick="signUp([document.getElementById('username').value,document.getElementById('email').value])" id="submit">Sign up</button>
You don't really want to be using javascript in your DOM so first modify your signUp
function:
signUp = function() {
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
}
Finally, remove the onclick from your HTML entirely and replace it with this javascript:
document.getElementById('submit').onclick=signUp;
var signUp = function() {
var username = document.getElementById('username').value;
var email = document.getElementById('email').value;
alert("username:" + username);
alert("email:" + email);
}
document.getElementById('submit').onclick = signUp;
console.log("fred");
<input type="text" id="username">
<input type="text" id="email">
<button id="submit">Sign up</button>
Upvotes: 0
Reputation: 1002
You may take @adeneo's idea or, just send'em in an array like this
signUp([document.getElementById('username').value,
document.getElementById('email').value])
Upvotes: 1
Reputation: 1281
You can surround by { } to pass them as an object, or [ ] to pass them as an array. However, all of your arguments are document values, your function could just reference them itself.
Upvotes: 2