简体   繁体   中英

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?

you could do:

<input type="button" id="s1" value="" />
<script type="text/javascript">
 var elem = document.getElementById("s1");
 elem.value = "some text";
</script>

You can also do it in an elegant way by using custom data attributes.

See a JSFiddle demo here: http://jsfiddle.net/NJ5sK/

Basically, you mark your input elements with the name of the function that should be called to return its value. Then you grab all the elements that have the data-value-function attribute, run the function and assign the value.

HTML:

<input type="text" data-value-function="cheese" />
<input type="text" data-value-function="animal" />

JS:

window.cheese = function() {
    return "Limburger";
}

window.animal = function() {
    return "Cat";
}

var elements = document.querySelectorAll('*[data-value-function]');
for (var i = 0; i < elements.length; i++) {
    var valueFunctionName = elements[i].getAttribute('data-value-function');
    elements[i].value = window[valueFunctionName]();
}

Enjoy!

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>
function test(){
    x = "some text";
    document.getElementById('s1').value = x;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM