Reputation: 358
I am using codeigniter 3. Below is the code of the view page, where data inside the $row->poll_question; is coming from the database. Thus, the different values coming inside this variable are echoed on a page called voting.php. And just beside this variable, there is a button called View Poll. Now, on clicking this button I want to pass the data of this php variable to javascript section. And simply alert and check in javascript. Please help. I have pasted the code I tried.
voting.php
<h3 class="val" id="val" style="color:rgb(158, 158, 158);font-family:
arial;margin-top: 2%;" ><?php echo $row->poll_question; ?></h3>
</td>
<td>
<a class="btn btn-lg btn-primary view_button" id="view_button"
style="margin-left: 18%;padding:10%;border-radius: 10px;"
onclick="fetch_val(<?php echo $row->poll_question ?>)">View Poll</a>
Javascript
function fetch_val(val)
{
alert(val);
}
Upvotes: 0
Views: 3129
Reputation: 47894
I don't recommend the redundant storage of the string.
You already have the value in your id
'ed <h3>
tag. Just use that.
Further advice move all stylings to an external stylesheet and use a javascript listener on your #view_button
.
You could stay with an inline function call:
<h3 class="val" id="val"><?php echo $row->poll_question; ?></h3>
<a class="btn btn-lg btn-primary view_button" id="view_button"
onclick="fetch_val(document.getElementById('val').innerHTML);">View Poll</a>
Or trigger fetch_val()
via a listener written in your javascript (this is the cleaner / more professional way):
document.getElementById('view_button').onclick = function() {
alert(document.getElementById('val').innerHTML);
}
About writing a pure javascript onclick handler: https://stackoverflow.com/a/17633164/2943403
Assigning a custom function to an event: https://stackoverflow.com/a/24665785/2943403
Using either of my above techniques will remove the possibility of quoting issues caused by questions like What is your mother's maiden name?
.
Upvotes: 1
Reputation: 9642
You have forgot to add quote
on '<?php echo $row->poll_question ?>'
. Check updated code below
<h3 class="val" id="val" style="color:rgb(158, 158, 158);font-family:
arial;margin-top: 2%;" ><?php echo $row->poll_question; ?></h3>
</td>
<td>
<a class="btn btn-lg btn-primary view_button" id="view_button"
style="margin-left: 18%;padding:10%;border-radius: 10px;"
onclick="fetch_val('<?php echo $row->poll_question ?>')">View Poll</a>
Upvotes: 1