Danielle Rose Mabunga
Danielle Rose Mabunga

Reputation: 1724

Javascript alert when space or no entered value

I need to write a regular expression for form validation that allows spaces within a string, but doesn't allow only white space.Example, if the user just enter spaces, it should trigger javascript alert

I tried this but this not work

<script>

if (document.getElementsByClassName('notes') == " ") {
    alert("Notes should not begin with space");
}

}

html

 <textarea name="notes" class="form-control" class="notes"></textarea>

Upvotes: 0

Views: 1687

Answers (6)

Roh&#236;t J&#237;ndal
Roh&#236;t J&#237;ndal

Reputation: 27202

Try this it is working fine :

HTML :

<textarea name="notes" class="form-control notes"></textarea>

Script :

$('textarea').on('keyup', function(){
if (document.getElementsByClassName('notes')[0].value[0] == " ") {
    alert("Notes should not begin with space");
}
});

Demo : https://jsfiddle.net/fer49eby/

Upvotes: 0

Danielle Rose Mabunga
Danielle Rose Mabunga

Reputation: 1724

Ok I got it. All answers above are correct, but I have to add "onclick" event on submit

 <input type="submit" name="submit" class="btn btn-primary btn-default" value="submit" onclick="return showAlert()">

js

 <script>
function showAlert(){
    if (document.getElementsByClassName('notes')[0].value[0] == " ") {
    alert("Notes should not begin with space");
    return false;
    }

}

Upvotes: 0

Mahesh Chavda
Mahesh Chavda

Reputation: 593

Please check your HTML. There are two class attributes:

<textarea name="notes" class="form-control" class="notes"></textarea>

Combine them first :

<textarea name="notes" class="form-control notes"></textarea>

Now the selector

document.getElementsByClassName('notes')[0]

should give you the target element.

Upvotes: 1

GBarroso
GBarroso

Reputation: 477

You are comparing the array of elements that document.getElementsByClassName returns to " ", which will obviously be false, you want to compare the value of the element.

if (document.getElementsByClassName('notes')[0].value[0] == " ") {
    alert("Notes should not begin with space");
}

In this example, the .value returns the value of the textarea, and .value[0] means the first char of the value

Upvotes: 1

Alvaro Silvino
Alvaro Silvino

Reputation: 9743

You need to get the value of inputlike:

if (document.getElementsByClassName('notes')[0].value == "") {
        alert("Notes should not begin with space");
    }

Ps. The getElementsByClassName will return a list of elements. So,when compared with " " will always return false.

Upvotes: 1

Ramanlfc
Ramanlfc

Reputation: 8354

if (document.getElementsByClassName('notes') == " ")

getElementsByClassName() returns a collection of nodes not value of node , use [] and value property along with trim() .

if(document.getElementsByClassName('notes')[0].value.trim() === "")

Upvotes: 1

Related Questions