如何使用javascript获取输入值

时间:2016-10-01 13:52:57

标签: javascript php jquery

我的脚本从db中获取并插入一些数据并显示给用户然后我决定稍微更改我的代码并添加一些功能。例如,如果任何textbox为空,那么我添加了一个控制的java脚本文件这个sitituation.Bu我无法从索引.php文件中获取文本框值的值

这是index.php文件

<?php    
$records = array();
$db = new mysqli("localhost", "root", "", "app");   
if (!empty($_POST)) {
    $first = $_POST["first"];
    $last = $_POST["last"];
    $bio = $_POST["bio"];    
    $insert = $db->prepare("Insert into people (first,last,bio,created) values(?,?,?,NOW())");
    $insert->bind_param("sss", $first, $last, $bio);
    if ($insert->execute()) {
        header("location: index.php");
    }    
}
if ($result = $db->query("select * from people")) {    
    if ($result->num_rows) {    
        while ($row = $result->fetch_object()) {
            $records[] = $row;
        }
        $result->free();    
    }    
} else {
    $db->error;
}    
?>    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script type="text/javascript" src="sites.js"></script>
    <title>Title</title>
</head>
<body>    
<?php
if (!count($records)) {
    echo "no";
} else {
    ?>
    <table>
        <tr>
            <td>First</td>
            <td>Last</td>
            <td>Bio</td>
            <td>Created</td>
        </tr>
        <?php
        foreach ($records as $r) {  
            ?>
            <tr>
                <td><?php echo $r->first; ?></td>
                <td><?php echo $r->last; ?></td>
                <td><?php echo $r->bio; ?></td>
                <td><?php echo $r->created; ?></td>
            </tr>    
            <?php
        }
        ?>
    </table>
    <?php
}
?>

这是html标记

<form action="" method="post">
    First <input type="text" id="first"><br>
    last <input type="text" id="last"><br>
    Bio <input type="text" id="bio"><br>
   <button id="submit" value="click me!!"></button>

</form>
</body>
</html>

我试图从索引文件中获取输入值,如下所示但它不会以这种方式工作它返回对象

$(document).ready(function () {
    $('#submit').click(function () {
        var name=$('#last');
      alert(name);
    });
});

提前谢谢

3 个答案:

答案 0 :(得分:1)

使用

选择元素时
$_POST

你得到的是整个元素。有了它,您可以使用$('#last') 方法检索元素值:

val()

答案 1 :(得分:0)

这不会返回name字段的值:

exec

您可以使用:

var name=$('#last');

另请注意,您缺少输入字段中的name属性。如果没有名称属性,您无法获得var name=$('#last').val(); 中的值。

答案 2 :(得分:0)

您指的是对象,因此您将获得该对象。

public function login() {

    // Set cookie expire time
    $cookie_expire = 3600 * 24 * Yii::$app->params['settings']['cookie_expire'];

    return Yii::$app->user->login($this->getUser(), ($this->remember_me ? $cookie_expire : 0));

}

如果你需要价值,你必须要求它:

var name=$('#last');