繁体   English   中英

如何在文本框中显示传递给函数的结果

[英]How to display a result passed to a function in a textbox

我有一个函数,它从数据库中检索数据并将其返回给函数。我正在尝试从要显示在文本框中的结果中获取收入值。

这就是我尝试过的。

function Display(result) // result gets passed
{
 var income= $('#Income'); //getting the textbox;
income.value=result.Income  // when i try this result.Income,Income comes back as undefined.
 }

如何将结果中的值显示在文本框中? 这就是传递给Display函数的“结果”的外观。因此,理想情况下,“收入”的值为“工资”,因此应在文本框中显示工资。

{
ID: 0
Number: 520
OtherIncome: "Private"
Income: "Salary"
}
This is my HTML
<input type="text" name="Income" id="Income" class="text ui-widget-content ui-corner-all" value="">

 var json = { ID: 0, Number: 520, OtherIncome: "Private", Income: "Salary", } function Display(result) // result gets passed { var income = $('#Income'); //getting the textbox; income.val(result.Income) // when i try this result.Income,Income comes back as undefined. } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="Income" id="Income" class="text ui-widget-content ui-corner-all" value=""> <button onClick="Display(json)">Click</button><br> Click the button to set the textbox value. 

尝试使用income.val(result.Income)设置文本框的值。 在这里,我使用了一个按钮单击事件来生成示例。

function Display(result) {
  var income = $('#Income'); //getting the textbox;
  //income.value=result.Income  here use the .val() method
  income.val(result.Income);
}

文档: http : //api.jquery.com/val/

让我们解释一下您的代码


var json = {
  ID: 0,
  Number: 520,
  OtherIncome: "Private",
  Income: "Salary",
}

function Display(result) // result gets passed
{
  var income = $('#Income'); //getting the textbox;
  income.val(result.Income) // when i try this result.Income,Income comes back as undefined.
}

您有一个存储在variable json的数据对象。 然后是一个带有参数的函数Display(param) 然后在您的函数中,您尝试访问empty参数。 参数结果是一个变量,尚未定义。 因此,实际上它的值是undefined。 因此,为什么在调用display时不传递任何参数而得到未定义的原因。 假设您在函数调用中输入了有效参数,那么您将获得正确的结果。

例:


var json = {
  ID: 0,
  Number: 520,
  OtherIncome: "Private",
  Income: "Salary",
}


//invoke you function with the json data
Display(json)
//this should work perfectly.


//you can even remove the function and just make it

var income = $('#Income'); 
 income.val(json.Income);

//But you only do this if you want to get the value once



暂无
暂无

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

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