Nmarediya Nmarediya - 27 days ago 9
HTML Question

how can I print javascript variable in input type textbox value

<script type="text/javascript">
var str = "abc,def,ghi,jkl,mno,pqr";
var x = str.split(",");
alert(x[0]); // It will alert abc from array.
</script>


I have input
type='text'
in the body tag like

<input id="txtOne" name="txtOne" type="text" value="I want to print here using javascript x[0]" />

<input id="txtOne" name="txtOne" type="text" value="I want to print here using javascript x[1]" />


I want to print variable in value property of input type textbox.

I want this
value="<script>document.write(x[0]);</script>"

not a script block in the head tag or elsewhere.

Thanks.

Answer

At first change your inputs to these

<input class='txt' name='txtOne' type='text' data-number='0' />
<input class='txt' name='txtTwo' type='text' data-number='1' />

Then

var str = "abc,def,ghi,jkl,mno,pqr";
var x = str.split(",");

$.each($('.txt'), function(key, value){
    var number = parseInt($(value).data('number'));
    $(value).val(x[number]);
})
Comments