Document

JavaScript Techniques for Using Yes/No Prompts

The recommended approach for this type of functionality is Zakaria’s method, although there are numerous JavaScript modal popup solutions available.

JS button prompt with Yes/No options

The primary issue arises due to the absence of parentheses in the mentioned line, as shown in () .

 ______________________________^^ 

My recommendation would be to refrain from using the inline-event onclick and opt for addEventListener() instead.

document.getElementById('my-button').addEventListener('click', function() < if (confirm('Remove token?')) < console.log('OK'); >else < console.log('Cancel'); >>)

The function call is incomplete without () as mentioned before in onclick=»alertFunction()» .

At present, the onclick event is attempting to utilize a variable instead of executing the function.

Employing Zakaria’s method is possibly the more accurate approach for this particular functionality. In general, it is advisable to maintain all functions separate from your markup as a good practice.

How to create a dialog with “yes” and “no” options in JavaScript?, No, you cannot create a dialog box with “yes” or “no”. A confirmation dialog box in JavaScript has “Ok” and “Cancel” button.

Читайте также:  Цвет рамки

How to create javascript confirm box yes no

How to create javascript confirm box yes no. If someone click on cancel button then our HTML Duration: 5:02

How To Alert In JavaScript With Yes / No

Unfortunately, you can’t actually customise the text to be yes/no or any other combination, you Duration: 2:09

In Javascript prompt yes/no before dropping the file?

To prevent the default action, you can utilize either return false or e.preventDefault(); .

$('input[type=file]').on('drop', function(e) < if (!confirm("are you sure?")) < e.preventDefault(); >>);

Regrettably, it seems to be non-transferable since it functions properly only in Chrome and Safari, not in FireFox (I haven’t tested it on IE since I use a Mac).

To make it portable, an HTML modal dialogue can be utilized to obtain confirmation. Once canceled, the Clearing technique in jQuery can be used to remove the dropped file from the input field of .

Window.confirm in javascript Code Example, javascript confirm yes no ; 1. var proceed = confirm(«Are you sure you want to proceed?»); ; 2. if (proceed) < ; 3. //proceed ; 4. >else < ; 5. //don't proceed.

How to implement a custom ‘confirm’ prompt in JS using promises

In fact, I favor your initial method since it demonstrates a greater degree of separation of concerns.

To implement the Promise approach, simply pass the resolve function instead of the Promise.

var resolveGlobal; // declare so that it's available both from within `add-item` and `button` handlers $(".add-item").click(function () < promise = new Promise(function (resolve, reject) < var ask_about_flag = true; if (ask_about_flag) < $("#flag_modal").modal("show"); resolveGlobal = resolve; >else < resolve(null); >>); promise.then(function (flag) < // flag is the parameter passed to resolve addItem(flag); >); >); $("#yes").click(function () < resolveGlobal(true); >); $("#no").click(function () < resolveGlobal(false); >); function addItem(flag)
      

Yes/No with for loop, for answer in Yes yes y Y; do [[ $answer == $ANS ]]; do :; done · What do you exactly mean with a for loop? What do you want to do that if and

Code to ask yes/no question in javascript

There are three modal boxes available in JavaScript, namely prompt , confirm , and alert . Unfortunately, your request cannot be fulfilled by any of them.

A wide range of JS modal popup options are available, and the following is one illustration.

An alternative option would be to utilize a modal popup within the browser.

As mentioned by others, there is no option but to use OK/Cancel with confirm() .

I highly suggest trying out the jqModal jQuery plugin. It has been extensively tested and proven to work flawlessly on all of my recent projects. In particular, take a look at this example.

In this section, we will explore the use of jqModal’s «FUN! Overrides» feature, specifically the «view (alert)» and «view (confirm)» options. The main purpose is to demonstrate how to replace the default alert() and confirm() dialogs with custom ones using jqModal. It’s important to note that since JavaScript is single-threaded, the confirm() function requires a callback instead of returning a boolean value.

How to implement a custom ‘confirm’ prompt in JS using promises, So, once you change the additem click handler, you don’t need to change the yes/no click handler. However, for your promise approach, yes/no

Источник

Взаимодействие с пользователем: alert, prompt, confirm

Материал на этой странице устарел, поэтому скрыт из оглавления сайта.

Более новая информация по этой теме находится на странице https://learn.javascript.ru/alert-prompt-confirm.

