programing

jQuery UI 대화상자에서 버튼을 비활성화하려면 어떻게 해야 합니까?

bestprogram 2023. 9. 9. 09:45

jQuery UI 대화상자에서 버튼을 비활성화하려면 어떻게 해야 합니까?

jQuery UI 대화상자에서 버튼을 비활성화하려면 어떻게 해야 합니까?위 링크의 어떤 설명서에서도 찾을 수 없는 것 같습니다.

모달 컨펌("Confirm", "Cancel") 버튼 2개가 있습니다.경우에 따라서는 "확인" 버튼을 비활성화하고 싶습니다.

Nick Craver가 제시한 답변의 첫 번째 부분과 유사한 이 연결된 질문에서도 누구나 이 해결책을 제안한 것 같습니다.

$("#dialog").dialog({
    width: 480,
    height: "auto",
    buttons: [
        {
            id: "button-cancel",
            text: "Cancel",
            click: function() {
                $(this).dialog("close");
            }
        },
        {
            id: "button-ok",
            text: "Ok",
            click: function() {
                $(this).dialog("close");
            }
        }
    ]
});

그런 다음 다른 곳에서 jquery UI 버튼에 대한 API를 사용할 수 있습니다.

$("#button-ok").button("disable");

jQuery UI에 포함된 플러그인/위젯을 포함하는 경우(전체 라이브러리가 있고 1.8+에 있는 경우), 이를 사용하여 버튼을 비활성화하고 시각적으로 상태를 업데이트할 수 있습니다.

$(".ui-dialog-buttonpane button:contains('Confirm')").button("disable");

여기서 한 번 시도해 볼 수 있습니다... 또는 이전 버전이거나 버튼 위젯을 사용하지 않는 경우 다음과 같이 비활성화할 수 있습니다.

$(".ui-dialog-buttonpane button:contains('Confirm')").attr("disabled", true)
                                              .addClass("ui-state-disabled");

특정 대화상자 안에서 사용하려면 ID로 표시한 다음 다음 작업을 수행합니다.

$("#dialogID").next(".ui-dialog-buttonpane button:contains('Confirm')")
              .attr("disabled", true);

다른 경우에는 위양성을 제공할 수 있지만, 여기서는 두 개의 버튼을 알고 있기 때문에 너무 많이 사용할 수 있습니다.다른 상황에서 그런 경우라면 다음과 같습니다.

$("#dialogID").next(".ui-dialog-buttonpane button").filter(function() {
  return $(this).text() == "Confirm";
}).attr("disabled", true);

이것은 방지할 것입니다.:contains()다른 것의 부분 문자열을 맞추는 것에서.

not now documented 를 사용할 수도 있습니다.disabled특성:

$("#element").dialog({
    buttons: [
    {
        text: "Confirm",
        disabled: true,
        id: "my-button-1"
    }, 
    {
        text: "Cancel",
        id: "my-button-2",
        click: function(){            
               $(this).dialog("close");
        }  

    }]
});

대화 상자가 열린 후 활성화하려면 다음을 사용합니다.

$("#my-button-1").attr('disabled', false);

JsFiddle: http://jsfiddle.net/xvt96e1p/4/

다음은 버튼 클릭 기능 내에서 작동합니다.

$(function() {
    $("#dialog").dialog({
        height: 'auto', width: 700, modal: true,
        buttons: {
            'Add to request list': function(evt) {

                // get DOM element for button
                var buttonDomElement = evt.target;
                // Disable the button
                $(buttonDomElement).attr('disabled', true);

                $('form').submit();
            },
            'Cancel': function() {
                $(this).dialog('close');
            }
        }
    });
}

이 코드는 버튼을 'YOUR_BUTTON_LABLE'로 비활성화합니다. contains()에서 이름을 바꿀 수 있습니다.

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("disable");

'YOUR_BUTTON_LABLE'을 버튼의 라벨로 바꿉니다.가능하게 하다

$(".ui-dialog-buttonpane button:contains('YOUR_BUTTON_LABEL')").button("enable");

버튼은 클래스에 의해 식별됩니다.ui-button. 단추를 비활성화하려면:

$("#myButton").addClass("ui-state-disabled").attr("disabled", true);

대화상자를 동적으로 만들지 않는 한(가능한) 단추의 위치를 알 수 있습니다.첫번째 단추를 비활성화하려면:

$("#myButton:eq(0)").addClass("ui-state-disabled").attr("disabled", true);

ui-state-disabled수업은 그 멋진 희미한 스타일의 버튼을 주는 것입니다.

저는 이 작업을 좀 더 쉽게 하기 위해 jQuery 기능을 만들었습니다.아마 지금 더 좋은 해결책이 있을 겁니다어쨌든 여기 2센트 있습니다.:)

JS 파일에 추가하기만 하면 됩니다.

$.fn.dialogButtons = function(name, state){
var buttons = $(this).next('div').find('button');
if(!name)return buttons;
return buttons.each(function(){
    var text = $(this).text();
    if(text==name && state=='disabled') {$(this).attr('disabled',true).addClass('ui-state-disabled');return this;}
    if(text==name && state=='enabled') {$(this).attr('disabled',false).removeClass('ui-state-disabled');return this;}
    if(text==name){return this;}
    if(name=='disabled'){$(this).attr('disabled',true).addClass('ui-state-disabled');return buttons;}
    if(name=='enabled'){$(this).attr('disabled',false).removeClass('ui-state-disabled');return buttons;}
});};

클래스가 '대화 상자'인 대화 상자에서 '확인' 단추 사용 안 함:

$('.dialog').dialogButtons('Ok', 'disabled');

모든 버튼 활성화:

$('.dialog').dialogButtons('enabled');

'닫기' 버튼을 활성화하고 색상을 변경합니다.

$('.dialog').dialogButtons('Close', 'enabled').css('color','red');

모든 단추의 텍스트 빨간색:

$('.dialog').dialogButtons().css('color','red');

도움이 되길 바라요 :)

function getDialogButton( jqUIdialog, button_names )
{
    if (typeof button_names == 'string')
        button_names = [button_names];
    var buttons = jqUIdialog.parent().find('.ui-dialog-buttonpane button');
    for (var i = 0; i < buttons.length; i++)
    {
        var jButton = $( buttons[i] );
        for (var j = 0; j < button_names.length; j++)
            if ( jButton.text() == button_names[j] )
                return jButton;
    }

    return null;
}

function enableDialogButton( jqUIdialog, button_names, enable )
{
    var button = getDialogButton( jqUIdialog, button_names );
    if (button == null)
        alert('button not found: '+button_names);
    else
    {
        if (enable)
            button.removeAttr('disabled').removeClass( 'ui-state-disabled' );
        else
            button.attr('disabled', 'disabled').addClass( 'ui-state-disabled' );
    }
}

단추 배열을 덮어쓰고 필요한 단추만 남겨둘 수 있습니다.

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

이를 통해 첫 번째 단추를 비활성화할 수 있습니다.

$('.ui-dialog-buttonpane button:first').attr('disabled', 'disabled');

은 입니다.Cancel: function(e) { $(e.target).attr( "disabled","disabled" ); }

이것이 제가 찾은 가장 짧고 쉬운 방법입니다.

녹아웃을 사용한다면, 이것은 더 깨끗합니다.다음과 같은 것이 있다고 생각해 보십시오.

var dialog = $('#my-dialog').dialog({
    width: '100%',
    buttons: [
        { text: 'Submit', click: $.noop, 'data-bind': 'enable: items() && items().length > 0, click: onSubmitClicked' },
        { text: 'Enable Submit', click: $.noop, 'data-bind': 'click: onEnableSubmitClicked' }
    ]
});

function ViewModel(dialog) {
    var self = this;

    this.items = ko.observableArray([]);

    this.onSubmitClicked = function () {
        dialog.dialog('option', 'title', 'On Submit Clicked!');
    };

    this.onEnableSubmitClicked = function () {
        dialog.dialog('option', 'title', 'Submit Button Enabled!');
        self.items.push('TEST ITEM');
        dialog.text('Submit button is enabled.');
    };
}

var vm = new ViewModel(dialog);
ko.applyBindings(vm, dialog.parent()[0]); //Don't forget to bind to the dialog parent, or the buttons won't get bound.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div id="my-dialog">
  Submit button is disabled at initialization.
</div>

마법은 jQuery UI 소스에서 가져온 것입니다.

$( "<button></button>", props )

기본적으로 버튼 객체를 통해 임의의 jQuery 인스턴스 함수를 호출할 수 있습니다.

예를 들어 HTML을 사용하려는 경우:

{ html: '<span class="fa fa-user"></span>User' }

또는 단추에 클래스를 추가하려는 경우(여러 방법으로 작업할 수 있음):

{ addClass: 'my-custom-button-class' }

아마 당신은 미쳤을 것이고, 당신은 버튼이 맴돌 때 돔에서 버튼을 제거하고 싶을 것입니다.

{ mouseover: function () { $(this).remove(); } }

이런 수많은 스레드에서 아무도 이에 대해 언급하지 않은 것 같아 정말 놀랍습니다.

이게 내겐 통했어요..

$("#dialog-confirm").html('Do you want to permanently delete this?');
$( "#dialog-confirm" ).dialog({
    resizable: false,
    title:'Confirm',
    modal: true,
    buttons: {
        Cancel: function() {
            $( this ).dialog( "close" );
        },
        OK:function(){
            $('#loading').show();
            $.ajax({
                    type:'post',
                    url:'ajax.php',
                    cache:false,
                    data:{action:'do_something'},
                    async:true,
                    success:function(data){
                        var resp = JSON.parse(data);
                        $("#loading").hide();
                        $("#dialog-confirm").html(resp.msg);
                        $( "#dialog-confirm" ).dialog({
                                resizable: false,
                                title:'Confirm',
                                modal: true,
                                buttons: {
                                    Close: function() {
                                        $( this ).dialog( "close" );
                                    }
                                }
                        });
                    }
                });
        }
    }
}); 

대화상자를 구성할 때 버튼을 비활성화할 수 있습니다.

$(function() {
  $("#dialog").dialog({
    modal: true,
    buttons: [
      { text: "Confirm", click: function() { $(this).dialog("close"); }, disabled: true },
      { text: "Cancel", click: function() { $(this).dialog("close"); } }
    ]
  });
});
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<div id="dialog" title="Confirmation">
  <p>Proceed?</p>
</div>

또는 대화상자가 만들어진 후 언제든지 비활성화할 수 있습니다.

$(function() {
  $("#dialog").dialog({
    modal: true,
    buttons: [
      { text: "Confirm", click: function() { $(this).dialog("close"); }, "class": "confirm" },
      { text: "Cancel", click: function() { $(this).dialog("close"); } }
    ]
  });
  setTimeout(function() {
    $("#dialog").dialog("widget").find("button.confirm").button("disable");
  }, 2000);
});
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>

<div id="dialog" title="Confirmation">
  <p>Button will disable after two seconds.</p>
</div>

언급URL : https://stackoverflow.com/questions/3646408/how-can-i-disable-a-button-on-a-jquery-ui-dialog