Input in Javascript

A place to discuss the implementation and style of computer programs.

Moderators: phlip, Moderators General, Prelates

CortoPasta
Posts: 38
Joined: Fri Aug 15, 2008 5:51 pm UTC

Input in Javascript

Postby CortoPasta » Thu Oct 22, 2009 2:08 pm UTC

So this should be a retardedly easy question to answer, but when I look on W3 or run a google search, I can't find what I'm looking for. Basically, I'm just trying to teach myself Javascript to get my feet wet, and I can't figure out how to get an input from the user to use in an equation.

Code: Select all

<html>
<body>
<script type="text/javascript">
//take an input for x
//take an input for y
document.write((x+y));
</script>
</body>
</html>

Any ideas? I feel stupid for having to ask this.

User avatar
Cosmologicon
Posts: 1806
Joined: Sat Nov 25, 2006 9:47 am UTC
Location: Cambridge MA USA
Contact:

Re: Input in Javascript

Postby Cosmologicon » Thu Oct 22, 2009 2:20 pm UTC

There might be a better way, but I like to use the HTML element "input". You can give it an id, and then read from it using document.getElementById("myinput").value.

User avatar
Xanthir
My HERO!!!
Posts: 5423
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Input in Javascript

Postby Xanthir » Thu Oct 22, 2009 5:06 pm UTC

Two basic ways. The first, and worst, way is to use the prompt() function. It takes two arguments: some text to display as the prompt and a default value. It returns whatever the user entered. It's bad because it pops up a modal dialog, like alert(), which will prevent the user from doing anything else on the page, and in some browsers will prevent them from doing anything else on *any* page.

The better way is to leverage html for your needs. <input id=foo> on the page, then in the javascript use document.getElementByID("foo").value to retrieve the value of the input. Since you want to wait for the user to actually enter something, either put that code in an change event handler, or attach it to some click handler on a button.

I don't know how to do it in vanilla js (I refuse to learn DOM), but using jQuery you'd have something like this:

Code: Select all

<!DOCTYPE html>
<title>Test</title>
<script src="link/to/jquery.js"></script>
<script>
$(function(){
  $("#submit").click(function(){
    alert("Answer is " + ( parseInt($("#x").val(),10) + parseInt($("#y").val(),10) ) + "!");
  });
});
</script>
<p><label>X: <input id=x></label></p>
<p><label>Y: <input id=y></label></p>
<p><button id=submit>Calculate Sum!</button></p>
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

User avatar
ash.gti
Posts: 404
Joined: Thu Feb 07, 2008 1:18 am UTC
Location: Probably a coffee shop.

Re: Input in Javascript

Postby ash.gti » Thu Oct 22, 2009 5:17 pm UTC

Code: Select all

<script type="text/javascript">
var x = prompt('input a x:');
var y = prompt('input a y:');
document.write((x+y));
</script>



Although Xanthir's approach is better IMO.
# drinks WAY to much espresso

CortoPasta
Posts: 38
Joined: Fri Aug 15, 2008 5:51 pm UTC

Re: Input in Javascript

Postby CortoPasta » Thu Oct 22, 2009 6:25 pm UTC

Code: Select all

<!DOCTYPE html>
<title>Test</title>
<script src="link/to/jquery.js"></script>
<script>
$(function(){
  $("#submit").click(function(){
    alert("Answer is " + ( parseInt($("#x").val(),10) + parseInt($("#y").val(),10) ) + "!");
  });
});
</script>
<p><label>X: <input id=x></label></p>
<p><label>Y: <input id=y></label></p>
<p><button id=submit>Calculate Sum!</button></p>


This gives me two fields and a submit button, but nothing happens when submit is clicked

Code: Select all

<script type="text/javascript">
var x = prompt('input a x:');
var y = prompt('input a y:');
document.write((x+y));
</script>


This gives me 1+2=12 :-/ Man, I thought this was a basic question

User avatar
ash.gti
Posts: 404
Joined: Thu Feb 07, 2008 1:18 am UTC
Location: Probably a coffee shop.

Re: Input in Javascript

Postby ash.gti » Thu Oct 22, 2009 6:30 pm UTC

CortoPasta wrote:This gives me 1+2=12 :-/ Man, I thought this was a basic question


They are strings if you do the prompt.

You need to cast them to the data type you need, you can do x = parseInt(x); and y = parseInt(y);
# drinks WAY to much espresso

User avatar
Xanthir
My HERO!!!
Posts: 5423
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Input in Javascript

Postby Xanthir » Thu Oct 22, 2009 7:13 pm UTC

CortoPasta wrote:

Code: Select all

<!DOCTYPE html>
<title>Test</title>
<script src="link/to/jquery.js"></script>
<script>
$(function(){
  $("#submit").click(function(){
    alert("Answer is " + ( parseInt($("#x").val(),10) + parseInt($("#y").val(),10) ) + "!");
  });
});
</script>
<p><label>X: <input id=x></label></p>
<p><label>Y: <input id=y></label></p>
<p><button id=submit>Calculate Sum!</button></p>


This gives me two fields and a submit button, but nothing happens when submit is clicked

Are you just copypasting this code? Do you have jQuery? I thought my "link/to/jquery.js" was fake enough to draw notice.

Code: Select all

<script type="text/javascript">
var x = prompt('input a x:');
var y = prompt('input a y:');
document.write((x+y));
</script>


This gives me 1+2=12 :-/ Man, I thought this was a basic question

Yeah, as ash.gti says, prompt returns strings (so does my method). You have to turn it into an int, such as by using parseInt like I did in my example.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

eric.lifka
Posts: 10
Joined: Thu May 21, 2009 1:58 am UTC

Re: Input in Javascript

Postby eric.lifka » Thu Oct 22, 2009 8:04 pm UTC

Here's a way you could use it. It's standard javascript, so it uses the dom, but I think that's probably better for you since you're just tinkering.

Code: Select all

<html>
<head>
<title>Calculation</title>
<script type="text/javascript">

window.onload = function(evnt) {
   document.calcBox.onsubmit = function(e) {
      var x = parseInt(document.calcBox.xval.value);
      var y = parseInt(document.calcBox.yval.value);
      document.calcBox.response.value = x+y;
      return false;
   }
}

</script>
</head>
<body>

<form name="calcBox">
<input type="text" name="xval"></input><br />
<input type="text" name="yval"></input><br />
<input type="submit"></input><br />
<textarea name="response" cols=30 row=1></textarea>
</form>

</body>
</html>


it essentially assigns an onsubmit listener to the form so that whenever you click submit it calls that function. I wrapped the assignment of that function inside the window.onload function so that the form would exist when I tried to assign a listener to it. The function returns false because that's how you stop the submit process, otherwise the data would disappear right after you clicked submit.

User avatar
jaap
Posts: 2094
Joined: Fri Jul 06, 2007 7:06 am UTC
Contact:

Re: Input in Javascript

Postby jaap » Fri Oct 23, 2009 7:09 am UTC

eric.lifka wrote:I wrapped the assignment of that function inside the window.onload function so that the form would exist when I tried to assign a listener to it.


Is that necessary? As far as I can tell the code below would work just fine too, assigning the listener at the spot the form is created. I assume a sensible browser will not allow a form to be submitted before it has parsed the /form tag.

The main difference is that there is a small bit of script in the form itself so that it isn't all in one place, and that might be against your stylistic preference. I prefer this however because the "return false" is on the form rather than in the called function so that the reason for it is clearer.

Code: Select all

<html>
<head>
<title>Calculation</title>
<script type="text/javascript">

function addIt() {
  var x = parseInt(document.calcBox.xval.value);
  var y = parseInt(document.calcBox.yval.value);
  document.calcBox.response.value = x+y;
}

</script>
</head>
<body>

<form name="calcBox" onSubmit="addIt(); return false;">
<input type="text" name="xval"></input><br />
<input type="text" name="yval"></input><br />
<input type="submit"></input><br />
<textarea name="response" cols=30 row=1></textarea>
</form>

</body>
</html>

singlefin
Posts: 377
Joined: Mon Aug 04, 2008 3:12 pm UTC
Location: https://www.accountkiller.com/removal-requested
Contact:

Re: Input in Javascript

Postby singlefin » Fri Oct 23, 2009 10:35 am UTC

ash.gti wrote:You need to cast them to the data type you need, you can do x = parseInt(x); and y = parseInt(y);


Correct, although best practice dictates that when using parseInt(), you should specify the base of the numbers you're using:

Code: Select all

parseInt("11") //returns 11, but...
parseInt("011") // returns 9 the leading 0 specifies an octal number.
//If you're not actually after an octal number, this leads to vary protracted debugging sessions, so...
parseInt("011", 10) //returns 11 as you'd presumably expect - the second argument sets the numeric base

User avatar
Xanthir
My HERO!!!
Posts: 5423
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Input in Javascript

Postby Xanthir » Fri Oct 23, 2009 2:23 pm UTC

jaap wrote:Is that necessary? As far as I can tell the code below would work just fine too, assigning the listener at the spot the form is created. I assume a sensible browser will not allow a form to be submitted before it has parsed the /form tag.

The main difference is that there is a small bit of script in the form itself so that it isn't all in one place, and that might be against your stylistic preference. I prefer this however because the "return false" is on the form rather than in the called function so that the reason for it is clearer.

Yeah, assigning the handler with @onsubmit will work just fine. That's the best thing to do in some circumstances. I advocate learning proper unobtrusive javascript first, though, so you don't pick up bad habits and litter your code with on* attributes.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))

CortoPasta
Posts: 38
Joined: Fri Aug 15, 2008 5:51 pm UTC

Re: Input in Javascript

Postby CortoPasta » Fri Oct 23, 2009 4:32 pm UTC

eric.lifka wrote:Here's a way you could use it. It's standard javascript, so it uses the dom, but I think that's probably better for you since you're just tinkering.

Code: Select all

<html>
<head>
<title>Calculation</title>
<script type="text/javascript">

window.onload = function(evnt) {
   document.calcBox.onsubmit = function(e) {
      var x = parseInt(document.calcBox.xval.value);
      var y = parseInt(document.calcBox.yval.value);
      document.calcBox.response.value = x+y;
      return false;
   }
}

</script>
</head>
<body>

<form name="calcBox">
<input type="text" name="xval"></input><br />
<input type="text" name="yval"></input><br />
<input type="submit"></input><br />
<textarea name="response" cols=30 row=1></textarea>
</form>

</body>
</html>


it essentially assigns an onsubmit listener to the form so that whenever you click submit it calls that function. I wrapped the assignment of that function inside the window.onload function so that the form would exist when I tried to assign a listener to it. The function returns false because that's how you stop the submit process, otherwise the data would disappear right after you clicked submit.


Exactly what I'm looking for it to do, thank you eric.lifka!

Xanthir wrote:
CortoPasta wrote:

Code: Select all

<!DOCTYPE html>
<title>Test</title>
<script src="link/to/jquery.js"></script>
<script>
$(function(){
  $("#submit").click(function(){
    alert("Answer is " + ( parseInt($("#x").val(),10) + parseInt($("#y").val(),10) ) + "!");
  });
});
</script>
<p><label>X: <input id=x></label></p>
<p><label>Y: <input id=y></label></p>
<p><button id=submit>Calculate Sum!</button></p>


This gives me two fields and a submit button, but nothing happens when submit is clicked

Are you just copypasting this code? Do you have jQuery? I thought my "link/to/jquery.js" was fake enough to draw notice.


Zero knowledge of Javascript/jquery/etc. Just trying to learn about how to get user input and manipulate variables

User avatar
Xanthir
My HERO!!!
Posts: 5423
Joined: Tue Feb 20, 2007 12:49 am UTC
Location: The Googleplex
Contact:

Re: Input in Javascript

Postby Xanthir » Fri Oct 23, 2009 6:33 pm UTC

K, no problem. jQuery is a javascript library that makes a lot of the basic stuff, like selecting elements from the page and manipulating them, ridiculously easier. It also smooths over a lot of the browser differences, so you don't have to care whether your users have IE, Firefox, etc. You just program and it does the rest. Finally, it promotes a more functional approach by papering over a lot of the imperative APIs attached to javascript.

Go get it at jQuery.com. It's the most widely-used js library in the world for a reason.
(defun fibs (n &optional (a 1) (b 1)) (take n (unfold '+ a b)))


Return to “Coding”

Who is online

Users browsing this forum: No registered users and 9 guests