简体   繁体   English

仅在单击按钮后才使用JS var值

[英]Use JS var value only after a button click

I want to show which menu value was selected using JavaScript, like this: 我想显示使用JavaScript选择的菜单值,如下所示:

<script> 
document.writeln(value);
</script>

Where the JS variable called value gets defined by jQuery when a button is clicked: 单击按钮时,jQuery定义了名为value的JS变量:

$('#submit').click(function(){
    var value = $('#model').val();   

});

The problem being that the code tries to render value before it has been created by the button. 问题在于代码试图在按钮创建value之前呈现value

I know I can show/hide a div based on the button click, but even if the section with writeln is hidden it still has the same problem. 我知道我可以基于按钮单击显示/隐藏div ,但是即使隐藏了writeln的部分,它仍然存在相同的问题。 I also need to be able to change my selection, click submit, and have the value update properly. 我还需要能够更改选择,单击提交,并正确更新值。

Here's a jsFiddle illustrating the problem: 这是一个说明问题的jsFiddle:

https://jsfiddle.net/f3n7uq14/4/ https://jsfiddle.net/f3n7uq14/4/

<span id="result"></span>
<script>
$('#submit').click(function(){
    var value = $('#model').val();
    $('#result').text(value);
});
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击按钮后将Var更改为0 - Change Var to 0 after button click 在按钮单击中使var值可用 - making var value available in button click 如何使按钮仅在节点 js 和 ejs 中单击时提交值 - how to make button submit value only on click in node js and ejs 在 React 中单击按钮后仅显示输入值 - Only displaying input value after button click in React JS HTML:单击按钮后获取特定的列值 - JS HTML: Get particular column value after button click 我的显示“上一个”内容的按钮的JS代码只有在我单击“下一个”按钮两次后才能工作 - My JS code for the button that shows 'previous' content only works after I click the 'next' button twice 单击按钮后,仅使用 JS 脚本的第一部分,第二次单击后无效果 - after clicking on button only first part of JS script is used, after second click none works 我的update.js.erb文件仅在第一次单击按钮时运行,而不在随后的单击中运行(更改按钮的类和单击值) - My update.js.erb file only runs on the first button click and not on subsequent clicks (change a button's class and value on click) var newusername = $(this).val(); 只发出按钮的值 - var newusername=$(this).val(); only sends out the value of the button 页面重新加载后从 JS 的按钮单击仅有效并不一致 - Button Click from JS after page reload only works does not work consistently
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM