Printing a JS variable in a value=“” attribute

时光总嘲笑我的痴心妄想 提交于 2019-12-20 05:54:46

问题


I'm trying to implement a Paypal button with a dynamic value. When I enter, for example, value="300.00", the button works fine.

However, if I do it my way, the button doesn't work properly. The variable price is the JS variable that holds the information I need to put into the Paypal button.

Here's the line of code at fault:

<input type="hidden" name="amount" value="<script>document.write(price)</script>.00">

回答1:


In javascript:

document.write('<input type="hidden" name="amount" value="' + price + '">')

Or better yet

var div = document.createElement('div');
div.innerHTML = '<input type="hidden" name="amount" value="' + price + '">';
document.body.appendChild(div);

DEMO




回答2:


It doesn't work because you have unclosed tags.
Notice here that you opened another tag without closing the other tag.

<*input type="hidden" name="amount" value="<*script

To achieve what you want, you need to write the entire block using JS

<script>
document.write('<input type="hidden" name="amount" value="' + price + '.00">');
</script>



回答3:


document.getElementsByName('amount')[0].value = price;

This will find the "button" and set its value to the value of the price variable. I assume that the "button" already is somewhere on the page.



来源:https://stackoverflow.com/questions/4812198/printing-a-js-variable-in-a-value-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!