【问题标题】:Changing the selected text of a select box in javascript在javascript中更改选择框的选定文本
【发布时间】:2014-12-19 19:11:09
【问题描述】:

我有一个功能,如果用户在选择框中将 IP 更改为未分配,则会弹出一个警报,询问他们是否确定,在取消此警报时,我希望 select2 框改回原来的状态(即分配等)。

我已经能够通过将原始值存储在一个变量中来更改 select2 框的值,然后在取消警报时将其分配给 select 的值

else
    $('#ip_status').val(original_status)

但是,尽管这确实会更改 select2 框的值,这意味着该功能正在运行,但 select2 框中的文本仍保持“未分配”状态,从而给最终用户带来误导性的值。请记住 .text(" example ") 不起作用。

谢谢。

完整代码 -

original_status = document.getElementById('ip_status').value
$('#ip_status').change ->

# If the user changes ip status to unallocated, clear and hide system name and description fields.
if parseInt($('#ip_status').val()) == 0

  r = confirm("You are about to unallocate this IP! Are you sure you want to do this?")
  if r == true
    $('#ip_description').val("").parent().hide()
    $('#ip_system_name').val("").parent().hide()

  else
    $('#ip_status').val(original_status)
else
  # if the select changes to allocated or reserved, re-show the fields that were hidden
  $('#ip_description').parent().show()
  $('#ip_system_name').parent().show()

【问题讨论】:

  • 能否提供您正在使用的现有代码
  • 请查看更新后的代码
  • 您的问题与 Coffeescript 有什么关系?我看到的只是 JQuery。
  • @AlexisDufrenoy 不是$('#ip_status').change ->coffeescript 吗? -> 部分。 -> 表示我相信的功能。
  • 是的,这都是coffeescript,你可以在这个文件中通过'$'来引用dom元素。 'ips.js.coffee'。我还在一些文档中找到了我自己问题的答案。

标签: javascript html coffeescript


【解决方案1】:

你必须使用类似的东西:

$( function() {
    $("#your_option").attr("selected", "selected");
});

【讨论】:

    【解决方案2】:

    我可以通过改变来解决这个问题

    $('#ip_status').val(original_status)
    

    $("#ip_status").select2("val", original_status)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-03
      • 2013-03-23
      • 2016-09-28
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多