JavaScript - multi-line textbox in prompt()? - javascript

Is there anyway to make the textbox/input box in prompt multiline?

No, browsers only allow single-line input for prompt(). However, with a simple change to the jQuery Alert Dialogs library you could get multi-line input there. Take jquery.alerts.js, look for <input type="text" size="30" id="popup_prompt" /> and replace it by <textarea rows="5" cols="30" id="popup_prompt"></textarea>. That should do to have a multi-line input field show up when calling jPrompt().
Edit: As Mulletfingers999 points out in a comment, jQuery Alert Dialogs have been deprecated in favor of jQuery UI dialogs. There you can also show a "modal" dialog, that dialog can have arbitrary content however - meaning that a <textarea> tag is possible if you want multi-line input.

Use \n encased in double quotes ("\n")
prompt("This\nis\nmultiline");

For pretty much any user-facing web application these days, you're going to want to avoid using clunky old dialogs like alert() and prompt(). Almost any library you're using should have a much better answer. jquery would be fine as others have said. It would also be good to think of how you might eliminate a need for modality by designing a more clever interface.
"Interestingly", in Firefox they are already using XUL and reinventing a lot of user interface based on that (instead of relying on the "common dialogs" of the underlying OS). There's a template for modal dialogs in /source/toolkit/components/prompts/content/tabprompts.xml:
<vbox anonid="infoContainer" align="center" pack="center" flex="1">
<description anonid="info.title" class="info.title" hidden="true" />
<description anonid="info.body" class="info.body"/>
</vbox>
<row anonid="loginContainer" hidden="true" align="center">
<label anonid="loginLabel" value="&editfield0.label;" control="loginTextbox"/>
<textbox anonid="loginTextbox"/>
</row>
<row anonid="password1Container" hidden="true" align="center">
<label anonid="password1Label" value="&editfield1.label;" control="password1Textbox"/>
<textbox anonid="password1Textbox" type="password"/>
</row>
<row anonid="checkboxContainer" hidden="true">
<spacer/>
<checkbox anonid="checkbox"/>
</row>
What they do is just hide the elements of the UI that they don't need. In the case of a call to prompt, they re-use the user name field and keep the password and checkbox elements hidden. You can see this happening in /source/toolkit/components/prompts/src/CommonDialog.jsm#52:
case "prompt":
this.numButtons = 2;
this.iconClass = ["question-icon"];
this.soundID = Ci.nsISound.EVENT_PROMPT_DIALOG_OPEN;
this.initTextbox("login", this.args.value);
// Clear the label, since this isn't really a username prompt.
this.ui.loginLabel.setAttribute("value", "");
break;
Since it's more or less HTML, the only question is what the non-standard tag <textbox> means for the user interface. The XUL controls documentation informs us that it's only a one-line entry, you would need <textarea> for more:
https://developer.mozilla.org/en/XUL_controls
I thought it would be "fun" to look at the implementation in Chromium on top of GTK too. After a bit of digging through the circuitous wrappers of WebKit, I did manage to find chromium/src/chrome/browser/ui/gtk/js_modal_dialog_gtk.cc, specifically this part:
// Adjust content area as needed. Set up the prompt text entry or
// suppression check box.
if (ui::MessageBoxFlags::kIsJavascriptPrompt == dialog_->dialog_flags()) {
GtkWidget* content_area =
gtk_dialog_get_content_area(GTK_DIALOG(gtk_dialog_));
GtkWidget* text_box = gtk_entry_new();
gtk_entry_set_text(GTK_ENTRY(text_box),
UTF16ToUTF8(dialog_->default_prompt_text()).c_str());
gtk_box_pack_start(GTK_BOX(content_area), text_box, TRUE, TRUE, 0);
g_object_set_data(G_OBJECT(gtk_dialog_), kPromptTextId, text_box);
gtk_entry_set_activates_default(GTK_ENTRY(text_box), TRUE);
}
The text_box is created with gtk_entry_new() and the GTK documentation states that GtkEntry is "A single line text entry field". For multi-line entry you would have to use GtkTextView:
http://developer.gnome.org/gtk/2.24/GtkTextView.html
So there's your answer not just of "can you?" but the smoking guns of why you can't (in a couple of popular browser implementations.) Unless there's a way to override that XUL in Firefox with an extension of some kind, which there may well be! I'll leave it as an exercise for the reader. :P

Related

Is it possible to give a textarea spell checking in a specified language?

I'm building a flash cards app for language learning, and I have spellcheck="false" set on my input for the foreign language. Ideally I would be able to spell check that input in the target language, is this possible (without making a custom text editor)?
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/lang
Even if the lang attribute is set, it may not be taken into account, as the xml:lang attribute has priority.
But this minimal test doen't work on Chrome ...
<html><body>
<textarea spellcheck="true" lang="en-GB">Thiss is a test mesage.</textarea>
<textarea spellcheck="true" lang="fr-FR">Un mesage puor test.</textarea>
</body></html>

