简体   繁体   中英

Javascript: how do I take my users input data and turn it into an object?

I have a to-do list that I want I can receive user input on via html text boxes. The information is currently printed under these text boxes in an un-ordered list form after a button is clicked.

Its not perfect, that said I skipped a step, I want to take the strings the user inputs with button click and add them first to this function.

function task(task_text, date, time) 

The purpose of this of course is to trade the objects properties throughout the code later.

So, how would I go about taking the information in the text boxes and submit it to the above function on click of the button?

The Fiddle http://jsfiddle.net/brendanjackson/j501hc1k/1/

Getting the input onclick

To get this input into the function you must listen for the onclick event.

var input_text = document.getElementById('input_text').value;
var input_date = document.getElementById('input_date').value;
var input_time = document.getElementById('input_time').value;

onclick="task(input_text, input_date, input_time);"


how do I take my users input data and turn it into an object?


When your function is called, you can then create an object from the data passed in, like so:

var inputs = [];
function task(task_text, date, time) {
    input.push({
        task_text: task_text,
        date: date,
        time: time
    });
}

or if you are only planning to accept one input, you could just do this:

var obj = {};
function task(task_text, date, time) {
    obj.task_text: task_text,
    obj.date: date,
    obj.time: time
}

Fiddle: http://jsfiddle.net/KyleMuir/3rh4u7qu/1/

I think this is what you're after:

function task(text, date, time) {
    this.text = text;
    this.date = date;
    this.time = time;
}

function buttonClicked() {
    var myText = document.getElementById('myText');
    var input_text = document.getElementById('input_text').value  ;
    var input_date = document.getElementById('input_date').value  ;
    var input_time = document.getElementById('input_time').value  ;
    var item = new task(input_text, input_date, input_time);
        myText.innerHTML += "<li>"+item.text+" "+item.date+" "+item.time+"</li>";
}

Also, added a slightly more interesting use of your task object here which might be useful from a learning perspective: http://jsfiddle.net/KyleMuir/3rh4u7qu/2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM