简体   繁体   中英

Javascript Form Validation Issue (<SELECT> Tag)

$(document).ready(function(){

$('#userForm').submit(function(){

    user_id = $('#user_id').val();

    valid = true;

    if (user_id > 0) {
        $('#user_id').removeClass('error');
        } else {
        valid = false;
        $('#user_id').addClass('error');
    }



    return valid;

    });

});

The above code should add a class to the user_id select I am using. This code snipet I am using on another page and it works fine but this one just seems to not like me. I have checkec all the variable names and its still not working.

This is validationg a SELECT (drop down menu)

Here it the relative HTML

<form method="post" action="index.php?action=save&course_id=<?php echo $_REQUEST['course_id']?>" id="userForm">
  <input name="company_id" value="<?php echo $companyData->id?>" type="hidden" size="20" />
  <select name="user_id" id="user_id" class="">
    <option value="0" selected="selected">Select a User</option>
    <?php if (count($userListData) > 0) {
            foreach ($userListData as $userList) { ?>
    <option value="<?=$userList->id?>"><?=$userList->firstname?> <?=$userList->surname?></option>
<?php } } ?>
  </select>
  <input name="submit" type="submit" value="Assign this user" />
  </form>

Try:

if (user_id.length > 0)

This checks if there's a value for user_id at all, but if the select contains values like "-123" or "0" you might want to try a different approach:

if(user_id.length > 0) {
   if(parseInt(user_id) > 0) {
       // Has a value and is bigger than zero
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM