Liam
Liam

Reputation: 9855

Input type values into variables

Im trying to define variable values from values inputted into an input textfield onkeyup. I've never done this before and cant find it on Google so was wondering if anybody had any idea on how to do this...

<input type="text" id="values" />

var numberone = "";
var numbertwo = "";
var numberthree = "";

Imagine the user types into the input box "thomas the tankengine" thomas would become 'var numberone'. 'the' would become number two and so on...

Is this possible?

Upvotes: 1

Views: 74

Answers (3)

Jasper
Jasper

Reputation: 76003

How about saving each word in an index of an array so you can have a dynamic number of words:

var max_words = 3;
$('#values').on('keydown', function (event) {
    if (event.keyCode == 32) {//32 == space key
        var arr = $(this).val().split(' '),
            len = max_words < arr.length ? max_words : arr.length,
            out = [];
        for (var i = 0; i < len; i++) {
            out.push(arr[i]);
        }
    }
});

Here is a jsfiddle to demonstrate this code: http://jsfiddle.net/r8dXw/1/ (Note that the output is logged via console.log so check your console to see the output)

Upvotes: 0

Russell
Russell

Reputation: 17719

You can split a string by spaces using the split() function

eg

var words = document.getElementById("values").value.split(' ');
var op1 = words[0];
...

Upvotes: 1

Quentin
Quentin

Reputation: 943585

Possible, but unwise and would require messing about with eval if you didn't want the variables to end up in the global scope.

Any time you variable variables can solve a problem, it can be better solved by using an array (for sequential data) or object (for named data).

This is exactly the sort of job that arrays are designed to handle.

var numbers = document.getElementById('values').value.split(' ');
console.log(numbers[0]);
console.log(numbers[1]);
console.log(numbers[2]);

Upvotes: 0

Related Questions