programing

jquery를 사용하여 드롭다운 읽기만 만드는 방법은 무엇입니까?

linuxpc 2023. 8. 14. 22:33
반응형

jquery를 사용하여 드롭다운 읽기만 만드는 방법은 무엇입니까?

나는 다음 문장을 읽기 전용으로 사용하고 있지만 작동하지 않습니다.

$('#cf_1268591').attr("readonly", "readonly"); 

사용할 수 없도록 설정하지 않고 읽기 전용으로 설정합니다.

$('#cf_1268591').attr("disabled", true); 

드롭다운은 항상 읽기 전용입니다. 사용하지 않도록 설정할 수 있습니다.

폼으로 작업할 경우 비활성화된 필드가 제출되지 않으므로 숨겨진 필드를 사용하여 비활성화된 드롭다운 값을 저장합니다.

저도 같은 문제가 있었습니다. 제 해결책은 선택하지 않은 모든 옵션을 비활성화하는 것이었습니다.jQuery를 사용하면 매우 간단합니다.

$('option:not(:selected)').attr('disabled', true);

편집 => 한 페이지에 여러 개의 드롭다운이 있는 경우 아래와 같이 select-ID에서 선택되지 않은 옵션을 모두 비활성화합니다.

$('#select_field_id option:not(:selected)').attr('disabled', true);

이것이 당신이 찾고 있는 것입니다.

$('#cf_1268591').attr("style", "pointer-events: none;");

매력적으로 작동합니다.

이거 한번...선택한 값을 비활성화하지 않고..

$('#cf_1268591 option:not(:selected)').prop('disabled', true);

저한테는 효과가 있어요.

필드를 사용할 수 없게 만들 것입니다.그런 다음 양식이 제출될 때 사용 불가능으로 설정합니다.제 생각에 이것은 숨겨진 분야를 다루는 것보다 쉽습니다.

//disable the field
$("#myFieldID").prop( "disabled", true );           

//right before the form submits, we re-enable the fields, to make them submit.
$( "#myFormID" ).submit(function( event ) {
    $("#myFieldID").prop( "disabled", false );
});     

를 사하을용으로 disabled, 데이터는 제출하지 않습니다.select요에없이 .readonly.

시뮬레이션할 수 있습니다.readonlyselect스타일 설정을 위해 CSS를 사용하고 탭 변경을 방지하기 위해 JS를 사용합니다.

select[readonly] {
  background: #eee;
  pointer-events: none;
  touch-action: none;
}

그런 다음 다음과 같이 사용합니다.

var readonly_select = $('select');
$(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
    $(i.target).val($(this).attr('data-original-value'));
});

결과:

  // Updated 08/2018 to prevent changing value with tab
$('a').on('click', function() {
var readonly_select = $('select');
$(readonly_select).attr('readonly', true).attr('data-original-value', $(readonly_select).val()).on('change', function(i) {
	$(i.target).val($(this).attr('data-original-value'));
});
});
select[readonly] {
  background: #eee;
  pointer-events: none;
  touch-action: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#">Click here to enable readonly</a>
<select>
<option>Example 1</option>
<option selected>Example 2</option>
<option>Example 3</option>
</select>

선택하지 않은 옵션을 제거하는 단순 jquery입니다.

$('#your_dropdown_id option:not(:selected)').remove();

문제를 단순화하기 위해 번거로움 없이 수행할 수 있는 jQuery 플러그인이 있습니다. https://github.com/haggen/readonly

은 " 라은다사선택다니합여용하을음이"로 합니다.readonly속성 읽기 전용:

$('select[readonly=readonly] option:not(:selected)').prop('disabled', true);

효과가 아주 좋습니다

$('#cf_1268591 option:not(:selected)').prop('disabled', true);

옵션을 볼 수 있지만 선택할 수 없습니다.

가장 쉬운 옵션은 읽기 전용으로 선택하고 다음을 추가하는 것이었습니다.

onmousedown="return false" onkeydown="return false"

당신은 추가적인 논리를 쓸 필요가 없습니다.숨김 입력이 없거나 양식 제출 시 비활성화된 후 다시 활성화됩니다.

이것이 오래된 주제인 것은 알지만, 선택 필드를 사용 불가능으로 설정하지 않고 읽기 전용으로 설정하려는 다른 사용자를 위해 응답해야 한다고 생각했습니다.

선택 필드에는 읽기 전용 특성이 있을 수 없습니다.제가 찾은 가장 좋은 방법은 CSS를 사용하는 것이었습니다.

이렇게 하면 선택 필드가 값을 제출하는 동안 읽기 전용으로 작동합니다.

필드를 읽기 전용으로 사용하려면:

$("#FieldId").css({"pointer-events": "none", "touch-action": "none", "background": "#ede6e6"});

필드를 실행 가능으로 설정하려면:

$("#FieldId").css({"pointer-events": "auto", "touch-action": "auto", "background": "#ffffff"});

또한 접근 단계에 따라 읽기 전용으로 만들어야 하는 필드가 여러 개 있는 양식이 있을 경우 변수로 선언하여 이 필드를 사용합니다.E.G PHP

if($UserAccess == "Limited"){
$ReadOnlyFields = "style='pointer-events:none;touch-action:none;background:#ede6e6;'";
}

<select name='TheField' <?php if(!empty($ReadOnlyFields)){echo $ReadOnlyFields;} ?>>

이 코드는 먼저 각 드롭다운에 원래 선택 항목을 저장합니다.그런 다음 사용자가 선택을 변경하면 드롭다운이 원래 선택으로 재설정됩니다.

http://jsfiddle.net/4aHcD/22/

//store the original selection
$("select :selected").each(function(){
    $(this).parent().data("default", this);
});

//change the selction back to the original
$("select").change(function(e) {
    $($(this).data("default")).prop("selected", true);
});

그것은 오래된 물건이지만, 저는 그것을 찾을 사람들에게 경고하고 싶습니다.이름별로 got 요소가 있는 비활성화된 특성에 주의하십시오.이상하지만 별로 효과가 없는 것 같습니다.

작동하지 않습니다.

<script language="JavaScript">
function onChangeFullpageCheckbox() {    
$('name=img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>

이 작업:

<script language="JavaScript">
function onChangeFullpageCheckbox() {    
$('#img_size').attr("disabled",$("#fullpage").attr("checked"));
</script>

네, 저는 속성이 아닌 프롭을 사용하는 것이 낫다는 것을 알고 있습니다. 하지만 적어도 지금은 오래된 버전의 jquery 때문에 프롭이 작동하지 않을 것이고, 지금은 업데이트할 수 없습니다. 왜 그런지 묻지 마세요.html 차이는 ID만 추가됩니다. ...

<select name="img_size" class="dropDown" id="img_size">
<option value="200">200px
</option><option value="300">300px
</option><option value="400">400px
</option><option value="500">500px
</option><option value="600" selected="">600px
</option><option value="800">800px
</option><option value="900">900px
</option><option value="1024">1024px
</option></select>

<input type="checkbox" name="fullpage" id="fullpage" onChange="onChangeFullpageCheckbox()" />

...

나는 스크립트에서 오류를 발견하지 못했고, 이름이 있는 버전에서는 콘솔에서 오류가 없었습니다.하지만 물론 그것은 내 코드의 실수일 수 있습니다.

표시됨: Win 7 Pro의 Chrome 26

문법이 안좋아서 죄송합니다.

이를 위한 더 나은 방법은 CSS를 사용하여 포인터 이벤트를 제거하고 드롭다운의 불투명도를 수정하는 것입니다(0.5 시도).이렇게 하면 사용자가 정상적으로 비활성화된 것처럼 보이지만 여전히 데이터를 게시합니다.

물론 이전 버전과의 호환성에 문제가 있지만 성가신 비활성화/읽기 전용 문제를 피하는 것보다 더 나은 선택이라고 생각합니다.

또한 사용하지 않도록 설정하고 제출 호출을 사용하도록 설정할 수 있습니다.가장 쉬운 방법이라고 생각합니다 :)

@Kanishka가 말했듯이, 우리가 양식 요소를 비활성화하면 제출되지 않을 것입니다.이 문제에 대한 토막글을 만들었습니다.선택 요소가 비활성화되면 숨겨진 입력 필드가 생성되고 값이 저장됩니다.활성화되면 생성된 숨겨진 입력 필드를 삭제합니다.

추가 정보

jQuery(document).ready(function($) {
  var $dropDown = $('#my-select'),
    name = $dropDown.prop('name'),
    $form = $dropDown.parent('form');

  $dropDown.data('original-name', name); //store the name in the data attribute 

  $('#toggle').on('click', function(event) {
    if ($dropDown.is('.disabled')) {
      //enable it 
      $form.find('input[type="hidden"][name=' + name + ']').remove(); // remove the hidden fields if any
      $dropDown.removeClass('disabled') //remove disable class 
        .prop({
          name: name,
          disabled: false
        }); //restore the name and enable 
    } else {
      //disable it 
      var $hiddenInput = $('<input/>', {
        type: 'hidden',
        name: name,
        value: $dropDown.val()
      });
      $form.append($hiddenInput); //append the hidden field with same name and value from the dropdown field 
      $dropDown.addClass('disabled') //disable class
        .prop({
          'name': name + "_1",
          disabled: true
        }); //change name and disbale 
    }
  });
});
/*Optional*/

select.disabled {
  color: graytext;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="#" name="my-form">
  <select id="my-select" name="alpha">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
  </select>
</form>
<br/>
<button id="toggle">toggle enable/disable</button>

읽기 전용 드롭다운은 없습니다.변경할 때마다 수동으로 첫 번째 값으로 재설정할 수 있습니다.

$("select").change(function(event) {
    $(this).val($(this).find("option").first().val());
});

http://jsfiddle.net/4aHcD/

할 때 빈 을 만들어 .

Html은 다음과 같습니다.

<input id="cf_1268591" style="width:60px;line-height:16px;border:1px solid #ccc">

Jquery는 다음과 같습니다.

$("#cf_1268591").combobox({
  url:"your url",
  valueField:"id",
  textField:"text",
  panelWidth: "350",
  panelHeight: "200",
});

빈 문자열로 키업 후 만들기

var tb = $("#cf_1268591").combobox("textbox");
  tb.bind("keyup",function(e){
  this.value = "";
});

이런 식으로 시도해 볼 수도 있습니다.

function myFunction()
{
   $("select[id^=myID]").attr("disabled", true);
   var txtSelect = $("select[id^=myID] option[selected]").text();
}

드롭다운의 첫 번째 값이 기본값으로 설정되며 읽기 전용인 것 같습니다.

html5 지원:

`
     $("#cCity").attr("disabled", "disabled"); 
     $("#cCity").addClass('not-allow');

`

다음은 비활성화 사용을 제안하는 다른 답변에 대한 약간의 변형입니다.비활성화된 특성은 실제로 어떤 값도 가질 수 있지만 여전히 비활성화되어 있기 때문에 비활성화된="읽기 전용"과 같이 읽기 전용으로 설정할 수 있습니다.이렇게 하면 평소처럼 컨트롤이 비활성화되고 다음과 같은 CSS를 사용하여 일반 비활성화된 컨트롤과 다른 스타일을 쉽게 설정할 수 있습니다.

select[disabled=readonly] {
    .... styles you like for read-only
}

제출할 데이터를 포함하려면 다른 답변에서 자세히 설명한 대로 제출하기 전에 숨겨진 필드를 사용하거나 사용 가능으로 설정합니다.

사용해 보십시오.

$('#Dropdown').attr('readonly', true);
$('#Dropdown').css('pointer-events','none');

언급URL : https://stackoverflow.com/questions/8100351/how-to-make-a-dropdown-readonly-using-jquery

반응형