如何在jQuery中设置文本框值? [英] How to set textbox value in jQuery?
问题描述
如何使用jQuery正确地将某个值加载到文本框中?尝试了下面的方法,但是得到了 [object Object]
作为输出.请对此有所启发,我是jQuery的新手.
How do I properly load the a certain value into a textbox using jQuery? Tried the one below but I get the [object Object]
as output. Please enlighten me on this, I'm new to jQuery.
proc = function(x, y) {
var str1 = $('#pid').value;
var str2 = $('#qtytobuy').value;
var str3 = $('#subtotal').load('compz.php?prodid=' + x + '&qbuys=' + y);
$('#subtotal').val(str3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="yoh" method="get">
Product id: <input type="text" name="pid" value=""><br/>
Quantity to buy:<input type="text" name="qtytobuy" value="" onkeyup="proc(document.yoh.pid.value, this.value);"></br>
Subtotal:<input type="text" name="subtotal" id="subtotal" value=""></br>
<div id="compz"></div>
</form>
推荐答案
我认为您要将呼叫响应设置为URL 'compz.php?prodid ='+ x +'& qbuys ='+ y
作为文本框的值,对吗?如果是这样,您必须执行以下操作:
I think you want to set the response of the call to the URL 'compz.php?prodid=' + x + '&qbuys=' + y
as value of the textbox right? If so, you have to do something like:
$.get('compz.php?prodid=' + x + '&qbuys=' + y, function(data) {
$('#subtotal').val(data);
});
参考: get()
您的代码中有两个错误:
You have two errors in your code:
-
load()
将 HTML从Ajax返回到指定的元素:
load()
puts the HTML returned from the Ajax into the specified element:
从服务器加载数据,然后将返回的HTML放入匹配的元素中.
Load data from the server and place the returned HTML into the matched element.
您无法使用该方法设置文本框的值.
You cannot set the value of a textbox with that method.
$(selector).load()
返回一个jQuery 对象.默认情况下,将对象视为字符串时,会将其转换为 [object Object]
.
$(selector).load()
returns the a jQuery object. By default an object is converted to [object Object]
when treated as string.
进一步的说明:
假设您的网址返回 5
.
如果您的HTML看起来像:
If your HTML looks like:
<div id="foo"></div>
然后的结果
$('#foo').load('/your/url');
将是
<div id="foo">5</div>
但是在您的代码中,您有一个输入元素.理论上(它不是有效的HTML,并且无法正常运行),等效调用会导致
But in your code, you have an input element. Theoretically (it is not valid HTML and does not work as you noticed), an equivalent call would result in
<input id="foo">5</input>
但是您实际上需要
<input id="foo" value="5" />
因此,您不能使用 load()
.您必须使用另一种方法,获取响应并将其自己设置为值.
Therefore, you cannot use load()
. You have to use another method, get the response and set it as value yourself.
这篇关于如何在jQuery中设置文本框值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!