在javascript中更改选择框的选定文本

时间:2014-12-19 10:51:12

标签: javascript html coffeescript

我有一个功能,如果用户更改了要在选择框中取消分配的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()

2 个答案:

答案 0 :(得分:0)

你必须使用类似的东西:

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

答案 1 :(得分:0)

我可以通过更改

来解决这个问题
$('#ip_status').val(original_status)

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