0

Let's say I have var x = "<input type='number' />". So that's a string. What I want is set a value to that input and in the end, get a string like this:

var y = "<input type='number' value='some value' />"

I have tried different methods but none of them worked the way I wanted. I have tried this:

function myFunction(){
   $(x).val(5)
   console.log(x)
   //I get an object array
}

I do not want to append the element to the DOM, just want the HTML string

1
  • Before using $(x).val() the element needs to be attached to DOM. Try attaching it to body or some element in page abd then execute this code. It should work. Commented Nov 9, 2016 at 0:54

2 Answers 2

2

You'd use attr() to set an attribute in the HTML, and outerHTML if you want the string returned, otherwise you're console logging the jQuery object, which is indeed an object.

var x = "<input type='number' />";

var y = $(x).attr('value', '5');

console.log( y.get(0).outerHTML )
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

-1

To edit the value, use jQuery prop:

$(x).prop('value') = 5;
console.log(x);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.