-1

I work with this code:

   <form  method="get" name="MobileDetails">
 <input name="brand" id="brand" value="<?php echo $brand;?>" type="hidden">
<input name="brid" id="brid" value="<?php echo $brandid;?>" type="hidden">
 <button type="button" name="submitButton" value="get Details"    onclick="getDetails()">    
</form> 

java script

 <script type="text/javascript">
function getDetails(){
var brand = document.getElementById('brand').value;
var brandid = document.getElementById('brid').value;
document.MobileDetails.action = 'details.php?brand='+brand+'&id='+brandid;
document.MobileDetails.submit();
}
</script>

But it does not work in while loop. Whats the problem? My code is given below. When i click on the button it do not do anything. But the code work great with out while loop given on the top.

<?php
require_once('connection.php'); 
$SQL= "SELECT*FROM mobile ORDER BY price ASC  LIMIT 10";
$result= mysql_query($SQL);
while ($db_field = mysql_fetch_assoc($result)){
 $brand=$db_field['brand'];
 $id=$db_field['id'];
 $model=$db_field['model'];
 echo "<form  method='get' name='MobileDetails'>";
 echo " <input name='brand' id='brand' value='". $brand ."' type='hidden'>";
 echo" <input name='brid' id='brid' value='". $id ."' type='hidden'>";
 echo" <input name='mod' id='mod' value='". $model ."' type='hidden'>";
 echo" <button type='button' name='submitButton' value='get Details'   onclick='getDetails()'/>    
  </form>   ";
  echo "CLICK HERE";
    }

 ?>
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223

3 Answers3

1

You're using several times the same id. Ids have to be unique.

romainberger
  • 4,563
  • 2
  • 35
  • 51
1

Uou are dealing with multiple id's. The job of an ID is to be unique identifier for the element. I suggest just using

 <form action="details.php" type="get">

this will do exactly what you are trying to achieve without using the function.

0

The thing with element ID's is that they need to be unique for the page; however, as you may see, not required for HTML to be displayed. When calling your JS function getDetails(), it grabs the element by ID but when you have multiple ID's in the page, this will fail.

So what can you do? Well, in your loop, you create a new form for each 'brand'. You can pass a reference of the form to the grabdetails and then, by NAME, grab the values from that form.


Rather than using Javascript to generate a link based on given details put in a hidden field, you should just generate the action at the PHP level.

echo "<form  method='get' name='MobileDetails' action='details.php?brand=$brand&id=$brandid'>";

But since you do have hidden fields, using just action='details.php' the form will take the user to

details.php?brand={brand}&brid={id}&mod={model}

You should look into POST or making your button into a plain link rather than having a form.

UnholyRanger
  • 1,977
  • 14
  • 24