Ace editor (form) - Can I preserve line breaks/text format?

Working on a project for my school building an MVC Sinatra application. I want to create a web app that can save and display back snippets/algos using ace editor.
I figured out how to (seemingly) capture form input through ace editor by hiding the input field and assigning the value from ace on change with the snippet below.
//CAPTURE/SET VALUE
var textarea = $('input[name="content"]');
editor.getSession().on("change", function () {
textarea.val(editor.getSession().getValue());
});
my form looks like this
<!--ACE EDITOR-->
<div id="editor"></div>
To open settings panel, inside editor - CTRL+Q (Windows) | CMD+Q (Mac)
<!--------------------------------------------------------->
<!--FORM-->
<form action="/ace" method="POST">
<!--normal-->
<input type="text" name="content" style="display: none;" />
<!--submit-->
<input type="submit" value="Save">
</form>
I can capture the params fine but the problem is it doen't preserve the line breaks so entering...
def something
end
into ace editor and clicking submit gives me back
"def something end"
when I would love in theory to get something like
"def something\n\nend"
or something of the sort.. you get the drift
I need to be able to somehow use the editor to capture input, and on submit assign that to an object attribute so pseudo
snippet = Snippet.new(:content => params[:content])
then be able to call that back and display back on editor in the right format
snippet.content (preserves linebreaks)
Full code and images HERE if you rather visuals.
Any help would be appreciated and if there is anything I'm missing out please let me know.. hope I've supplied sufficient info and detailed properly.
input doesn't accept newlines, you need to use textarea instead.

Javascript hide HTML text if input box is not filled

I have an HTML form where users are able to input their mobile number. See below:
<form class="formulario" action="signature_test.html" method="get" onsubmit="return signature_Alert()" >
Mobile (mgrs): <input type="text" name="mobile" id="mobile"><br>
<br>
<input type="submit" value="Generate Signature">
</form>
Whatever the user enters, is then populated in another HTML file. It innerHTML the text "Default":
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
However, I would like that if the user leaves the mobile field blank, to have the "Mobile:" and the "Default" not displayed. Is that possible with Javascript?
By the way, this would be the Javascript that innerHTML the "Default" text.
<script>
var values = window.location.search.substring(1).split('&')
var mobile = values[3].split('=')[1]
document.getElementById('mobileInput').innerHTML = mobile;
</script>
Thanks.
Sure, just wrap the content in an element you can target and modify:
<span id="mobileInputContainer">
<font color="#008080">Mobile: </font></b><font id="mobileInput">Default </font><br>
</span>
Then just adjust that element's style similar to how you already adjust another element's content:
if (mobile.length < 1) {
document.getElementById('mobileInputContainer').style.display = 'none';
}
You'd of course want to double-check the actual value you're getting for mobile in your code. Make sure it doesn't have whitespace, etc. Or really tweak whatever your logic is for determining that no value is present to display. But the actual act of hiding the element is simple, just set the style to be hidden.
Additionally, I'd like to echo a comment above. <font> tags really shouldn't be used anymore. You'll find a little bit of an introduction to CSS styling can go a long way here. I recommend some introductory tutorials on the subject.
You also appear to have an errant </b> in your code. Perhaps you're not showing us the entire content. Either way, you'll want to double-check your HTML as well. Always start with valid and well-formed HTML before using any JavaScript or CSS, or behavior may not be what you expect.

How can I change label of OK/Cancel buttons of a dialog window?

How can I change/tranlate label of OK/Cancel buttons of a dialog window of XPCOM? You can see a list of such buttons here.
Indeed I want localize Zotero Firefox add-on. A portion of code that display such dialog is here:
var regenerate = promptService.confirmEx(
window,
Zotero.getString('integration.revert.title'),
Zotero.getString('integration.revert.body'),
promptService.STD_OK_CANCEL_BUTTONS + promptService.BUTTON_POS_1_DEFAULT,
null, null, null, null, out
);​
Well, first, if you want to learn XUL, I would highly recommend getting the XUL Explorer, which is an interactive tool you can use to build snippets and preview what you are designing.
This will come in handy if you've never worked in XUL before, as though it looks a lot like HTML, it's not the same lineup of elements and approaches. It really lives a bit above where HTML does, in that it's used to build desktop apps, which can be used to build things such as:
https://developer.mozilla.org/en-US/docs/tag/tools
The majority of those programs you can download the source for and look through it just like you would a list of documents. You'll also notice several extensions, such as the Firefox Web Developer add-on. Here's the source, and here's some of the XUL files. Which happens to include a dialogs directory, and a message.xul:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/"?>
<?xml-stylesheet href="chrome://web-developer/content/dialogs/style-sheets/message.css"?>
<!DOCTYPE dialog SYSTEM "chrome://web-developer/locale/dialogs/message.dtd">
<dialog buttons="accept" id="web-developer-message-dialog" onload="WebDeveloper.Message.initialize()" title="&webdeveloper.message.title;" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script src="chrome://web-developer/content/common/common.js"/>
<script src="chrome://web-developer/content/dialogs/javascript/message.js"/>
<vbox id="web-developer-message-details">
<description id="web-developer-message"/>
<description id="web-developer-more-information" value="&webdeveloper.more.information;" onclick="WebDeveloper.Message.moreInformation()" class="url"/>
</vbox>
</dialog>​
So you can use a Dialog for this, which let's you create different types of prompts. For instance, I made the following going through a tutorial some time ago:
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<dialog id="myDialog" title="My Dialog"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
onload="window.sizeToContent();"
buttons="accept,cancel"
buttonlabelaccept="Set Favorite"
buttonaccesskeyaccept="S"
ondialogaccept="return doSave();"
buttonlabelcancel="Cancel"
buttonaccesskeycancel="n"
ondialogcancel="return doCancel();">
<script>
function doSave(){
//doSomething()
return true;
}
function doCancel(){
return true;
}
</script>
<dialogheader title="My dialog" description="Example dialog"/>
<groupbox flex="1">
<caption label="Select favorite fruit"/>
<radiogroup>
<radio id="1" label="Oranges because they are fruity"/>
<radio id="2" selected="true" label="Strawberries because of color"/>
<radio id="3" label="Bananna because it pre packaged"/>
</radiogroup>
</groupbox>
</dialog>
Which looks like:
So you really have a lot of options, even, if you want, nsIPromptService...
var prompts = Components.classes["#mozilla.org/embedcomp/prompt-service;1"]
.getService(Components.interfaces.nsIPromptService);
var check = {value: false}; // default the checkbox to false
var flags = prompts.BUTTON_POS_0 * prompts.BUTTON_TITLE_SAVE +
prompts.BUTTON_POS_1 * prompts.BUTTON_TITLE_IS_STRING +
prompts.BUTTON_POS_2 * prompts.BUTTON_TITLE_CANCEL;
// This value of flags will create 3 buttons. The first will be "Save", the
// second will be the value of aButtonTitle1, and the third will be "Cancel"
var button = prompts.confirmEx(null, "Title of this Dialog", "What do you want to do?",
flags, "", "Button 1", "", null, check);
There's also something called PopupNotifications.jsm. There's a lot there, so I'm sure there's something you can find for what you're looking to do. There's also the Zotero source, too.
If you need custom labels then you just shouldn't use default buttons:
promptService.confirmEx(
window,
Zotero.getString('integration.revert.title'),
Zotero.getString('integration.revert.body'),
promptService.BUTTON_POS_0 * BUTTON_POS_0_DEFAULT,
Zotero.getString('integration.revert.OK'),
Zotero.getString('integration.revert.cancel'),
null, null, out
);​
This declares the first button as the default, other than that no flags need to be specified - two labels have been specified so two buttons will show up.
The only way to do this while supporting every browser is to create it with a dialog library, jQueryUI is a bit at the end of it's life as a trendy library, but is still really fully featured.

forms.elements.length in ff

I have a form validation routine in JS which cycles through elements of a the first form on the page. I read the size of the elements array like this:
maxi=document.forms[0].elements.length;
This works fine in IE returning 23. In FF it always returns 0 and no validation at all is performed.
Any suggestions?
Thanks!
Move your javascript after the mark up or make sure that it runs after the document is loaded. Sounds like in FF the code is running before the form has been added to the DOM.
You might also consider using a javascript library, such as jQuery (I would recommend this), MooTools, Prototype, etc. to iron out a lot of the inevitable cross-browser issues you will have. Using jQuery, and the validation plugin, the validation code is very simple, using CSS classes to help with validation.
<script type="text/javascript" src="jquery.js" />
<script type="text/javascript">
$(function() { // run on document load
$('form').validate(); // use validation plugin to validate form
});
</script>
<form ...>
<input type="text" id="txt" name="txt" class="required" /> <!-- a required element -->
<input type="text" id="num" name="num" class="required number" /> <!-- a required, numeric element -->
...
</form>
You should try some interactive javascript console to test issues like this -
but, for this particular thing, you could use the "for ...in" form of for to iterate over the elements:
http://en.wikipedia.org/wiki/Foreach#JavaScript
Probably, however, it is the "elements" property which is non-standard there, so you will need to check the DOMs to get to a better way to retrieve the form widgets as objects.
And finally: beware of cleint side verification: it is often a burden to users and, if special care is not taken, it is to ease to have your forms stop working on a variety of browsers/platforms due to a verification which is mostly meaningless anyway (since you must verify the lenght of data entered server side in either case)

Categories

Resources