【问题标题】:HTML select shows value instead of textHTML 选择显示值而不是文本
【发布时间】:2014-02-11 10:25:34
【问题描述】:

是否可以在html select 中显示选项的值而不是文本?

它将用于在下拉列表中显示长文本,但在选择时应仅显示短文本/选项的值。

代码:

<select>
    <option value="1">This is a long long text, that explains option 1</option>
    <option value="2">This is a long long text, that explains option 2</option>
</select>

现在,当您离开下拉菜单/组合框/其他内容时,所选项目应仅显示“1”

【问题讨论】:

  • 显示您的代码.. 这可能有助于了解您尝试过的内容
  • 我更新了问题,真的不行吗?
  • 您可能想要使用标签属性:*.com/questions/3905984/…
  • 把你的返回值代码放入 value=your_code" 就可以了。

标签: html html-select


【解决方案1】:

您可以使用标签标签来做到这一点:

<option value="the_value" label="the text displayed">the hidden text</option>

【讨论】:

  • "label" 属性在 Firefox 中不受支持。此外,您只会在下拉菜单中看到标签文本,而在关闭下拉菜单时会看到相同的文本。在该示例中,“隐藏文本”将在提交表单时发送到服务器。鉴于 value 属性的存在,它是多余的。
【解决方案2】:

这就是解决方案。

$("select option").each(function () {
    $(this).attr("data-label", $(this).text());
});
$("select").on("focus", function () {
    $(this).find("option").each(function () {
        $(this).text($(this).attr("data-label"));
    });
}).on("change mouseleave", function () {
    $(this).focus();
    $(this).find("option:selected").text($(this).val());
    $(this).blur();
}).change();

【讨论】:

  • 如果用户专注于选择元素并没有选择任何选项就离开,它不起作用。
  • @Rickyrock 你的意思是“mouseleave”在你的情况下不起作用吗?
  • @JeffreyNeo 当用户点击选择标签,但不选择其他选项保持原样。
【解决方案3】:

我找到了可能解决您的问题的解决方案:

HTML:

<select id="countryCode">
   <option data-text="his is a long long text, that explains option 1" value="1">This is a long long text, that explains option 1</option>
   <option data-text="his is a long long text, that explains option 1" value="2">This is a long long text, that explains option 1</option>
</select>

jQuery:

$('#countryCode option:selected').html($('#countryCode option:selected').attr('value')); // already changed onload

$('#countryCode').on('change mouseleave', function(){
    $('#countryCode option').each(function(){
      $(this).html( $(this).attr('data-text') ); 
    });
    $('#countryCode option:selected').html(  $('#countryCode option:selected').attr('value')   );
    $(this).blur();
});
$('#countryCode').on('focus', function(){
    $('#countryCode option').each(function(){
        $(this).html( $(this).attr('data-text') ); 
    });
});

http://jsfiddle.net/9y43gh4x/

【讨论】:

  • 在移动设备中,如果用户专注于选择元素并离开而不选择任何选项,则它不起作用,因为没有 mouseleave 事件。此外,用户能够看到文本从“his is....”更改为“1”。微秒延迟......
【解决方案4】:

我想这可能对你有帮助

<select id='cboSelect'>
 <option value="1">This is a long long text, that explains option 1</option>
 <option value="2">This is a long long text, that explains option 2</option>
</select>

试试这个jquery

$("#cboSelect").change(function(){    
   $("#cboSelect option:selected").text($("#cboSelect").val());
});

这将更改所选选项的文本及其相应的值

这是小提琴 Fiddle

【讨论】:

  • 嗯,是的,我想我想要的东西没有答案。我要去另一种方式来“解决”我的问题感谢您的回复..
  • 这将永远改变值。这不是预期的结果。
【解决方案5】:

只是不给出值:

<select>
    <option>Test</option>
</select>

选中后将提交Test

只需将您在value 中输入的值作为文本。

你不能让它像那样显示value=中的值。

【讨论】:

  • 我更新了问题,真的不行吗?