In a specific page a user will press a button but on button press before the actual processing, I need occasionally to present to the user a list of options
to select the appropriate one and use that selection in order to be able to proceed the processing.
So essentially I need to display a pop-up window that shows a select
box with available options and get the user's selection and then continue processing.
So to do this I found that I need a combination of window->open/prompt/showModalDialog
I found a way to present a pop-up window to the user with the options via
var newWindow = window.open("", null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.write("<select>");
newWindow.document.write("<option>");
newWindow.document.write(obj);
newWindow.document.write("</option>");
newWindow.document.write("</select>");
Example for passing just one option.
But I can not seem to find how to get back the selection.
The prompt
on the other hand returns the selection, but I don't think I can make it display my select
.
The showModalDialog
returns the selection, but seems to expect another web page as a parameter. So it is not suitable for me.
How can I create my pop-up using plain javascript?
var newWindow = window. open("", null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no"); newWindow. document. write("<select>"); newWindow.
JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.
Here is a simple solution that will allow you to fetch value from opened window. All you need is to inject JavaScript code into opened window that will interact with the parent window using window.opener
:
HTML
<input id="value" />
<button onclick="openWindow();">Open</button>
JavaScript
function openWindow() {
var i, l, options = [{
value: 'first',
text: 'First'
}, {
value: 'second',
text: 'Second'
}],
newWindow = window.open("", null, "height=200,width=400,status=yes,toolbar=no,menubar=no,location=no");
newWindow.document.write("<select onchange='window.opener.setValue(this.value);'>");
for(i=0,l=options.length; i<l; i++) {
newWindow.document.write("<option value='"+options[i].value+"'>");
newWindow.document.write(options[i].text);
newWindow.document.write("</option>");
}
newWindow.document.write("</select>");
}
function setValue(value) {
document.getElementById('value').value = value;
}
Working example here: http://jsbin.com/uqamiz/1/edit
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With