简体   繁体   中英

Javascript array length through user input

I have a problem in Javascript I want to make a form which have one input text field and one button when I click on the button window.prompt is called.

It will prompt depend upon my array length but I want array length get through input text field when I write 10 it will prompt 10 times when I write 2 it will prompt 2 times.

How can i write this type of query?

I tried this code but its not working.

words = new Array (4);
function a() {
    for ( k = 0 ; k < words.length ; k = k + 1 ) {
        words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
    }
}

Maybe you forgot to call your function a() .

Some remarks about your code:

  • You don't have to specify an initial array size, eg words = [] or words = new Array() is enough.
  • Also k=k+1 is usually written as k++ .

A remark about asking questions:

  • Use punctuation to make sentences! Your whole question is one sentence.

Hopefully it's just the snippet of code but I hope you are using var somewhere to declare all those variables.

Otherwise this should do the trick, however not sure what you are trying to achieve but this sounds like a bad user experience.

Here is the jsffidle http://jsfiddle.net/R2bCz/1/

function Handler(event) {
    var count = event.target.value;
    var i = 0;
    var words = [];
    var word;

    for (; i < count; i++) {
        word = window.prompt("Enter word # " + i, "");
        words.push(word);
    }
}

$("#multi").on("change", Handler);

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