0

I have this rails3 app that displays a score in a popup div that I want updated every time an user selects the score... (submits the form.) on the server side the score is calculated and returned back in AJAX. This works, I can put a breakpoint in the following JavaScript:

$('#eval_form')
    .bind("ajax:beforeSend", function (evt, xhr, settings) {
        xhr.setRequestHeader('accept', '*/*;q=0.5, ' + settings.accepts.script)
    })
    .bind("ajax:success", function (evt, data, status, xhr) {
        var $response = xhr.responseText
        var encoded = jQuery.parseJSON($response)
        $('#scoretotal').replaceWith('Total Evaluation Score: ' + encoded.scores[0])    

        //also change button text
        $('#score-popup').attr('value', 'testing value')
    });
});

encoded.scores[0] and `encoded.scores[1] equal what they want. The rest of the jQuery executes, the first line with scoretotal works fine, it will indeed change that score...ONCE any subsequent times with new stores, it just doesn't update or do the replace with anymore...

Not only that but the button

<button id="score-popup"><%= @document.score %></button>

Value does not change with the above jquery or even the .prop I am at a lost as to why this is acting so wonky... here is the rest of the code from the view:

<div id="element_to_pop_up" class="bobsyouruncle">
   <a class="bClose">x</a>
   <table cellpadding="10">
   <tr>
      <th colspan="3">OVERALL EVALUATION RATING</th>
   </tr>
   <tr>
     <td colspan="3" id="scoretotal">Total Evaluation Score: <%= @document.score %></td>
  </tr>
  ...etc...
  </table>
</div>

So I think I am doing something stupid, it all executes, even sort of works (the scoretotal one changes, just once no more after that, and a score popup never changes... is it something to do with this post:

jQuery Ajax only executing once, but appears to call every time it should

??

EDIT: I did get the button working by doing this:

   $('#score-popup').html(encoded.scores[0])

(apparently because its an html button) and that works, though the rest of the code just works first time its executed, subsequent ones it just doesn't change the data, maybe I'm grabbing the wrong thing? or not changing it correctly with the replaceWith ?

Community
  • 1
  • 1
Codejoy
  • 3,722
  • 13
  • 59
  • 99

1 Answers1

1

You are replacing the whole table cell with something else, thus after the first time there is no table cell any more.

Wrap only the dynamic value in a span tag:

Total Evaluation Score: <span id="lbDocumentScore"><%= @document.score %></span>

Then assign its inner text:

var $response = xhr.responseText;
var encoded = jQuery.parseJSON($response);
$('#lbDocumentScore').text(encoded.scores[0]);
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208