JavaScript Prompt

How do I get feedback from a user in JavaScript without implementing a form?

One way is to assign a prompt() method to a variable and then use the variable:

var answer = prompt("What's your favorite color?");

This works great for strings but how can I get it to work for numbers?

To get data as a number type you need to parse the data. Parsing converts a string type into a numeric type:

var answer = parseInt(prompt("Give me a number ranging from 0 to 10"));

You can also use parseFloat() for float point numbers.

Can a user select an object by writing the object’s name via a prompt window?

The data coming from a prompt box is of type string. A string is represented with quotes. In order to call an object, you need to strip the quotes. Assuming the object we pretend to call is on the Global scope (under object window), we can call its name by calling it as a window property.

After assigning a prompt response to the variable answer, we can re-point the variable to an object name (assuming the name of the object and the value of the variable match).

answer = window
;

Here’s a minimalistic example using window[prop]:

var tony = {
    name: "TONY"
};

Above I declared an object named tony (notice its lower case).
Below I create an independent method that can potentially be used by any object:

var message = function () {
    console.log("Hello, " + this.name +
        "! Thanks for your order today.");
};

Bellow I use prompt to ask for an object name, then the method message is called, passing the object name as the value to be applied to the message:

var newMessage = function () {
    var n = prompt("Please enter the object name");
    n = window[n];

    return message.call(n);
};

Call the newMessage() subroutine and use tony as an example:

newMessage();
//returns "Hello, TONY!Thanks for your order today."

If you have any difficult understanding call( ) read my other eBook JavaScript Objects Functions and Arrays Explained

Cool stuff!!

Link to Amazon ebook
eBook Solid Steps into javaScript
Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s