Joe
Joe

Reputation: 4917

If input field has no value, add a new value using JavaScript

Using JavaScript I'm trying to put together some validation for my form. What I'm trying to achieve is that if one input field is left blank, then a value is automatically added to that field upon hitting submit.

I will start off by saying I attempted by using the answer from this question: If input value is blank, assign a value of “empty” with Javascript.

However, this did not work.

I then tried to use the following in my external .JS file:

validateForm();
function validateForm() {
    "use strict";
//POSITION VALIDATION
    var numberOf = document.forms.themainform.numberOf.value;
    if (numberOf === "") {
        numberOf.value = "-5";
    }
}

and I also attempted to use a variation of the other questions answer:

var numberOf = document.forms.themainform.getElementById('numberOf');

if(numberOf.value.length === 0) {
    numberOf.value = "-5";
}

But as before, no luck. Below is the code to my HTML form:

<script>validateForm();</script>
<form action="" method="post" name="themainform" onsubmit="return validateForm()">
<table>
<tr><td>Number Of</td>
<td><input type="text" name="numberOf" id="numberOf" size="5" maxlength="5"/></td>
</tr>
</table>
<input type="submit" name="themainform" value="submit"/>
<hr/>
</form>

Any help would be greatly appreciated!

Upvotes: 0

Views: 249

Answers (2)

Anthony C
Anthony C

Reputation: 2157

You should call the validateForm() after the form is rendered so the html file should look like this

<form action="" method="post" name="themainform" onsubmit="return validateForm()">
    <table>
        <tr><td>Number Of</td>
        <tr><td><input type="text" name="numberOf" id="numberOf" size="5" maxlength="5"/></td>
        </tr>
    </table>
    <input type="submit" name="themainform" value="submit"/>
    <table/>
</form>
<script>validateForm();</script>

and in you js file, you can't set numberOf.value = "-5"; since numberOf is just a string, it should be the dom elment.

function validateForm() {
    "use strict";
//POSITION VALIDATION
    var numberOf = document.forms.themainform.numberOf;
    if (numberOf.value === "") {
        numberOf.value = "-5";
    }
}

Upvotes: 1

Joe
Joe

Reputation: 4917

Thanks for your assistance everyone. But I managed to figure it out :) However, I also tested Anthony's method and it also worked, so accepted his answer.

I used:

if(document.forms.themainform.numberOf.value === "") {
    document.forms.themainform.numberOf.value = "-5";
}

This meant that if someone left this input field empty, on submit it would put -5 as the input.

Upvotes: 0

Related Questions