簡體   English   中英

如何將選擇元素設置為只讀(“禁用”不會在服務器上傳遞選擇值)

[英]how to set select element as readonly ('disabled' doesnt pass select value on server)

當我使用以下任何代碼時, select元素確實看起來像禁用了,但選擇沒有在服務器上傳遞:我在考慮要使用的readonly ,但我不知道或者是否會解決問題。 任何幫助深表感謝。

$('#selectID').prop('disabled',true);

$('#selectID').prop('disabled','disabled');

$('#selectID').attr('disabled',true);

$('#selectID').attr('disabled','disabled');

看到這個答案- HTML 表單只讀 SELECT 標簽/輸入

您應該禁用 select 元素,但還要添加另一個具有相同名稱和值的隱藏輸入。

如果您重新啟用 SELECT,您應該將它的值復制到 onchange 事件中的隱藏輸入。

請參閱此小提琴以演示如何將禁用選擇中的選定值提取到將在表單中提交的隱藏字段中。

 $(function() { var select_val = $('#sel_test option:selected').val(); $('#hdn_test').val(select_val); $('#output').text('Selected value is: ' + select_val); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <select disabled="disabled" id="sel_test"> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> </select> <input type="hidden" id="hdn_test" /> <div id="output"></div>

希望有幫助。

為了能夠通過select ,我只是將它設置回:

  $('#selectID').prop('disabled',false);

或者

  $('#selectID').attr('disabled',false);

傳遞請求時。

您可以使用 CSSpointer-events 屬性模擬只讀選擇框:

select[readonly]
{
    pointer-events: none;
}

HTML tabindex 屬性也將阻止它被鍵盤 tab 鍵選中:

<select tabindex="-1">

 select[readonly] { pointer-events: none; } /* irrelevent styling */ * { box-sizing: border-box; } *[readonly] { background: #fafafa; border: 1px solid #ccc; color: #555; } input, select { display:block; width: 20rem; padding: 0.5rem; margin-bottom: 1rem; }
 <form> <input type="text" value="this is a normal text box"> <input type="text" readonly value="this is a readonly text box"> <select readonly tabindex="-1"> <option>This is a readonly select box</option> <option>Option 2</option> </select> <select> <option>This is a normal select box</option> <option>Option 2</option> </select> </form>

提交時不禁用選定的值..

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

If you use Jquery version lesser than 1.7
$('#selectID option:not(:selected)').attr('disabled', true);

這個對我有用..

為了簡化事情,這里有一個可以實現這個目標的 jQuery 插件: https : //github.com/haggen/readonly

  1. 在您的項目中包含 readonly.js。 (也需要jquery)
  2. .attr('readonly', 'readonly')替換為.readonly() 就是這樣。

    例如,從$(".someClass").attr('readonly', 'readonly'); $(".someClass").readonly(); .

select[readonly] {
  background: #eee; /*Simular campo inativo - Sugestão @GabrielRodrigues*/
  pointer-events: none;
  touch-action: none;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM