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

时间:2019-01-08 08:47:11

标签: javascript jquery

检查文本框是否不为空,否则刷新页面。

我尝试检查文本框的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 %}

这是我需要修复的代码块:

<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>

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

3 个答案:

答案 0 :(得分:2)

尝试此操作,默认情况下,页面将每5秒重新加载一次,但是如果您填充输入-页面将停止重新加载,但是,如果再次填充输入为空-页面将每5秒重新开始重新加载一次,以避免这种情况,只需删除myTimer内的if( $(this).val().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);
    }
 });

Fiddle

Screencast

答案 1 :(得分:0)

我已经为您实现了使用formwatcher的情况,其中-

  

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

这是上述情况的 plnkr jsfiddle 演示。记住要查看控制台以获取输出日志。

答案 2 :(得分:0)

您可以使用beforeunload事件

window.addEventListener("beforeunload", function (event) {
    // Cancel the event as stated by the standard.
    event.preventDefault();

    // check if everything is filled.
    event.returnValue = 'Did you fill the whole form?';
});