В этом разделе мы рассмотрим базовые UI операции: alert , prompt и confirm , которые позволяют работать с данными, полученными от пользователя.

alert

alert выводит на экран окно с сообщением и приостанавливает выполнение скрипта, пока пользователь не нажмёт «ОК».

Окно сообщения, которое выводится, является модальным окном. Слово «модальное» означает, что посетитель не может взаимодействовать со страницей, нажимать другие кнопки и т.п., пока не разберётся с окном. В данном случае – пока не нажмёт на «OK».

prompt

Функция prompt принимает два аргумента:

result = prompt(title, default);

Она выводит модальное окно с заголовком title , полем для ввода текста, заполненным строкой по умолчанию default и кнопками OK/CANCEL.

Пользователь должен либо что-то ввести и нажать OK, либо отменить ввод кликом на CANCEL или нажатием Esc на клавиатуре.

Вызов prompt возвращает то, что ввёл посетитель – строку или специальное значение null , если ввод отменён.

Единственный браузер, который не возвращает null при отмене ввода – это Safari. При отсутствии ввода он возвращает пустую строку. Предположительно, это ошибка в браузере.

Если нам важен этот браузер, то пустую строку нужно обрабатывать точно так же, как и null , т.е. считать отменой ввода.

Как и в случае с alert , окно prompt модальное.

var years = prompt('Сколько вам лет?', 100); alert('Вам ' + years + ' лет!')

Второй параметр может отсутствовать. Однако при этом IE вставит в диалог значение по умолчанию «undefined» .

Запустите этот код в IE, чтобы понять о чём речь:

Поэтому рекомендуется всегда указывать второй аргумент:

confirm

confirm выводит окно с вопросом question с двумя кнопками: OK и CANCEL.

Результатом будет true при нажатии OK и false – при CANCEL( Esc ).

var isAdmin = confirm("Вы - администратор?"); alert( isAdmin );

Особенности встроенных функций

Конкретное место, где выводится модальное окно с вопросом – обычно это центр браузера, и внешний вид окна выбирает браузер. Разработчик не может на это влиять.

С одной стороны – это недостаток, так как нельзя вывести окно в своём, особо красивом, дизайне.

С другой стороны, преимущество этих функций по сравнению с другими, более сложными методами взаимодействия, которые мы изучим в дальнейшем – как раз в том, что они очень просты.

Это самый простой способ вывести сообщение или получить информацию от посетителя. Поэтому их используют в тех случаях, когда простота важна, а всякие «красивости» особой роли не играют.

Резюме

  • alert выводит сообщение.
  • prompt выводит сообщение и ждёт, пока пользователь введёт текст, а затем возвращает введённое значение или null , если ввод отменён (CANCEL/ Esc ).
  • confirm выводит сообщение и ждёт, пока пользователь нажмёт «OK» или «CANCEL» и возвращает true/false .

Источник

JS button prompt with Yes/No options

I highly suggest you use something like the jQuery UI dialog feature to create an HTML dialog box instead. Solution 1: Unfortunately, there is no cross-browser support for opening a confirmation dialog that is not the default OK/Cancel pair.

Javascript Confirm popup Yes, No button instead of OK and Cancel

Javascript Confirm popup, I want to show Yes, No button instead of OK and Cancel.

I have used this vbscript code:

 function window.confirm(str) 

this only works in IE, In FF and Chrome, it doesn’t work.

Is there any workround to achieve this in Javascript?

I also want to change the title of popup like in IE ‘Windows Internet Explorer’ is shown, I want to show here my own application name.

Unfortunately, there is no cross-browser support for opening a confirmation dialog that is not the default OK/Cancel pair. The solution you provided uses VBScript, which is only available in IE.

I would suggest using a Javascript library that can build a DOM-based dialog instead. Try Jquery UI: http://jqueryui.com/

The only way you can accomplish this in a cross-browser way is to use a framework like jQuery UI and create a custom Dialog:

jquery Dialog

It doesn’t work in exactly the same way as the built-in confirm popup but you should be able to make it do what you want.

You can also use http://projectshadowlight.org/jquery-easy-confirm-dialog/ . It’s very simple and easy to use. Just include jquery common library and one more file only:

You can’t do this cross-browser with the confirm() function or similar. I highly suggest you use something like the jQuery UI dialog feature to create an HTML dialog box instead.

