ruby on rails - JQuery: Trigger Event based on Form Input Length -
i trying autosave form whenever form length changes. below code. initial form length recorded correctly , variable $("form input").length change when play form block inside if statement not triggered.
anyone knows why is?
var formlength = $("form input").length; console.log("the current formlength is" + formlength); $(document).ready(function() { if ($("form input").length > formlength) { settimeout(autosaveform, 10000); formlength = $("form input").length; console.log("the updated formlength is" + formlength); } });
update: florian has solved problem. , have update of 1 new problem. form have nested form using cocoon gem in rails. datepicker.js loaded whenever 1 child inside nest added.
however datepicker loaded after set time interval.
below new code. thoughts?
var formlength = $("form input").length; console.log("the current formlength : " + formlength);
$(document).ready(function() { $.each($('[data-behaviour~=datepicker]'), function(index, element) { if (element.value) { var dsplit = element.value.split("-"); var d =new date(dsplit[0],dsplit[1]-1,dsplit[2]); element.value = d; } new pikaday({ field: element }); }); setinterval(function() { if ($("form input").length > formlength) { console.log("the updated formlength : " + formlength); formlength = $("form input").length; var uuid = $("#uuid").html(); $.ajax({ type: "post", url: "trailers/" + uuid + "/save-draft", data: $("form").serialize(), success: function() { } }); } else { console.log("nop. (" + $("form input").length + ")"); } }, 30000); });
not sure you're drying achieve here working example :
var formlength = $("form input").val().length; console.log("the current formlength : " + formlength); $(document).ready(function() { setinterval(function(){ if ($("form input").val().length > formlength) { formlength = $("form input").length; console.log("the updated formlength is" + formlength); //settimeout(autosaveform, 10000); //auto save! } else { console.log("nop. (" + $("form input").val().length + ")"); } }, 3000); });
everything inside document.ready fonction executed once page loaded, if want have reccurent check need setinterval example (executed periodically).
you add on text input, example :
$("form input").bind("change paste keyup", function() { //but code inside });
Comments
Post a Comment