0

I have an input field which I add to html using ajax here:

function WritePrices(categories) {
    var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
    strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
    $("#price-range").html(strResult);
}

And then I want to catch a moment when this input is changed by the user. That's why in the script I also have change method

jQuery("input#minCost").change(function () {
        //...
    });

But this method doesn't "hear" any changes to my input field. It hears changes only when my input field is created in html(not during in the script). what should I change to make jQuery seen changes to my input field?

Оля
  • 91
  • 1
  • 8

2 Answers2

2

You must assign event just after the creation. Please find working snippet below:

function WritePrices(categories) {
    var strResult = "from: <input class=\"price\" type=\"text\" id=\"minCost\" value=\"" + categories.MinPrice + "\" />";
    strResult += "from: <input class=\"price\" type=\"text\" id=\"maxCost\" value=\"" + categories.MaxPrice + "\" />";
    $("#price-range").html(strResult);
    jQuery("input#minCost").change(function () {
        alert("working");
    });
}

var categories = {};
categories.MinPrice = 0.0;
categories.MaxPrice= 10;
WritePrices(categories);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price-range"></div>
Sumit Jha
  • 1,250
  • 7
  • 16
1

You need to use document change pattern

$(document).on('change','input#minCost',function(){
  ...
});
Ayaz Shah
  • 3,155
  • 7
  • 31
  • 62