0

So I have this serie of radio buttons generated by a php script that call a javascript function when they get clicked on:

<?php
    $databases = mysqli_query($link, "SHOW DATABASES");
    while($row = mysqli_fetch_row($databases)) {
        $db = $row[0];
        echo "<input type='radio' name='database' id='".$db."' onclick='displaydbcontent(".$db.")'>";     
    }
?>

The javascript function then has to alert the content of the string:

function displaydbcontent(dbid) {
    alert("This is a test");
    alert(dbid);
}

Now, no matter what the content of the variable $db is, after displaying the first alert printing "This is a test", the second one always prints "[object HTMLInputElement]".

I am pretty sure that it's all a matter of quotation marks, but I don't see any way to work around it.

And for those who are wondering about it even thought it hasn't to do much with my issue, the $link variable has been initializated and works correctly.

3
  • Adding same id and name for different html elements in the page is not a good sense.. Commented Apr 16, 2016 at 12:54
  • Because you're passing an object to the function, not a string. Commented Apr 16, 2016 at 13:45
  • The name is the same, the ID is always different. Commented Apr 17, 2016 at 11:16

1 Answer 1

1

Pass this.id as argument which will return id property of the clicked-element

onclick='displaydbcontent(this.id)'>"; 

As you are passing $db as argument, it represents the element. Element with id becomes the global variables.

function callMe(elem) {
  console.log(elem);
}
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
<div id='elem' onclick='callMe(elem)'>Hello!!!!!</div>

Edit: Or echo '<input type="radio" name="database" id="'.$db.'" onclick="displaydbcontent(\'$db\')">';

Sign up to request clarification or add additional context in comments.

2 Comments

Happy to help! Kindly accept and up-vote the best solution which has solved the purpose :) Happy coding!
Just to clarify, the this.id solution works, the other one doesn't since javascript quotation marks mess up with php's.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.