Andrew Hickman Andrew Hickman - 3 years ago 151
Javascript Question

Assign Value Of "0" To All Empty Input Elements

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" />


On a keyup event on any input, I need to assign a value of 0 to all the empty inputs, but leave the fields with existing values alone. This is my JQuery so far:

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();
});


The console shows this error when run:

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)


I'm not entirely sure I'm on the right track. Thanks for all help!

Answer Source

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");
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download