so i have some html elements generated from PHP since most contents are fetched from the database
i.e.
<?php
...
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt$row->name' data-value = '$row->total_count'>
<h3>$row->given_reference<h3>
</li>";
}
...
?>
and this is a sample structure based on my javascript
<script>
$("ul li").click(function(){
alert($(this).data('value'));
});
</script>
but if i inject an onClick= attribute while inside the echo. the script executed properly. what i need is for the script to work with the echo-ed html elements from php.
Try using variable interpolation syntax, i.e. wrap your variables around curly braces
"{$var}"
take note that you have to use double quotes("") for this
"<li class = 'lstOption' id = 'opt{$row->name}' data-value = '{$row->total_count}'>
<h3>{$row->given_reference}<h3>
</li>"
Just put your script inside document ready as below. That will fix the issue
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
You should try the code binding with the $(document).ready() method.
This is because once your all DOM elements are ready then after code bind with document ready will appear.
so do the following code.
<?php
...
while($row = $sqlQry->fetch_object()) { ?>
<li class = 'lstOption' id = 'opt<?php echo $row->name?>' data-value = '<?php echo $row->total_count?>'>
<h3><?php $row->given_reference?><h3>
</li>";
}
<?php ...
?>
<script>
$(document).ready(function(){
$("ul li").click(function(){
alert($(this).data('value'));
});
});
</script>
or write as follows
<script>
$(document).ready(function(){
$("ul li").on("click",function(){
alert($(this).data('value'));
});
});
</script>
You can try to select by id and use the on() method:
$(document).on('click', '[id^="opt"]', function () {});
Works only if you don't have anything else with id starting with "opt".
In my opinion id selectors are always stronger than any other selector.
The on() method is also preferable as it is also valid for dynamically generated elements (in case of adding content via ajax for example)
Also if you want to print the actual value and not the formula in your data-value, your quotes are wrong, here is the correct version :
while($row = $sqlQry->fetch_object()) {
echo "<li class = 'lstOption' id = 'opt".$row->name."' data-value = '".$row->total_count."'>
<h3>".$row->given_reference."<h3>
</li>";
}
try like
$(document).ready(function(){
$("ul li").on('click', function(){
console.log($(this).data('value'));
});
});
Since your html elements are generating dynamically you have to use on()
Related
I have a list of students that I am looping through and adding to my page. Each student has a unique ID, and when getStudentInfo is invoked, it does something with the id. The problem is that whichever student I click, I get back the same id, belonging to student1.
Where am I going wrong?
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo()"
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
js:
function getStudentInfo() {
var studentLink = $('.student-name-btn').attr('id');
console.log(studentLink);
}
Your code is selecting all the buttons on the page with that class and than reads the id of the first one in the list. You are not limiting it to the one that was clicked.
What most people would do is add events with jQuery and not inline.
//needs to be loaded after the element or document ready
$(".student-name-btn").on("click", function() {
console.log(this.id);
});
For yours to work, you would need to pass a reference to the button that was clicked.
onclick="getStudentInfo(this)"
and than change it to use the node passed in
function getStudentInfo(btn) {
var studentLink = $(btn).attr('id');
console.log(studentLink);
}
You can pass the reference to the element being clicked on the onclick event
foreach ($students as $student) {
echo '<tr>';
echo '<td>
'.$student[student_permalink].'
<input type="submit"
value="info"
onclick="getStudentInfo(this)" // << added this which refers to the input
class="student-name-btn"
id="'.$student[student_permalink].'"
/>
</td>';
}
And then use that to fetch the id in the js
function getStudentInfo(el) {
var studentLink = $(el).attr('id');
console.log(studentLink);
}
Don't use inline events - there's no need to clutter up the HTML with that. You have a common class on your element, so just make a jQuery handler and use an instance of this
$('.student-name-btn').click(function() {
var id = this.id;
});
Like #epascarello alluded to, you are not selecting the button that was actually clicked. What you should do is have your event handling in your JS, not in the HTML so you can see better how it works and use the this keyword within the closure to reference the clicked button.
$(document).on('click', '.student-name-btn', function(evt) {
// Prevent default if trying to do your own logic
evt.preventDefault();
// Need to use the "this" keyword to reference the clicked element
var studentId = $(this).attr('id');
console.log(studentId);
});
You can do this without inline JavaScript and since you're using jQuery drop the onClick() and the form element:
echo '<tr>';
echo '<td id="'.$student['student_permalink'].'" >
'.$student['student_permalink'].'
</td>';
You also need to quote the identifier in the array variable, 'student_permalink'.
The jQuery will be this:
$('td').click(function() {
var studentLink = this.id;
console.log(studentLink);
});
I have HTML <select> tag ID. I need to track with javascript, which option is selected
My html <select> id:
<select id="<?php echo $userArray[$key]["userID"]?>">
My javascript code:
<script type="text/javascript">
$(document).ready(function(){
$('#selectionButton').click(function(){
var selectedValue = $("#<?php echo json_encode($userArray[$key]['userID']);?>").val();
window.alert(selectedValue);
});
});
How to use PHP array as HTML id in javascript?
The point here is not about using particularly only PHP array values as your potential event target identifier, it's generally about using dynamicly generated data as part of elements' id attributes. Here you would better target class instead of id in your JS. So, when the event fires you check target's id value.
$(document).on('click', '.i-am-target-class', function () {
var targetId = $(this).attr('id');
// do your stuff knowing id
});
And what you are trying to do passing PHP code as your event target in your JS is far far not the best solution on the market
UPD:
PHP:
<select id="<?php echo $userArray[$key]['userID']; ?>" class="value-to-save"></select>
JS:
var results = {};
$('#save-button').click(function () {
$('.value-to-save').each(function () {
var userId = $(this).attr('id');
var value = $(this).val();
results[userId] = value;
});
});
So in the end you will get results object with all your data
I am self taught PHP with little js experience so it is probably something really simple, but I have made a js function to change the inner html of a table cell and added an onchange event listener on a select element to call the function. However nothing happens when I change the selected value and I have no idea why, considering it is so simple it should. Please help.
td that I want to change:
echo '<tr><td id="pastEvents">';
for($i=0;$i<=3;$i++){
echo '<table class="invisible"><tr><td><img src="/'.$pastEvents[$i]['banner'].'" alt="Event Banner"></td></tr><tr><td>'.$pastEvents[$i]['name'].'</td></tr></table>';
}
echo '</td></tr>';
Event Listener:
echo '<tr><td><table class="invisible"><tr><td>Number Shown: <select name="select" onchange="changePast()"><option value="3">3</option><option value="10">10</option><option value="20">20</option><option value="all">All</option></select></td></tr></table></td></tr>';
Script:
<script>
function changePast(){
var shown = document.getElementsByName("select");
document.getElementById("pastEvents").innerhtml = "test";
}
</script>
actually it is innerHTML
<div id="A"></div>
document.getElementById("A").innerHTML = 'text'
The correct way to use is .innerHtml() instead of .innerhtml()
<script>
function changePast(){
var shown = document.getElementsByName("select");
document.getElementById("pastEvents").innerHtml = "test";
}
</script>
My javascript function
function ConfirmDelete()
{
if (confirm("Delete Account?"))
var id= $(this).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
onclick event trigger
<?php
echo "<span onclick=\"ConfirmDelete()\" data-id={$row['project_id']} class='button-content'>
<i class='glyph-icon icon-trash-o float-left'></i>
Delete
</span>
</div>
</a>
</li>"; ?>
I cant able to get the data-id.It keep saying undefined.Any help would be appreciated.
In your example, this doesn't refer to the element where you called the function, but rather refers to the owner of the function (which, as you've defined it, looks like it's in the global scope). So you'd have to call the function with the parameter of the value you want, then use it within the function, as such:
<?php
echo "<span onclick=\"ConfirmDelete(\$(this).attr('data-id'))\" data-id={$row['project_id']} class='button-content'>
...
(The $ is escaped because you're echoing it with PHP).
And then your function would look something like this:
function ConfirmDelete(data_id)
{
if (confirm("Delete Account?"))
var id= data_id;
alert(id);
location.href='config-project-delete.php?id='+id;
}
If you aren't using the data-id attribute anywhere else and only for this purpose, you can simplify the HTML side as well by passing the value directly:
<?php
echo "<span onclick=\"ConfirmDelete('{$row['project_id']}')\" class='button-content'>
...
Note that I haven't tested any of this code, and when mixing HTML, JS, and PHP, it can be easy to screw this up (at least for me), so tweak the above as needed.
try this
<span onclick="javascript:deleteConfirm('<?php echo 'config-project-delete.php?id='.$row['project_id'] ?>');" deleteConfirm class='button-content'>
javascript
function deleteConfirm(url)
{
if(confirm('Do you want to Delete this record ?'))
{
window.location.href=url;
}
}
You have to pass the triggering object to your function.
function ConfirmDelete(triggering_object)
{
if (confirm("Delete Account?")) {
var id= $(triggering_object).attr('data-id');
alert(id);
location.href='config-project-delete.php?id='+id;
}
}
And add the 'this' to your object:
echo "<span onclick=\"ConfirmDelete(this);\" data-id={$row['project_id']} class='button-content'>";
Although Nick Coons answer is an easier way to do this (pass the variable to the function), to get the results you first asked about using the data attribute method, you have to pass event to the function to get the proper node. http://jsfiddle.net/2t4hK/
function ConfirmDelete(e) {
var target = $(e.target);
if (confirm("Delete Account?")) {
var id = target.attr('data-id');
alert(id);
//location.href='config-project-delete.php?id='+id;
}
}
<span onclick="ConfirmDelete(event)" data-id="1" class="button-content">Delete</span>
<?php
echo '<span onclick="ConfirmDelete(event)" data-id="'.$row['project_id'].'" class="button-content">';
echo '<i class="glyph-icon icon-trash-o float-left"></i>Delete</span>';
?>
Also, in your code, I suggest you wrap the value for data-id inside of quotes.
<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: "#google"});
});
</script>
I like to make the #google as a variable, so that I can change the ticker symbol as needed. I tried to echo with php. But, it's breaking the live tweet jquery.
Thanks!
<?php
$operator = "#google";
?>
<script>
$(document).ready(function() {
$(".tweets").liveTweets({operator: <?php echo json_encode($operator)?>});
});
</script>
EDIT: Thank you for your comment #icktoofay.
He is right, we don't need to wrap output in double quotes, it does that for us. I've just updated it.
HTML belongs in .html files, CSS belongs in .css files, and JS belongs in .js files. If you want to pass additional data from the server (PHP in this case) to JavaScript, you should use [data-*] attributes.
Wherever you're defining your .tweets element, you should pass the value you want used for operator as a custom data-* attribute:
HTML:
<?php
$operator = '#google';
?>
<div class="tweets" data-operator="<?php echo htmlspecialchars($operator) ?>">
...contents...
</div>
In your separate JS file, you can then use the custom server variable when initializing the widget:
JS:
$('.tweets').each(function () {
$(this).liveTweets({
operator: $(this).data('operator')
});
});
Alternatively, you can use the data-* attribute to contain the entire JSON object to initialize the widget:
HTML:
<?php
$liveTweets = array(
'operator' => '#google'
);
?>
<div class="tweets" data-live-tweets="<?php echo htmlspecialchars(json_encode($liveTweets)) ?>">
...contents...
</div>
JS:
$('.tweets').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});
Also, you could select elements based on the condition of having the appropriate data-* attribute:
JS:
$('[data-live-tweets]').each(function () {
$(this).liveTweets($(this).data('liveTweets'));
});