1

Check text box if it is not empty, else refresh the page.

I tried to check if the id of the textbox is == null then the page will refresh every 5 seconds and if its != null or not empty the page doesn't refresh.

based on the request of 20yco is the full code:

{% 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 %}

this is the chunck of code that i need to fix it :

<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 the textbox with id option has an input from the user that means it is not empty so the page will not refresh. Otherwise, if it is empty the page must refresh every 5 seconds.

pydev
  • 71
  • 1
  • 1
  • 11

3 Answers3

2

Try this one, by default, page will reload every 5 seconds, but if you fill input - page will stop reloading, but then, if you fill input empty again - page will start reload again every 5 seconds, to avoid this, just remove myTimer inside if( $(this).val().length == '' ) {}

Updated:

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

20yco
  • 876
  • 8
  • 28
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/186387/discussion-on-answer-by-20yco-deny-page-to-refresh-if-the-text-box-is-not-empty). – Samuel Liew Jan 09 '19 at 01:31
0

I've implemented a scenario using formwatcher for you, where -

jQuery will inform you only when you fill a form input or on clearing a form input. The page will only be refreshed once after a form input is cleared. So, please refer to this solution only if you are okay with this scenario; otherwise, you may refer to this similar question.

Here's the plnkr & jsfiddle demo for the scenario mentioned above. Remember to see console for output logs.

Tushar Walzade
  • 3,737
  • 4
  • 33
  • 56
0

You can use beforeunload event

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?';
});
Daut
  • 2,537
  • 1
  • 19
  • 32