Javascript — JS button prompt with Yes/No options, Won’t work with my current code: < Stack Overflow. About; Products JS button prompt with Yes/No options. Ask Question Asked 3 years, 10 months ago. I've voted to close the question but that doesn't mean not showing the …

JS button prompt with Yes/No options

Creating a «Remove Token» button that will alert the user with a confirmation «Yes» or «No». Won’t work with my current code:

  

What am I doing wrong? Thanks.

The main problem comes from the missing parentheses () in the following line :

 ______________________________^^ 

I suggest to avoid the inline-event onclick and use addEventListener() instead :

document.getElementById('my-button').addEventListener('click', function() < if (confirm('Remove token?')) < console.log('OK'); >else < console.log('Cancel'); >>)

You are just missing the () when you call the function i.e. onclick=»alertFunction()»

Currently the onclick event is just trying to use a variable and not run your function.

  

but using Zakaria’s approach is likely the more correct one for this type of functionality. Generally speaking its a good habit to keep any functions outside of your markup.

C# — JavaScript alert with yes no button, This answer shows promise, but it could really use some information about how to use this. How do you specify the text of the prompt, as in the question you are asking the user: «Are you sure you want to do that?». And, do you just change the text «Yes» and «No» to change the labels on the buttons? Can you …

JavaScript alert with yes no button

I want to show alert with yes no button.

using System; using System.Data; using System.Configuration; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Data.OleDb; using System.Collections; using System.Windows.Forms; public partial class _Default : System.Web.UI.Page < protected void Page_Load(object sender, EventArgs e) < >protected void Button1_Click(object sender, EventArgs e) < DialogResult dialogResult = MessageBox.Show("Sure", "Some Title", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) < OleDbConnection con = new OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;data source= C:/Users/xyz/Documents/Visual Studio 2010/WebSites/accesspassword/stud.accdb;Jet OLEDB:Database Password=12345;"); con.Open(); OleDbCommand com = new OleDbCommand("insert into Table1 values(@Roll,@f_name)", con); OleDbParameter obj1 = new OleDbParameter("@Roll", DbType.StringFixedLength); obj1.Value = TextBox1.Text; com.Parameters.Add(obj1); OleDbParameter obj2 = new OleDbParameter("@f_name", DbType.StringFixedLength); obj2.Value = TextBox2.Text; com.Parameters.Add(obj2); com.ExecuteNonQuery(); TextBox1.Text = ""; TextBox2.Text = ""; con.Close(); >else if (dialogResult == DialogResult.No) < TextBox2.Text = ""; >> > 

This code is running fine but i want to do this using JavaScript alert with yes no button. I am using Visual Studio 2010 asp.net c#.

   

Using jQuery you could create a custom dialog

If you are using Twitter Bootstrap as your interface framework,

I would recommend bootbox.js as it already has the confirm functionality simplified:

bootbox.confirm("Are you sure?", function(result) < Example.show("Confirm result: "+result); >); 

Code to ask yes/no question in javascript, Note; due to the single threaded nature of javascript, the confirm() function must be passed a callback — it does NOT return true/false. Share Follow

Code to ask yes/no question in javascript

I could only find the function confirm() that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?

Javascript offers 3 modal boxes. prompt , confirm and alert . None of those satisfy your request.

There are a plethora of js modal popup solutions. Here’s an example.

Instead you could use a in browser modal popup.

Like everyone else above says, you’re stuck with OK/Cancel using confirm() .

I would like to recommend this jQuery plugin though: jqmodal. I’ve used it on 3 recent projects and it has worked great for each one. Specifically check out this example:

6). FUN! Overrides — a. view (alert), b. view (confirm) It is now time to show a real-world use for jqModal — overriding the standard alert() and confirm dialogs! Note; due to the single threaded nature of javascript, the confirm() function must be passed a callback — it does NOT return true/false.

No, but there are JavaScript libraries that can accomplish this for you. Just as an example, Ext JS can be used to create a message box dialog.

Making a Javascript Yes/No Confirmation Box?, Create a div that contains your yes/no question and buttons, append it to your main page’s DOM, position it where you want it, and give the div a z-index greater than that of the iframe. Believe it or not, this means that the page is behind the iframe, but the div is in front of it. Exactly what you want. Handle clicks on the …

Источник

Оцените статью