i have this javascript variable
<script>var onclick_url_bid_o_matic = $(this).parent().find('.do_bid').data('urll');</script>
and this html button
<a style="cursor:pointer;" class="bido blu" onclick="+onclick_url_bid_o_matic+" id="btn-bidoo">Activate</a>
the javascript variable points to this:
data-urll="<?php
if($whim_available >= 1)
{
if($details['reward_type']=="play_to_win")
{
echo '$.auctions.bid(' .$details['id'] . ', $(this), event);';
}
if($details['reward_type']=="whim_it_now")
{
echo '$.auctions.claim(' . $details['id'] . ', $(this), event);';
}
}
else
{
echo "$.auctions.alert('You do not have sufficient Loots');";
}
?>"
but the button's onclick doesnt work. and i believe i am not passing the javascript variable right. any help?
Create a javascript function:
function setVariable(){
var onclick_url_bid_o_matic = $(this).parent().find('.do_bid').data('urll');
}
And call that function in your onClick like so:
<a style="cursor:pointer;" class="bido blu" onclick="setVariable()" id="btn-bidoo">Activate</a>
To test if the variable holds the value needed and that the funtion correctly executed, put it to the console:
console.log("Activate link clicked: " + onclick_url_bid_o_matic);
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 been trying to catch a variable in an array when an item is clicked on and have been struggling a great deal.
I have a list of items which each have their own name in a database. When the page is loaded these items are listed on the page and can be clicked on to open a new window which displays certain content depending on the items name in the array.
Currently I have managed to get the items names into an array when they are displayed on the page. But when I click on one item the variable used to open the unique window for that item contains every variable in the array (not just the variable name of the item I clicked on).
In my PHP code I go through the database (depending on if isLive == 1) and add each name of the items 'channel_title' into an array named $chName.
$chResult = mysql_query($chSQL);
if ($chResult) {
$chNum = mysql_num_rows($chResult);
if ($chNum>0) {
//Create the arraw
$chName = array();
while($row = mysql_fetch_array($chResult)) {
//Add channel name to array
$chName[] = ($row['channel_title']);
if ($row['is_live']=="1") {
$whatIsLive = "true";
} else {
$whatIsLive = "false";
}
echo
'<li id="'.$row['channel_id'].'" class="list-group-item col-xs-12 col-sm-6 col-md-4 col-lg-3">
<div class="item">
<div class="item-head">
<div class="badges">';
if ($row['is_live']=="1") {
echo '<span class="badge-live">Live</span>';
}
echo
'</div>
</div>
<div class="item-image">
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';
$activeSSImage = 'userData/'.$row['user_id'].'/channelImages/ss_'.$row['channel_id'].'_t.jpg';
$defaultSSImage = 'images/ss_default.jpg';
if (file_exists($activeSSImage)) {
echo '<img src="'.$activeSSImage.'?rand='.rand(0, 99999999).'" alt="'.$row['channel_title'].'" width="250" height="200">';
} else {
echo '<img src="'.$defaultSSImage.'" alt="'.$row['channel_title'].'" width="250" height="200">';
}
echo '<span class="image-cover"></span>
<span class="play-icon"></span>
</a>
</div>
</div>
</div>
</li>';
}
} else {
echo '';
}
} else {
echo '';
}
In this above code is:
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'"target="window" onclick="openStreamPopup(); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">';
which sends the compiler to a JavaScript function which grabs the array and assigns it to a JavaScript variable - allowing a new window to open with window.open(). This is done with this code:
<script type="text/javascript">
var theChannel = <?php echo(json_encode($chName)); ?>; //Grab the Array $chName - call it theChannel
var windowObjectReference = null; // global variable
function openStreamPopup() {
if(windowObjectReference == null || windowObjectReference.closed)
/* if the pointer to the window object in memory does not exist
or if such pointer exists but the window was closed */
{
windowObjectReference = window.open("channels/"+theChannel,
"window", "resizable,scrollbars,status"); //Open link with theChannel (channel_title) as url
/* then create it. The new window will be created and
will be brought on top of any other window. */
}
else
{
windowObjectReference.focus();
/* else the window reference must exist and the window
is not closed; therefore, we can bring it back on top of any other
window with the focus() method. There would be no need to re-create
the window or to reload the referenced resource. */
};
console.log( "function complete" );
console.log( theChannel );
}
</script>
The problem I am having is that in this created variable contains every variable of the array. Therefore when I click on an item it adds the URL of each 'channel_title' and not just the 'channel_title' of the item I clicked on.
I have been trying for hours now to get my head around it - I am terrible with PHP and arrays.
The effect I want to achieve is like on http://onperiscope.com/ when you click on a stream and it opens the stream in a new window.
Thank you for your time, please let me know if I have not given enough information.
I'm not sure I followed exactly which value you want where, but I think something like this should get you in the right direction:
PHP:
<a href="'.SERVERPATH.'channels/'.urlencode($row['channel_title']).'" target="window" onclick="openStreamPopup(\'' . $row['channel_title'] . '\'); return false;" data-islive="'.$whatIsLive.'" title="'.$row['channel_title'].'">
JavaScript:
function openStreamPopup(theChannel) {
...
windowObjectReference = window.open("channels/"+theChannel, "window", "resizable,scrollbars,status");
...
}
So in the PHP you put the "current" value inside the openStreamPopup call as a string (\'' . $row['channel_title'] . '\'), and then that will be available inside your JavaScript function call as the first parameter.
This should get things working, but generally my preference would be to store the contextual value as a data- attribute on the element, bind the onclick event, and inside the handler read the attribute of the triggering element.
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.
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>';
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.