ali ak ali ak - 2 months ago 7
jQuery Question

How to get inputs value using javascript

My script fetchs and insert some data from db and displays to the user then I decied to slightly change my code and add some functionality.For example what if any of textbox is empty so that I have added a java script file that controls this sitituation.Bu I cant get the value of textboxes values from index .php file

this is index.php file

<?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
}
?>


and this is the html markup

<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>


I am trying to get inputs values from index file like this below But it doesnt work this way It returns object

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


thank in advance

Answer

When selecting an element with

$('#last')

you are getting the entire element in return. With that, you can use the val() method to retrieve the elements value:

var name = $('#last').val();
Comments