猿问

无法让我的 Javascript 代码禁用加载页面上的输入框

我在 html 文件中有一个带有下拉列表的表单,当选择某个值时,该下拉列表会禁用输入框。它工作得很好,但是当用户单击表单的提交按钮时,它会在完成一些计算后刷新页面并启用输入框。我希望它保持禁用状态。我设法存储下拉列表的值,但无法对我的输入框执行相同的操作。我对 JS 的了解几乎为零,但我想出了以下脚本,我认为该脚本应该在页面重新加载时完成工作,但事实并非如此。您能告诉我下面的代码有什么问题吗?谢谢!


  <script type="text/javascript">

    $(document).ready(function() {

      var ComboboxType = document.getElementById('Type').value;

      var InputToDisable = document.getElementById("MyInput");


      if (ComboboxType.value == 'Some Value') {

          InputToDisable.disabled = true;

      }

    });


  </script>


青春有我
浏览 84回答 2
2回答

Helenr

您甚至可以在没有 jQuery 的情况下完成此操作,请参阅下面的示例。基本上,您可以使用 获取输入元素document.getElementById。然后,为了安全起见,我检查它是否存在。那么,只需禁用它即可。window.onload = function(e) {&nbsp; var input = document.getElementById("input");&nbsp; if(input) {&nbsp; &nbsp; input.disabled = true;&nbsp; }}<input name="foo" id="input" placeholder="disabled" />

呼啦一阵风

好吧,您可以在 jQuery 中创建一个 ajax 请求(据我所知,您在代码中使用了这个库)来处理刷新问题。&nbsp;https://api.jquery.com/jquery.ajax/例子:&nbsp; $("#my_form").submit(function(event){&nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault(); //prevent default action&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; var post_url = $(this).attr("action"); //get form action url&nbsp; &nbsp; &nbsp; &nbsp; var request_method = $(this).attr("method"); //get form GET/POST method&nbsp; &nbsp; &nbsp; &nbsp; var form_data = $(this).serialize(); //Encode form elements for submission&nbsp; &nbsp; &nbsp; &nbsp; $.ajax({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;url : post_url,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;type: request_method,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;data : form_data,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;success: (response) => {&nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if(response){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //do something&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

Html5
我要回答