geekth geekth - 28 days ago 9
Javascript Question

Change HTML input value and getting the a HTML string with jQuery

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

Answer

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>