Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
348 views
in Technique[技术] by (71.8m points)

javascript - How to set textbox value in 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
});

Reference: get()

You have two errors in your code:

  • load() puts the HTML returned from the Ajax into the specified element:

    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() returns the a jQuery object. By default an object is converted to [object Object] when treated as string.

Further clarification:

Assuming your URL returns 5.

If your HTML looks like:

<div id="foo"></div>

then the result of

$('#foo').load('/your/url');

will be

<div id="foo">5</div>

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>

But you actually need

<input id="foo" value="5" />

Therefore, you cannot use load(). You have to use another method, get the response and set it as value yourself.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...