最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Okay to call prompt() this way? - Stack Overflow

programmeradmin1浏览0评论

Is it okay to call prompt this way:

  prompt('Enter your text here');

instead of:

  prompt('Enter your text here', '');

I.e. without passing a suggested input to it?

Is it okay to call prompt this way:

  prompt('Enter your text here');

instead of:

  prompt('Enter your text here', '');

I.e. without passing a suggested input to it?

Share Improve this question edited Dec 1, 2011 at 11:20 jsalonen 30.6k15 gold badges92 silver badges110 bronze badges asked Dec 1, 2011 at 11:18 helpermethodhelpermethod 62.4k71 gold badges199 silver badges280 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 6

Yes, it is OK.

The second parameter to prompt method is optional (see "window.prompt on MDN"). As according to ECMAScript specification (ECMA-262, section 4.3.9), a value of undefined is given to a variable which has no assigned value. In the prompt method, it doesn't matter whether you leave the second parameter as undefined or pass an empty string to it: both result in empty string as default value in the prompt.

In case you are wondering why this information is not available on DOM standards such as W3C DOM the answer is that it is a non-standard method that is "just" monly supported by browsers (part of so called "DOM Level 0" spec). However, the uping HTML 5 is likely to define prompt (window.prompt) as a standard method (see "6.4 User prompts").

In the documentation on MDC, the second parameter is listed as optional.

value is a string containing the default value displayed in the text input field. It is an optional parameter.

Yes, the second parameter is optional according to the HTML5 spec (the closest thing we currently have to a specification of prompt and alert and such):

The prompt(message, default) method, when invoked, must release the storage mutex, show the given message to the user, and ask the user to either respond with a string value or abort. The user agent must then pause as the method waits for the user's response. The second argument is optional. If the second argument (default) is present, then the response must be defaulted to the value given by default. If the user aborts, then the method must return null; otherwise, the method must return the string that the user responded with.

(My emphasis)

I thought the answer was 'yes', until I just saw that in IE7, this will result in having 'undefined' prefilled in the input box instead. Try it out for yourself in IE7 with a quick JSFiddle: http://jsfiddle/ALw6r/

Edit: from the ments, seems this is also broken in IE8.

Yes, that is valid JavaScript. As w3schools mentions on http://www.w3schools./jsref/met_win_prompt.asp it's optional

发布评论

评论列表(0)

  1. 暂无评论