javascript - Use JS to get value of input field wrapped in a PHP while loop
I have an input box wrapped in a while loop, so i displays the ID or items in the database. Thus i have input boxes as 001,002,003,004,005 ... and I have a button below each input box.
What i want
1) When i click on a button, i want JS to log the value of the corresponding input box for example if I click on the button below input box 003, js should display 003.
2) I also want to use Ajax to send that value to database via (sendajax.php) and on success it should display a div with a message.
What I'm Getting
I keep getting 001 no matter the button i click on.
The Code
<?php
$booksSql = "SELECT * FROM tblitems";
$getBooks = mysqli_query($con, $booksSql);
while($row = mysqli_fetch_assoc($getBooks)){
$id = $row["itemid"];
?>
<form>
<input id="itemID" name="itemID" type="text" value="<?php echo $id; ?>">
<!--it display 001, 002, 003, 004 in the input boxes as it should-->
<input id="submit" onclick="addCart();" type="button" value="Submit">
</form>
<?php
}
?>
<script>
function addCart(){
var input = document.getElementById('itemID').value;
console.log(input);
//but this keeps displaying 001, no matter which button i click
}
</script>
My current sendajax.php
include("dbconn.php");
$id = $_POST["id"];
if (isset($_POST['id'])) {
$send = "query to insert to db";
$query = mysqli_query($con, $send);
}
Answer
Solution:
An HTML element's
id
is supposed to be unique; you have given multiple elements the sameid
, which is why your function simply grabs the first element.Instead of a
<form>
and multiple inputs, use just this:Now you can grab the id in
addCart()
:Edit: It should be noted that I avoid inline code wherever possible and would use jQuery instead, something like
Answer
Solution:
The comments about duplicate IDs are absolutely correct and probably the only issue with your existing code, but I'd recommend also not parsing the DOM for a value that you can just pass to the function when you call it, like this...
PHP
Javscript
People are also looking for solutions to the problem: cannot use isset() on the result of an expression (you can use "null !== expression" instead)
Source
Share
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Answer
Solution:
The comments about duplicate IDs are absolutely correct and probably the only issue with your existing code, but I'd recommend also not parsing the DOM for a value that you can just pass to the function when you call it, like this...
PHP
Javscript