Kevinster
Kevinster

Reputation: 67

jQuery update input field multiple times

I'm currently using the following to update an input field without reloading the entire page:

<input type="number" name="voorraad" id="5258" class="voorraad 5258" value="129">

<script>
(function($) {
jQuery(document).ready(function(){
jQuery('.voorraad').blur(function(){

var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});
});
})(jQuery);
</script>

However, after the second replace, the input field no longer works, and I need to refresh the entire page. What I am looking for, is that the script runs on each change I make to the input field. Any ideas?

Upvotes: 0

Views: 161

Answers (2)

Kevinster
Kevinster

Reputation: 67

It seems this did the trick

<script>
(function($) {

jQuery( document ).on("blur", ".voorraad", function() {


var nieuwevoorraad = jQuery(this).val();
var productid = jQuery(this).attr('id');
jQuery( "." + productid ).replaceWith( '<span class="' + productid + '_glyphspan"><span class="glyphicon glyphicon-refresh glyphicon-refresh-animate"></span> Bijwerken...</span>' );
    $.post("<?php echo site_url();?>/updateStock.php",{
        productid : productid,
        nieuwevoorraad : nieuwevoorraad,

     },

  function(result){
  jQuery( "." + productid + "_glyphspan" ).replaceWith( '<input type="number" name="voorraad" id="'+productid+'" class="voorraad '+productid+'" value="'+nieuwevoorraad+'"/>' );
        });
});

})(jQuery);
</script>

Found here: Calling a jQuery function multiple times

Upvotes: 0

zuluk
zuluk

Reputation: 1577

You have to replace

jQuery('.voorraad').blur(function(){

with

jQuery(document).on("blur",".voorraad",function(){

because you dynamically replace this element.

Upvotes: 1

Related Questions