John John - 1 year ago 57
jQuery Question

Allow html tag to be visible only if user input is correct

I want to make a div tag appear only if the user input is acceptable.

This is my index.php file

<script type="text/javascript" src="../js/jquery.js"></script>
function validate_group_name(value){
<input type="text" name="group_name" id="group_name" onkeyup="validate_group_name(this.value)">
<span class="validate_group_name"></span>

<div id="display_sometimes" style="display:none;">
This text only displays sometimes.

This is my validate_group_name.php file

mysql_connect("servername ", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$group_option = $_POST['group_name'];
$len = strlen($group_option);
$groups = mysql_query("SELECT name FROM groups");
$go = 0;
while($group = mysql_fetch_array($groups)) {
if(strtolower($group['name']) == strtolower($group_option)){
$go++; //check if group already exists

if(!preg_match("/^[a-zA-Z0-9 ]*$/", $group_option)){
echo "<span style='color: red;'>" . "Invalid Group Name." . "</span>";
} else if($len < 3){
echo "<span style='color: red;'>" . "Your group name must be greater than 2 characters." . "</span>";
} else if($go != 0){
echo "<span style='color: red;'>" . "That group name already exists." . "</span>";
} else {
echo "<span style='color: green;'>" . "That group name is available." . "</span>";

Is it possible to create a javascript function that detects the text outputted from the id "validate_group_name".

I have been able to use this function to make the div tag visible, but it doesn't check whether the group name is available, and also doesn't detect change while typing.

if ($(this).val()) {

Thanks for any help.

Answer Source

You can do that in the success callback function of your AJAX (.post()) method:

function validate_group_name(value){
        if (data=="Bob Smith"){
            $('#display_sometimes').show().css({'width':'100%', 'height':'200px'});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download