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?
you could do:
<input type="button" id="s1" value="" />
<script type="text/javascript">
var elem = document.getElementById("s1");
elem.value = "some text";
</script>
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
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With