Rebinding buttons in a jQuery dialog box

One dilemma I am facing involves a jQuery dialog box with an HTML input inside. This dialog box includes two buttons - Save and Cancel. When the user clicks Save, I check if they have entered input in the text field. If not, I display an error message within the dialog box and prompt them to provide input. However, after hitting Save again, nothing occurs. How can I re-bind the Save button once it has already been used? Thank you!


    var message = "Please enter a phone number."
    var phoneNumber = "<input type='text' id='phoneNumber' name='phoneNumber'/> ";
    var dialogHtml = "<div id='confirmPhoneNumber'>"  + message + phoneNumber + "<div id='dialogError' style='display:none'>Phone number field cannot be empty</div>" + "</div>";
    $(this).append(dialogHtml);
    $("#confirmPhoneNumber").css("font-size", "70%");
    $("#confirmPhoneNumber").dialog({
        resizable : false,
        modal : true,
        title : 'Save Phone',
        buttons : {
            'Save' : function () {
                // Check if phone number is provided
                if ($("#phoneNumber").val().trim().length == 0) {
                    $("#dialogError").show();
                } else {
                // Make AJAX call
                }
            },
            'Cancel' : function () {
                $(this).dialog('close');
            }
        }
    });

Answer №1

It appears that the code is properly functioning, but there may be a misunderstanding due to a misconfigured test scenario (or so I believe, LoL).

var message = "Please enter your phone number.";
var phoneNum = "<input type='text' id='phoneNum' name='phoneNum'/>";
var dialogHtml = "<div id='confirmPhoneNumber'>"  + message + phoneNum + "<div id='dialogError' style='display:none'></div>" + "</div>";
$('body').append(dialogHtml);
$("#confirmPhoneNumber").css("font-size", "70%");
$("#confirmPhoneNumber").dialog({
    resizable : false,
    modal : true,
    title : 'Save Phone',
    buttons : {
        'Save' : function () {
            // Phone number must be provided
            if ($.trim($("#phoneNum").val()).length == 0){
                $("#dialogError").html("An error occurred, please fill out the textfield.");
                $("#dialogError").show();
            } else {
                $("#dialogError").html("It's now working: " + $("#phoneNum").val());
                $("#dialogError").show();
            // Make AJAX call
            }
        },
        'Cancel' : function () {
            $(this).dialog('close');
        }
    }
});

If you run a test on this, you will observe that there are no instances of unbinding.

UPDATE: Adjusted the if statement in the save button. Hopefully, this resolves any issues.

Answer №2

Are you currently testing with Internet Explorer? Have any errors appeared on the page?

If you refer to (I'm doing my tests in Chrome) this link, the functionality works fine. You can click the button, receive an error message, input something new, click again, and see an alert. Hence, the button remains operational.

Nevertheless, Internet Explorer encounters issues; it displays an error stating that .trim() is not a supported function in IE. To address this, you can utilize jQuery's .trim() instead:

$("#confirmPhoneNumber").dialog({
    autoOpen: true,
    resizable: false,
    modal: true,
    title: 'Save Phone',
    buttons: {
        'Save': function() {
            // A phone number is required
            if ( $.trim($("#phoneNum").val()).length == 0) {
                 $("#dialogError").show();
            } else {
                alert('Got a number');
            }
        },
        'Cancel': function() {
            $(this).dialog('close');
        }
    }
});

You can retry using this link for compatibility with Internet Explorer.

Refer to the issue of Trim not functioning in JavaScript on IE.

Answer №3

Here's a way to handle the validation process:


'Save' : function () {
    var isValid = true;

    // Make sure phone number is provided
    if ($("#phoneNum").val().trim().length == 0) {
        $("#dialogError").show();
        isValid = false;
    }
    // Add any additional validations here

    if (isValid === true) {
        // Perform AJAX call
    }
},

This code allows for the validation to be triggered multiple times, and if all fields are valid, the form will be processed.

Answer №4

One way to connect to the control is by utilizing the 'live' function, which is commonly applied when dealing with dynamically generated controls.

Answer №5

When using jQuery UI, the click handler on a dialog button is not unbound after it has been pressed.

To see a demonstration of this, visit http://jsfiddle.net/MwNJd/2/

There must be another factor causing this issue.

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

Fetching weather data from the Darksky.com API in JSON format

My goal is to retrieve weather data in JSON format from the Darksky.com API. To do this, I first successfully obtained my latitude and longitude using the freegoip.com API. However, the Darksky API requires both longitude and latitude before it can provid ...

Jquery Query: Is it possible to incorporate variables into CSS properties?

I manage a website that supports multiple languages, and I want to adjust the position of my container based on the selected language. To achieve this, I attempted the following code: prop = lang == 'ar' ? 'right' : 'left'; $ ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

Deactivating and activating an HTML input button

So I was tinkering with this cool button: <input id="Button" type="button" value="+" style="background-color:grey" onclick="Me();"/> I've been wondering, how can I conveniently control its state of being disabled or enabled? Initially, I attem ...

Is it achievable for a modal popup to automatically move to a specified location?

I need assistance with... Is it feasible to display an external webpage within a modal window and have that page automatically scroll to a specific section (such as an anchor point)? ...

Deleting a database row when the cancel button is pressed

I have a scenario where I need to remove a database row containing a file name when the user clicks on the cancel button. However, despite my efforts, the database row is not being deleted. Can anyone help me identify what I might be doing wrong? Here is ...

Increasing Asynchronous Capabilities with Dynamically Updating jQuery Deferred within then() Method

I am currently exploring the functionalities of jQuery Deferred and I have encountered a challenge regarding chaining multiple deferreds. Let me outline my simplified issue: var def1 = $.ajax(...); // executing ajax call 1 var def2 = null, def3 = null; $ ...

Arrange images in a fluid manner around other images

Check out the website I'm currently working on: metroweb.tk I'm in the process of designing a website that mimics the Windows 8 metro UI. However, I've encountered an issue with larger app icons such as notes and clocks sticking out. Is the ...

What is the procedure for altering a particular element using ajax technology?

I have an AJAX request that updates the user information. I need to retrieve a specific value from the response and update the content of a specific element. For example, here is the element that needs to be changed: <div id="changeMe"><!-- New ...

The contrast between FormData and jQuery's serialize() method: Exploring the distinctions

Recently I came across a situation where I needed to submit a form using AJAX. While researching the most efficient method, I discovered two popular approaches - some developers were utilizing jQuery#serialize() while others were opting for FormData. Here ...

Using JavaScript, add a complex JSON record to a JSON variable by pushing it

I have been attempting to insert a complex JSON data record into a JSON variable using the following code: var marks=[]; var studentData="student1":[{ "term1":[ {"LifeSkills":[{"obtained":"17","grade":"A","gp":"5"}]}, {"Work":[{"obtained":"13"," ...

Exploring a new method for AJAX loading when handling large amounts of data into multiple div elements

As I continue my learning journey with html and jquery, I have been exploring ways to replicate monitoring systems (SCADA) into web-based systems. During this process, I discovered openseadragon as a MAP system similar to google maps that allows for overla ...

Toggle visibility of table columns by selected options (using jQuery)

I am seeking to create a dynamic table that only shows specific columns based on the selection in a dropdown menu. <table> <thead> <td colspan="5"> <SELECT name="menu"> <option value="eur">EUR</option> & ...

I can't figure out why this form isn't triggering the JS function. I'm attempting to create an autocomplete form field that connects to a MySQL database using a PHP script and AJAX

I am encountering an issue while trying to implement the .autocomplete() function from jQuery UI with a list of usernames fetched from a MySQL database using a PHP script. Strangely, it is not functioning as expected and no errors are being displayed in th ...

The jQuery dynamic fields vanish mysteriously after being validated

I am facing an issue with my jQuery and validation. Below is the code snippet causing the problem: var fielddd = 1; $(document).on('click', '.btn.add-field', function() { fielddd++; $('#newfield').append('< ...

Issue with retrieving data from controller in Spring MVC 3 using jQuery and AJAX via $.get method. The value is not being returned to the

I am currently diving into the world of AJAX, particularly in conjunction with Spring MVC. However, I am encountering some challenges along the way. Before delving into my actual real-time project requirements, I decided to test out the AJAX+Spring MVC+jQ ...

Angular-material's Md-dialog popup box is displayed as a separate view within the Yeoman framework

I have recently created a project using Yeoman (angular-fullstack, angular-material) and encountered an issue with triggering the md-dialog box. When clicking on a div element, the dialog box is supposed to appear. However, instead of showing the popup the ...

Tips for setting the id parameter on the asp-route-id for the modal button

My code is causing me some trouble. I have a table with 3 columns: category, subcategories and actions. In the third column, I display buttons "Edit" and "Delete". Here is a snippet of my code: <tbody> @foreach (var category in Model.ToList() ...

The menu field remains open even after clicking on the menu

I have encountered an issue with my code. Here is a DEMO that I created on jsfiddle.net Currently, when you click on the red div, the menu opens. However, if you click on the menu items, the menu area does not close. What do I need to do in order to clo ...

Using JavaScript, create a set of buttons within a div element and implement

$(document).ready(function() { $('#b1').click(function() { $('#uch').toggle("slow"); }); $('#b2').click(function() { $('#uch2').toggle("slow"); }) }) Although I'm not a program ...