1
votes

I'm trying to get the value of input select option without submitting the form (need to keep it available while displaying the live results). I then need to use this value with a global variable to be inserted in an array later on. Because I can't use submit, I need to find a way to update this value if the user changes the option (ie probably using onchange).

Here's what I have currently (doesn't work):

html

<select id="color" >
    <option value="">select:</option>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="yellow">Yellow</option>
</select>


javascript

document.getElementById('color').onchange = function() {
    var colorInput = this.value;
    console.log(colorInput);
};


updated

Okay, no using inline javascript, I get it. I updated the script above to reflect most of the answers I'm getting - which are not addressing my central problem. Tracking the input option value within the script is no problem; I need to the value as a global variable. For some reason I can't do it.

Here's a jsfiddle that is analogous to how I need to use it: http://jsfiddle.net/agvRn/2/

It should be able to track the select option (already can) and then must be able to use this value in a separate function - in this case inserting it into the paragraph field "show".

3

3 Answers

2
votes

Don't use inline JavaScript.

Try this (avoiding global variables):

(function() {
    var select_val;
    document.getElementById('color').addEventListener('change', function() {
        select_val = this.value;
        document.getElementById("show").innerHTML = select_val;
    }, false);

})();

DEMO

1
votes

Firstly, I would suggest you don't use the inline onchange attribute.

You can try this (see the jsfiddle):

document.getElementById('color').onchange = function() {
    var color = this.value;

    console.log(color);
};

Better yet, use addEventListener:

document.getElementById('color').addEventListener('change', function() {
    var color = this.value;

    console.log(color);
});
0
votes

you may try

var  colorInput;    
function colorCalc(value) {
    colorInput = value;
    console.log(colorInput);
}

i think the issue is that you are trying to set the var from the method return but at the time you call the method you are not giving it a value

instead you should let the method set you value when the change event triggers it with the selected value

function colorCalc(value) {
    return value;
}
var colorInput = colorCalc(/*there is no value here value == undefined so will return undefined*/);
console.log(colorInput);