views:

69

answers:

1

How can you check an empty tag -field by Javascript like in asking questions at SO?

I would not like to pass the user to send a question without specifying the tag.

+2  A: 

To start you off, in your page:

function validateForm()
{
    var tags = document.getElementById('tags').value;
    if(tags == '' || tags == null) {
        alert('Please enter one or more tags');
        return false;
    }
    return true;
}

<form method="post" onsubmit="javascript:validateForm()">
<input type="text" id="tags" name="tags"/>
<input type="submit" value="Post your question"/>
</form>

In your PHP script:

if(isset($_POST['tags']) && !empty($_POST['tags'])) {
    $tags = $_POST['tags'];
}
karim79
So the first JS code should be attached to the action of the send button in PHP. Then, I need to put your first code the JS file which I then source at index.php.
Masi
@Masi - That sounds about right. Note the 'return false' in the JS code above, that will prevent the form from submitting.
karim79
My code puts the question to my database although no tag given. I do get the alert. My code is this http://dpaste.com/83449/ **Do you see the problem?**
Masi