This question already has an answer here:
I`m trying to pass a string value to a JavaScript parameter. this is my html code
<input type="submit" value="Edit" onclick="edit(<?php echo $key; ?> );" name="<?php echo $key; ?>" >
this is my JavaScript function
<script type="text/javascript">
function edit(id){
window.location.href="http://localhost/koko/edit-post.php?id="+id;
}
</script>
But this didn't work for me. How I solve this problem?
</div>
As the type of $key
is string
you need to surround it in quotes. Use quotes to the parameter.
onclick="edit('<?php echo $key; ?>');"
// ^ ^
Better way:
As the name
what you want in the function, you can get it by using the element.name
.
See the comments highlighted in the code below:
HTML:
<input type="submit" value="Edit" onclick="edit(this);" name="<?php echo $key; ?>">
<!-- ^^^^ Pass the element instance to the function -->
Javascript:
<script type="text/javascript">
function edit(el) {
// ^^ // Get the element instance here
window.location.href = "http://localhost/koko/edit-post.php?id=" + el.name; // Use element.name to get the `$key` value.
// ^^^^^^^
}
</script>