Javascript 如果文本框不为空,则拒绝刷新页面

Javascript 如果文本框不为空,则拒绝刷新页面,javascript,jquery,Javascript,Jquery,如果文本框不为空,请选中该文本框,否则请刷新页面 我试图检查文本框的id是否为==null,然后页面将每5秒刷新一次,如果!=null或不为空页面不刷新 根据20yco的要求,完整代码如下: {% block body %} <head> <link rel="stylesheet" type="text/css" href="{% static '/css/simpleInformation.css' %}"> <link rel="styles

如果文本框不为空,请选中该文本框,否则请刷新页面

我试图检查文本框的id是否为==null,然后页面将每5秒刷新一次,如果!=null或不为空页面不刷新

根据20yco的要求,完整代码如下:

{% block body %}
<head>

    <link rel="stylesheet" type="text/css" href="{% static '/css/simpleInformation.css' %}">
    <link rel="stylesheet" type="text/css" href="{% static '/css/simpleInformationSearch.css' %}">

</head>

<body>
{#   refresh the page each 50 second   #}
<script type="text/javascript">

// if($('#opinion').val() == null ){
//     window.setInterval(function () {
//         location.href = " ";
//     }, 5000);
// } 

var myTimer = setInterval('window.location.reload()', 5000);

 $('#opinion').on('keyup change', function(){
    if( $(this).val().length == '' ) {
        myTimer = setInterval('window.location.reload()', 5000);
    } else {
        clearInterval(myTimer);
    }
 });


</script>

<form class="form-style-9">
      <!-- {{ Queryresult }} -->

<table border="1" style=" border-style:solid; width: 100%; ">
<thead>
<tr style=" text-align: center; padding: 8px; background-color: #4CAF50;
  color: white;">
    <th style=" text-align: center; padding: 8px; background-color: #2D77A2;
  color: white;">
add opinion
    </th>
    <th style=" text-align: center; padding: 8px; background-color: #2D77A2;
  color: white;" >
            num
    </th>
    <th style=" text-align: center; padding: 8px; background-color: #2D77A2;
  color: white;">
        title
    </th>
    <th style=" text-align: center; padding: 8px; background-color: #2D77A2;
  color: white;">
        date
    </th>
    <th style=" text-align: center; padding: 8px; background-color: #2D77A2;
  color: white;">
        description
    </th>
</tr>
</thead>
{% for item in Queryresult %}

    <tr style=" text-align: center; padding: 8px;">
    <td style=" text-align: center;" >
        <a href="#" class="te2">
                 {{ item.te2chira_id }}
        </a>
    </td>
        <td style=" text-align: center;">
  {{ item.num }}
    </td>
    <td style=" text-align: center;">
        {{ item.title }}
    </td>
    <td style=" text-align: center;">
        {{ item.te2chira_date }}
    </td>
    <td style=" text-align: center;">
        {{ item.description }}
    </td>
    </tr>

{% endfor %}
</table>
<br>
<br>
<ul>
<li>
    <input type="hidden" id="theid">

    <input type="date" name="field2" class="field-style field-split align-left" placeholder="date" id="date" readonly/>

</li>

<li>
    <input type="number" name="field3" class="field-style field-split align-right" placeholder="num" id="num" readonly/>
</li>
<li>
<input type="text" name="field4" class="field-style field-full align-none" placeholder="title" id="title" readonly/>
</li>
<li>
<textarea name="field5" class="field-style" placeholder="description" id="text" readonly></textarea>
</li>
<li>
    <table id="opinions_table" class="searchte2chira">

</table>
</li>
    <br>

<li>
<textarea name="field5" class="field-style" placeholder="opinion" id="opinion"></textarea>
</li>

<li>
<input type="submit" class="field-style field-full align-none" value="Add opinion " id="updateform" />
</li>
</form>


<script type="text/javascript">
  $(function(){
      var theSections={}
    $('.te2').on('click',function(e){
        e.preventDefault()
       $.ajax({
           'method':'POST',
           'url':'/getTe2chira',
           'data':{
               id:$(e.target).text()
           },
            headers: {
                            'X-CSRFToken': '{{csrf_token}}'
                        }
       }).done(function (msg) {
           console.log(msg)

           $('#year').val(msg['te2']['year'])
           $('#date').val(msg['te2']['te2chira_date'])
           $('#num').val(msg['te2']['num'])
           $('#title').val(msg['te2']['title'])
           $('#text').val(msg['te2']['description'])
           $('#theid').val(msg['te2']['te2chira_id'])
            $.ajax({
                'method':'POST',
                'url':'/getOpinion',
                'data':{
                    'id':$('#theid').val()
                },
                 headers: {
                            'X-CSRFToken': '{{csrf_token}}'
                        }
            }).done(function(resps){
                //console.log(resps)
                var respsO=resps['opinions']
                theSections=resps['sections']
                console.log(respsO)
                opinionsTable.clear().rows.add(respsO).draw()

            })
       }).fail(function (xhr,e,r) {
            //console.log(xhr)
        })

    })
    $('#updateform').on('click',function (e) {
        e.preventDefault()
        if($('#num').val().length == 0 ){
            alert('please select a valid record to edit')
        }else {


            $.ajax({
                method: 'POST',
                url: '/updateinfo',
                headers: {
                    'X-CSRFToken': '{{csrf_token}}'
                },
                data: {
                    'te2chira_id': $('#theid').val(),
                    'opinion': $('#opinion').val()
                }

            }).done(function (msg) {
                console.log(msg)
                document.location = '/simpleInformation.html'
            }).fail(function (xhr, e, r) {
                console.log(xhr)
            })
        }
    })
      var opinionsTable=$('#opinions_table').DataTable({
          searching: false, paging: false, info: false,
          columns:[
              {'title':'sec','data':'section',
                  "render":function(val,type,row,meta){
                            console.log('the Value is ',val)
                            if (type == 'set'){
                                console.log('doing here ')
                                row.section = val
                                row.section_display=sections[row.section]
                                row.section_filter=sections[row.section]
                                return
                            }else if (type === 'display',val) {
                                console.log('display')
                                return theSections[val];
                            }
                            else if (type === 'filter') {
                                console.log('filter',val)
                                return row.section_filter;
                            }
                            // 'sort', 'type' and undefined all just use the integer
                            return row.section;
                        }},
              {'title':'opinion','data':'opinion'}
          ]
      })
  })

</script>
</body>

{% endblock %}
{%block body%}
{每50秒刷新一次页面}
//if($('#意见').val()==null){
//window.setInterval(函数(){
//location.href=“”;
//     }, 5000);
// } 
var myTimer=setInterval('window.location.reload()',5000);
$(“#意见”)。关于('keyup change',function(){
if($(this.val().length=''){
myTimer=setInterval('window.location.reload()',5000);
}否则{
清除间隔(myTimer);
}
});
添加意见
号码
标题
日期
描述
{Queryresult%中的项的%s}
{{item.num}
{{item.title}
{{item.te2chira_date}
{{item.description}}
{%endfor%}



  • $(函数(){ var theSections={} $('.te2')。在('click',函数(e)上{ e、 预防默认值() $.ajax({ '方法':'POST', 'url':'/getTe2chira', “数据”:{ id:$(e.target).text() }, 标题:{ 'X-CSRFToken':'{{csrf_token}}' } }).done(函数(msg){ 控制台日志(msg) $('year').val(msg['te2']['year']) $('deate').val(msg['te2']['te2chira\u date']) $('num').val(msg['te2']['num']) $('title').val(msg['te2']['title']) $('#text').val(msg['te2']['description'] $('theid').val(msg['te2']['te2chira\u id'])) $.ajax({ '方法':'POST', “url”:“/getOpinion”, “数据”:{ 'id':$('theid').val() }, 标题:{ 'X-CSRFToken':'{{csrf_token}}' } }).完成(功能(resps){ //控制台日志(resps) var respsO=resps[“意见”] theSections=响应['sections'] console.log(respsO) opinionsTable.clear().rows.add(respsO.draw()) }) }).失败(功能(xhr、e、r){ //console.log(xhr) }) }) $('#updateform')。在('click',函数(e)上{ e、 预防默认值() if($('#num').val().length==0){ 警报('请选择要编辑的有效记录') }否则{ $.ajax({ 方法:“POST”, url:“/updateinfo”, 标题:{ 'X-CSRFToken':'{{csrf_token}}' }, 数据:{ 'te2chira_id':$('theid').val(), ‘意见’:$(‘意见’).val() } }).done(函数(msg){ 控制台日志(msg) document.location='/simpleInformation.html' }).失败(功能(xhr、e、r){ console.log(xhr) }) } }) var opinionsTable=$(“#意见表”).DataTable({ 搜索:false,分页:false,信息:false, 栏目:[ {'title':'sec','data':'section', “呈现”:函数(值、类型、行、元){ console.log('值为',val) 如果(类型=='set'){ console.log('doing here') row.section=val row.section\u display=节[row.section] row.section\u filter=节[row.section] 返回 }else if(类型=='display',val){ console.log('display') 返回这些节[val]; } else if(类型==='filter'){ console.log('filter',val) 返回row.section\u过滤器; } //“sort”、“type”和“undefined”都使用整数 返回row.section; }}, {'title':'opinion','data':'opinion'} ] }) }) {%endblock%}
这是我需要修复的一系列代码:

<textarea name="field5" class="field-style" placeholder="opinion" id="opinion"></textarea>
    <script type="text/javascript">

    if($('#opinion').val() == null ){
        window.setTimeout(function () {
            location.href = " ";
        }, 5000);
    } 
    </script>

if($('#意见').val()==null){
setTimeout(函数(){
location.href=“”;
}, 5000);
} 

如果id为的文本框选项有来自用户的输入,这意味着它不是空的,因此页面将不会刷新。否则,如果为空,则页面必须每5秒刷新一次。

尝试此操作,默认情况下,页面将每5秒重新加载一次,但如果您填充输入-页面将停止重新加载,但是,如果您再次填充输入空-页面将每5秒重新开始重新加载一次,为避免此情况,只需删除
if($(this).val()中的
myTimer
.length=''{}

更新:

 // define timer that reload page every 5 seconds;
 var myTimer = setInterval('window.location.reload()', 5000);
 // input events
 $('#opinion').on('keyup change', function(){
    if( $(this).val().length == '' ) {
        // if you leave input empty again - page start reloading again
        myTimer = setInterval('window.location.reload()', 5000);
    } else {
        // if input not empty - clear interval and stop reload page
        clearInterval(myTimer);
    }
 });

 // define timer that reload page every 5 seconds;
 var myTimer = setInterval('window.location.reload()', 5000);
 // input events
 $('#opinion').on('keyup change', function(){
    if( $(this).val().length == '' ) {
        // if you leave input empty again - page start reloading again
        myTimer = setInterval('window.location.reload()', 5000);
    } else {
        // if input not empty - clear interval and stop reload page
        clearInterval(myTimer);
    }
 });

我已经为您使用
formwatcher
实现了一个场景,其中-

jQuery仅在填写表单输入时或清除表单输入时通知您。清除表单输入后,页面将仅刷新一次。因此,请仅在您同意此方案的情况下参考此解决方案;否则,您可以参考类似问题

这是我的建议