简体   繁体   English

未选择下拉列表中的默认值

[英]Default Value in drop down list not being selected

I have a drop down list [ Incident, Question, Problem, Task]. 我有一个下拉列表[事件,问题,问题,任务]。 I have written a code when an end user logins in and has a tag called product the default value should be problem. 当最终用户登录并有一个名为product的标签时,我已经编写了代码,默认值应该是问题。 However it does not seem to work. 但是,它似乎不起作用。 It still gives the user the option to select values from the list. 它仍然为用户提供从列表中选择值的选项。

$j(document).ready(function() {  
if(location.pathname == '/requests/new') {
var ct = currentUser.tags;

 if(ct.indexOf("product") >= 0){
 $j(document.getElementById("ticket_fields_75389").value = "Problem"); 
  }
 else {
 $j(document.getElementById("ticket_fields_75389").value = "");
 } 

 }
 })

Note: This answer is incorrect. 注意:此答案不正确。 I will delete it once I know the OP read my comment. 我知道操作员阅读了我的评论后,将其删除。


It still gives the user the option to select values from the list. 它仍然为用户提供从列表中选择值的选项。

Well, of course, setting value will only change the initially selected value. 好吧,当然,设置value只会更改初始选择的值。 If you want "fix" the value of the select element, so that the user cannot change it, you have to make it read-only . 如果要“固定” select元素的值,以使用户无法更改它,则必须将其设置为只读 Lets stick with jQuery (what you have is a weird mix of DOM API and jQuery ): 让我们坚持使用jQuery(您所拥有的是DOM API和jQuery 的怪异组合):

$j("#ticket_fields_75389").val("Problem").prop('readonly', true);

†: Let's have a close look at the line †:让我们仔细看一下这条线

$j(document.getElementById("ticket_fields_75389").value = "Problem");

What exactly is happening here? 这里到底发生了什么? Obviously we have a function call ( $j(...) ) and we pass something to it. 显然,我们有一个函数调用( $j(...) ),并将一些东西传递给它。 This "something" is the result of the expression 这种“东西”是表达的结果

document.getElementById("ticket_fields_75389").value = "Problem"

This finds an element by ID and assigns the string "Problem" to the value property. 这将通过ID查找元素,并将字符串"Problem"分配给value属性。 This is an assignment expression . 这是一个赋值表达式 The result of an assignment expression is the assigned value, ie "Problem" . 赋值表达式的结果是赋值,即"Problem"

That is the value that is passed to $j(...) , so we have $j("Problem"); 那就是传递给$j(...) ,所以我们有$j("Problem"); . Since $j refers to jQuery , this would search for all elements with tag name Problem , which does not exist in HTML. 由于$j引用jQuery ,这将搜索标记名称 Problem所有元素,而HTML中不存在。 It would also return a jQuery object, but you are not doing anything with it. 它还将返回一个jQuery对象,但您对此没有做任何事情。

Hence the wrapping in $j(...) is completely unnecessary or even wrong, even though it doesn't throw a syntax or runtime error. 因此,即使没有引发语法或运行时错误,在$j(...)的包装也是完全没有必要的,甚至是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM