简体   繁体   中英

Allow only one query result per table cell

I have a jquery script that accesses a db and returns a numeric result and writes that result into a table cell. This scripts runs when the page loads but also when the drop down menu is changed. I want to be able to limit only 1 result per table cell.

Right now when page loads it writes the result to the cell and when the drop down menu is changed it just adds the new result to the cell instead of replacing it.

I have search quite a bit trying to figure out how to do this and can not come up with anything. Can someone help me?

Here is the jQuery:

$(document).ready(function(){

$('.typeval').change(function(){
    var movement    =  $(this).val();
    var client_id   = $(this).parent().siblings().find('.clientval').val();
    var class_id    = <? echo $class_id; ?>;
        $count      = $(this).parents('tr').find('label.count');

$.ajax({ 
  type: "POST",
  url: "movement_count.php",
  data: {movement:movement, client_id:client_id, class_id:class_id},
  dataType: "json", 
  async: false,
  success:(function(output) {      

      $.each(output, function(index, value){
     //alert(value);
     $count.append(output[index]);
     }); // each
     })     
}) // ajax

}).change(); // .typeval

});  // document

Here is the table cell where I only want to show one result at a time.

<td><label class="count">5</label></td>

Please let me know if I have not provided enough info for the assistance needed.

Use .text() instead of .append() :

$count.text(output[index]);

As its name implies, .append() adds the content to the end of the container. Whereas, .text() sets the text displayed in the container, overwriting any existing text.

Actually, .html() , behaves more like .append() than .text() does, but I don't recommend using .html() unless you are actually setting .html() . Since you said the result is numeric, .text() is better.

Try updating your AJAX call to clear the contents before adding new results:

$.ajax({ 
    type: "POST",
    url: "movement_count.php",
    data: {movement:movement, client_id:client_id, class_id:class_id},
    dataType: "json", 
    async: false,
    success:(function(output) {      

        $.each(output, function(index, value){
            //alert(value);

            $count.html(''); // Clear current content

            $count.append(output[index]); // Append new content

        }); // each
     })     

}) // ajax

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM