I have three input elements in the DOM:
<input type="input" id="triangle-base" />
<input type="input" id="triangle-height" />
<input type="input" id="triangle-area" />
const baseInput = $('#triangle-base');
const heightInput = $('#triangle-height');
const areaInput = $('#triangle-area');
function ifEmpty () {
$("input").each(function(i) {
if (i.val("")){
$(this).val("0");
}
});
}
baseInput.keyup(function() {
ifEmpty();
});
heightInput.keyup(function() {
ifEmpty();
});
areaInput.keyup(function() {
ifEmpty();
});
main.js:178 Uncaught TypeError: i.val is not a function
at HTMLInputElement.<anonymous> (main.js:178)
at Function.each (jquery-3.2.1.min.js:2)
at r.fn.init.each (jquery-3.2.1.min.js:2)
at ifEmpty (main.js:177)
at HTMLInputElement.<anonymous> (main.js:186)
at HTMLInputElement.dispatch (jquery-3.2.1.min.js:3)
at HTMLInputElement.q.handle (jquery-3.2.1.min.js:3)
jQuery $.each
callback functions are (index, item)
. The item is a DOM node, not jQuery object. Also, your code logic is incorrect. $(item).val("")
sets the input value to (null). See the below fix:
$("input").each(function(i, item) {
if ( $(item).val() == '' ){ // or $(this).val() == ''
$(this).val("0");
}
});