Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return the value of a JS function and use it as the value for an input button

I want to set a JavaScript function which returns a string, and that string to be used as a value for a button. Something like this:

function test(){
 x = "some text";
 return x;
}

I want to use this function in a input element in the value attribute. Something like this:

<input type="button" id="s1" value="test()" />

Unfortunatly the button doesn't show "some text" but "test()" on the button. How can i fix this?

like image 981
Julian Avatar asked Apr 23 '13 11:04

Julian


3 Answers

you could do:

<input type="button" id="s1" value="" />
<script type="text/javascript">
 var elem = document.getElementById("s1");
 elem.value = "some text";
</script>
like image 50
Sudhir Bastakoti Avatar answered Sep 22 '22 11:09

Sudhir Bastakoti


The correct way to set the value of the button would be to use the HTML DOM, or a framework like JQuery. This also has a JSBin Demo.

For example,

HTML - Runs function test when document loads.

<body onload = "test()">
  <input type="button" id="s1" value="" />
</body>

JavaScript -

function test(){
 x = "some text";
 document.getElementById("s1").value =x;
}

View JSBin Demo

like image 24
KernelPanik Avatar answered Sep 19 '22 11:09

KernelPanik


value attribute for html button accepts only text. see here.

What I understand from your question is you want a html button whose value should be set by a javascript function. you can achieve this the other way around.

Get button element using document.getElementById and set the value inside the test()

you code should looks like this:

<input type="button" id="s1"/>

<script>
   function test(){
      document.getElementById('s1').value ='some text'; //s1 is the id of html button
   };
   test(); //dont forget to call function
</script>
like image 32
rkm Avatar answered Sep 21 '22 11:09

rkm