Customizing buttons on Dialogs in JavaScript to have dynamic names

There is something on my website that resembles this:


        $("#id").html(msg2show).dialog({
            //Other attributes
            buttons: {
                "Yes": function() {//Code},
                "No": function() {//Code}
            }
        });
    

I am currently working on adding language support to my site. Is there a way for me to dynamically change the text displayed as "Yes" and "No" without having to duplicate any code?

I tried using the following approach, where I replaced the strings above with variable names, but it seems that the variables are being interpreted as string literals rather than their actual values:


        var yes = 'Si';
        var no = 'No';
    

Answer №1

To ensure smooth functionality, it is recommended to create your buttons object first before passing it to the .dialog() function. This way, you can easily use your variables as keys using bracket notation:

var agree = 'Agree';
var disagree = 'Disagree';
var buttons = {};
buttons[agree] = function() {};
buttons[disagree] = function() {};
$("#id").html(messageToShow).dialog({
    //Other attributes
    buttons: buttons
});

Answer №2

utilize the text attribute to designate the names of the button. See this Illustration

   $( "#dialog" ).dialog({

   buttons: [
        {
         text: "OK",
         click: function() {
          $( this ).dialog( "close" );
     }
   }
 ]
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jump to Anchor when Page Reloads

Hey there! I'm currently developing a gallery script and I'm trying to figure out how to automatically position the page to the top of a specific anchor when it is loaded. I attempted to use the following code: <script>location.href = "#tr ...

What is the method for retrieving the IDs of checkboxes that have been selected?

I attempted running the following code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="http://static.jstree.com/v.1. ...

An error stating that "DataTable is not a recognized function" occurred within the document function

Previously, I set up datatables using the code below: $(function () { $('#keywords-table').DataTable({ "ajax": ({ url: "{{ route('getKeywordsByProductId') }}", method: "get", ...

Creating an infinite loop animation using GSAP in React results in a jarring interruption instead of a smooth and seamless transition

I'm currently developing a React project where I am aiming to implement an infinite loop animation using GSAP. The concept involves animating a series of elements from the bottom left corner to the top right corner. The idea is for the animation to sm ...

Tips for interpreting the JSON data returned by a Node server in Angular

When trying to implement a login form in my Angular frontend, I encountered an issue with reading the JSON object returned from my node.js server. Despite following the correct steps, the console displays "undefined" as if it cannot recognize the format. ...

Preventing SQL Injection by properly formatting SQL queries

In my Node.js application, I need to construct an SQL query that looks like the one shown below. SELECT * FROM my_table WHERE my_column IN ['name1','name2'] The user inputs an array, such as ['name1', 'name2'], whic ...

Employ material-ui default prop conditionally

I am implementing a StepLabel component in material ui. Depending on the props passed to the parent, I may need to make changes to the icon property of the StepLabel: interface Props { customClasses?: ClassNameMap; customIcon?: ReactNode; } const MySt ...

What causes the empty gap to appear during animated transitions between two 'div' elements?

Is there a way to eliminate the white space in between elements during animation? Should I wrap both divs into another div to achieve this? I am using position-top to adjust my div animations. Could this be causing the issue? What other methods can you s ...

What steps should I take to prompt Postman to interact with a Web API?

I have recently installed the Postman plugin for Chrome and I am curious about how to use it to call my web API. Currently, I am making an AJAX call in JavaScript with the following code: alert("Getting security token"); // Do AJAX call to get security t ...

Creating a circular frame for your image to use as a Facebook profile picture

In the process of developing an input feature that allows users to upload file images for avatar changes, similar to Facebook's functionality. However, I am aware that Facebook utilizes a circular area for avatars and enables users to adjust the image ...

Compiling and rendering HTML code from a file with AngularJS

Here is the custom directive code that I have created: angular.module('app.directives', []).directive('userHeader', ['authService', '$compile', function(authService, $compile) { return { restrict: 'AEC&ap ...

Unable to locate module - relative file path

I'm currently running a test with the following code and encountering an error message: Failed: cannot find module '../page/home_page.js The main page consists of: describe("login to website",function(){ var employeeId; var employee ...

Ways to isolate and limit the application of CSS in React and Gatsby to specific pages instead of having it affect the global scope

At the moment, I'm working on integrating a keen-slider library(https://www.npmjs.com/package/keen-slider). To install it, we have to include import 'keen-slider/keen-slider.min.css'. This essentially adds the CSS globally to our project. Ho ...

Issue encountered when displaying various data options in the dropdown menus within a modal window

My goal is to display a modal when a button is clicked. The modal renders perfectly fine, but I am facing an issue with duplication of dropdowns inside the modal when the "add more" button is clicked. The main issues are: 1. Selecting the first option in ...

What is the best way to utilize Typescript when making queries to Firebase?

I have successfully integrated push notifications for my app using Firebase Cloud Functions. Now, I am looking to enhance the user experience by updating the app's badge count alongside the push notifications. I understand that this can only be achiev ...

Add elements to an array following an AJAX request

On my .cshtml page, I have the following script: $(function () { var tempArray = []; var tbValue = $('#tb1').val(); $.ajax({ url: "/ControllerName/getdata", dataType: 'json', ...

What is the method for replacing browser bundle sources using Rollup?

Is it possible to use rollup to swap out a specific source with another source in an NPM package when creating a browser bundle? The source in question is loaded dynamically using import('./relativeFile.js') (I need this to be replaced). I attem ...

Guide to building a nested React component

My custom dropdown component requires 2 props: trigger (to activate the dropdown) list (content to display in the dropdown) Below is the implementation of my component: import { useLayer } from "react-laag"; import { ReactElement, useState } fr ...

Dealing with multi-line strings in Javascript

I am having an issue with my code: let testStr = "Asdfads"; let htmlStr = `<script>${ testStr }</script>`; // but it works with: <div>${ testStr }</div> console.log(htmlStr); When I run this code, I receive the following error: ...

Steps for implementing target='_blank' on a <Link> tag with more than just an <a> element inside

I'm facing an issue where I need to open a new browser tab and redirect to a specific URL when a button is clicked. The problem arises when using an element other than an anchor tag inside the Next's <Link> element, as it seems to ignore th ...