简体   繁体   中英

value from span to input

I have value that is displayed in span tag. If i want to post the value i have to assign that value to an input. So this is the code i have written to assign value to input and trying to post that value. But when i alert the assigned value its showing as

[object Object] 

Pls check the code and correct me.

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);

and i tried this also

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower);

Both the above code shows

[object Object] 

Because of this i am not able to post values.

That is because the value setter function on an input return the jQuery object of that input element only, it allows you to chain the event.

Try this

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Read more about it here http://api.jquery.com/val/#val-value

"lower" is an object. if you want to see the text inside, you need to call lower.val(). eg

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

jQuery supports chaining objects return.

So, whenever you do an operation on an object (except some like .val() getter, it returns object of that selector element.

So, you can do much more operations in a single statement.

In your statement,

var lower=$("#inputElement").val(value);
alert(lower);,

It is returning the object of element #lower .

You can add more operations to it.

For example:

var lower=$("#inputElement").val(value).css('color', 'red');

You want only plain value.

So, rather you should do this:

var value = $("#spanElement").text();
$("#inputElement").val(value);
var lower=$("#inputElement").val();
alert(lower);

Just do in this way..

var span_text = $("#spanElement").text(); //get span text
$("#inputElement").val(span_text); //set span text to input value
var input_value = $("#inputElement").val(); //get input value
alert(input_value); //alert input value

Hope this will help

This is because it will return a jQuery object . If you want to see the same text which is in the input you can either use .val() like answered previously or use like this

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert($("#spanElement").prop('innerHTML'));

WORKING DEMO

You are getting 'Object Object' because lower is an object if you want to get the text you need to perform below actions.

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Or

var value = $("#spanElement").text();
var lower=$("#inputElement").val(value);
alert(lower.val());

Hope it helps !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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