Skip to content Skip to sidebar Skip to footer

Jquery Store Input Value Into Empty Array Element

I have this array var foods = new Array(); foods = [ { id: 1, correct:'icecream', display: 'icecream', response: ''}, { id: 2, correct:'sundae', display: 's

Solution 1:

It helps to store the user's response in case you want to output a summary of how they did and what they typed for each one.

You need a function to check the input value with your list:

var checkInputValue = function () {
    trials[curTrial].response = input.val();    // store user's input into responseif (trials[curTrial].response === trials[curTrial].correct) {    // users input is equal to the correct textalert('Correct!');
    } else {
        alert('Incorrect!');
    }
    curTrial++;    // next trialshowTrial();
};

And I recommend you isolating the logic for showing a question, so you can call the same function for each qustion, I moved your code into here:

var curTrial = 0;
var input = $("#inputFoodChoice");
var container = $("#showfoods");
var prompt = $("#textPrompt");
var showTrial = function() {
    container.hide();
    if (curTrial < trials.length) {
        txtTrial = trials[curTrial].display;
    } else {
        alert("No more questions left.");
    }
    prompt.html(txtTrial);
    container.show();
    input.val('');
    input.focus();        
}; 

See fiddle: http://jsfiddle.net/amyamy86/jSyfy/

My example uses a button click to trigger the checkInputValue(), you can change it for your needs and attach the keydown/keypressed event for the enter key.

Post a Comment for "Jquery Store Input Value Into Empty Array Element"