JS to change inner html table cell - javascript

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>

Related

Unable to get element id dynamically in javascript

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);
});

echo-ed HTML Element from PHP is not read in JAVASCRIPT

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()

How to compose multiple $(document).ready() function

I have a function which creates dynamic <select>. I have to make it a multiple select options, so I have to initialise it as well.
The function is called multiple times; here's the function:
function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for)
{
echo '<script>
$(document).ready(function()
{
$("#zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'").multiselect({
includeSelectAllOption: true,
enableFiltering: true,
enableCaseInsensitiveFiltering: true,
maxHeight: 150
});
});
</script>'.'<div class="time_zone_list"><select name="rules['.$r.']['.$c.']['.$for.'_timezone]" class="input_field zonefield" id="zoneFilter_criteria_'.$for.'_'.$r.'_'.$c.'" style="width:30%; margin-right:5px; float:left;">';
foreach ($this->timezoneArrayNotDefault as $k => $val) {
$selected = '';
$val_array = explode(")",$val);
if (isset($val_array[1]) && trim($val_array[1]) == trim($filterKey)) {
echo $selected = SELECTED;
}
echo '<option value="' . $val . '"' . $selected . '>' . $val . '</option>';
}
echo '</select></div>';
}
Now, as you can see, the html is made as php string (my client stated that by this way, the html loads faster so he used this technique, and U can't convince him to alter to another way.
Now let's come to the point: if the function is called multiple times, then it's also causing multiple $(document).ready(function(){});
Is there any way, that I can have only $(document).ready(){}); and initialise the multiple drop-downs in some other way??
Set a flag variable.
$firstCall = TRUE;
renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall);
And check it:
function renderTimezoneFilterStringCriteria($filterKey,$onChange,$r,$c,$for, &$firstCall)
{
if($firstCall) {
echo '<script> $(doucment).ready(function() { ... ';
//your document.ready here
$firstCall = FALSE;
}
// your other stuff here
}
UPD: The better solution probably is to make single function wich echoes your document.ready, and call it once.
Here is an example of just rebinding your code when you add the new html.
http://jsfiddle.net/64e41LL9/
Html
<div id="container">
<button class="button-item">I am a button</button>
</div>
<br/>
<button id="add-html" >add button</button>
<br/>
<button id="rebind" >rebind</button>
Jquery
$(document).ready(function(){
//function to rebind
function rebind() {
$('.button-item').click(function(){
alert("Im binded");
})
}
//initial bind on page load
rebind()
//adding new html thats unbinded
$("#add-html").click(function(){
$("#container").append('<button class="button-item">I am a button</button>')
})
//calls function to bind new html
$("#rebind").click(function(){
rebind()
})
})
So essential what is happening here is when the page loads you will initially bind the alert code to the button but when you append new html to the page you will see the new button won't fire the on click event even though it has the same class. This is because its not binded. Once you click that rebind button it will rebind all the buttons with that class(button-item). You can use the same concept but it will call the rebind function everytime you add your dynamic html.

javascript function with 2 arguments is not working

DEscription :
I have a php script that displays the div on an html page
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id)"></div>';
Now when I click on this div the star_it function gets called and it works perfect...
The problem
I want to pass another argument in the star it function .. like this
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,'.$each_status['regno'].')"></div>';
or a simple alphabet if any like star_it(this.id,s)
but when I do so the function stops working as when I click the div the function does not gets called ....
I dont know why I am stuck and now my star rating system does not work... I have absolutely no idea what is wrong
Anyone ??
You should modify your string quote's like this :
<?php
$status = "second test";
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$status."'".');" >Hello</div>';
?>
<script>
function star_it(foo1,foo2){
console.log(foo1);
console.log(foo2);
}
</script>
This example works for me.
So with your code :
<?php
echo '<div class="star_box" id="'.$id.'" onmousedown="star_it(this.id,'."'".$each_status['regno']."'".');" >Hello</div>';
?>
Here you go
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\''.$each_status['regno'].'\')"></div>';
you forget to add \' before and after your string , the JS engine on the browser will treat your string as an undefined variable and the function will not work because of that .
//my English is not so good.
Try
echo '<div class = "star_box" id = "'.$each_status['post_id'].'" onmousedown = "star_it(this.id,\"'.$each_status['regno'].'\")"></div>';

how can I add a copy of a div with jquery?

I have a div containg a few dynamically generated dropdowns.
I want to clone this and add it underneath the original. The code for the original is:
<div id="subjectselectiondiv" style="width:inherit;">
<h4>Select the subjects that you are able to tutor</h4>
<div id='choices'>
<script type="text/javascript">
var doc = document.getElementById("choices");
var subj_div = document.createElement('div');
subj_div.setAttribute('class', 'selectSearchBar');
subj_div.innerHTML = '<select id="level'+counter+'" name="level'+counter+'" class="selectSearchBar"><?php echo "<option>Level</option>"; while($row = mysqli_fetch_array($result_level, MYSQLI_ASSOC)){echo "<option value=".$row['id'].">".$row['level']."</option>";}?></select><div id="subject'+counter+'" style="display:inline;">sBar2</div><div id="topic'+counter+'" style="display:inline;">sbar3</div>';
doc.appendChild(subj_div);
</script>
Add another subject
</div>
I thought that the function Repeat() would work with:
function Repeat(){
counter++;
$('#choices').clone().appendTo('#subjectselectdiv');
event.preventDefault();
}
but this isnt working - am I missing something?
Thanks
Name mismatches:
<div id="subjectselectiondiv" style="width:inherit;">
^^^^^^
$('#choices').clone().appendTo('#subjectselectdiv');
^^^
What you're attempting to append to doesn't exist. Most likely if you'd bothered checking your javascript console, you'd have seen the warnings/errors about the non-existing element.

Categories

Resources