Pass a PHP variable from a loop via an onclick - javascript

This may have been answered elsewhere but I couldn't find a question which fit my circumstances.
I have a site page which out puts in DIVs records from a database, this the same DIV looped. In this DIV I have a button which brings up a modal box. This modal DIV however is not coded within the looped DIV.
I need the modal box to be able to get the ID of the record for the data which the looped DIV is showing.
The button is:
<a href = "javascript:void(0)"onclick = "document.getElementById('light2').style.display='block';document.getElementById('fade').style.display='block'">
<div class= "obutton feature2">Reserve Book</div>
</a>
I assume I'll need to use java script somehow, but I don't know how to use it in this manner.
Ideally using some sort of form $_POST would be easiest with the form button having the set value of the $row->ID, but I can't make a form button also a can I?
Sorry for the possibly silly question, as I've said I've found similar things asked, but always find it hard to understand the full workings on other peoples scenarios as opposed to my own.
All help appreciated -Tom

I think the key to your answer is understanding how JS (and jQuery) uses this. When a function is called, the caller is almost always passed as the this variable. For example:
<button data-id="1234" onclick="runThisFunction()" value="run" />
<script>
function runThisFunction() {
//Do Stuff
var data_id = this.data('id');
};
</script>
In the above code, this contains the button that was clicked on. You can get lots of information from the this variable. In jQuery, you can even get to siblings, parents, or children in the DOM.
Here is an example solution to your question:
http://jsfiddle.net/yr6ds/1/
Here is a more elegant solution:
http://jsfiddle.net/yr6ds/2/

Related

Dynamic div id's with jQuery ajax php and javascript how to identify?

Simple question from a newbie to javascript / jQuery I cannot figure out. Maybe someone here can answer this.
Let's say I have a php script that loads thousands of rows and displays them one per line and each row has a userid associated with it.
Each row is displayed within a div andd each div has a unique id based on the userid.
So in my while loop I have
$id = "div${userid}";
then each line would be like
<div id='$id'>some info here </div>
My question is, if I were to trap for an onclick, normally I would
$('#div123').on('click', function() {
..
..
..
But since I don't know the names of the divs, how can I create at trap for an unknown?
$('#unknown').on('click', function() {
..
..
..
Thank you for taking the time to read this.
JT
You can find elements that start with a specific string. The code below will find any id that starts with div, for example <div id="div123">
$( "[id^='div']" )

Changing class of h2 inside specific div

I want to make it so that everytime you click on an 'h2' tag, the 'input' inside gets selected and the 'h2' tag changes background, but if another 'h2' tag is clicked, the current highlight and 'input' selection changes accordingly.
problem is that I have 3 different that do the same and with my code all the 3 forms are affected rather one. How do i limit my changes to only be contained to that form. Here is some code for clarification
'
<form>
...
<h2 onclick="document.getElementById(1001).checked='True'
$('h2').removeClass('selected');
$(this).addClass('selected');
">
CONTENT
<input type="radio" name="radio" id="1001" value="1001" />
</h2>
...
</form>
I think this is what you need:
$("form h2").click(function() {
var form = $(this).closest("form");
$("#"+$(this).text().trim()).prop('checked', true);
form.find('h2').removeClass('selected');
$(this).addClass('selected');
});
All the changes are confined to elements within this form.
#Barmar has answered this from a code perspective. Let's see about helping pass some knowledge on. There are some non-code concepts that will help you avoid this problem in the future.
This is a common, and very frustrating, mistake with understanding how JavaScript and HTML work together. The JavaScript doesn't full "belong" to the h2 element when you put it in the onclick attribute, it just runs when you click it. The JavaScript can touch anything in the rest of the page. That's why $('h2').removeClass() is selecting every h2 element.
In general, you should do a few things to help your confusion.
Put your JavaScript in script blocks, or better yet separate
files, not inside HTML elements.
Use jQuery to only deal with the
one h2 at a time (as Barmar suggested).
Do some reading how how jQuery selectors work. jquery.com documentation is very good, it will be time well spent.

auto update function results on a page

Ok, first off. No jquery, no ajax, just pure javascript.
I have the following code on a page called text.html.
<html><body>
<script>
function live(ID,txt2) {
var a = document.getElementById(ID);
a.innerHTML = (txt2);
}
setInterval(live, 250);
a.innerHTML =(txt2);
</script>
<div id="txt1">Live</div><p />
</body></html>
I have the following code on live2.html
<html>
<body>
<p />
<iframe width="400" height="50" src="text.html" name="frameA" id="frameA"></iframe><p />
<input type="button" value="Live" onClick="document.getElementById('frameA').contentWindow.live('txt1','L I V E')">
<input type="button" value="Rebroadcast" onClick="document.getElementById('frameA').contentWindow.live('txt1','Rebroadcast')"><br />
text
</body>
</html>
The current code works exactly as I wanted it to by updating the information in an iframe. My issue is this. If someone visits text.html directly, I want them to be able to see whatever I've changed that document to.
Example:
I click on a button and the text in the iframe now says rebroadcast.
Someone else visits text.html and they also see rebroadcast. If while they are looking at text.html, I hit the live button, the text.html page will update with the word live.
I can do PHP scripting on this as well. I have tried jquery and have issues with getting it to work correctly and I don't really have the knowledge or access to implement much of anything else.
This is an on-going project. The end result, I hope, will be an iframe that I can update while not actually being on the same page that the frame is located on. (same domain tho) The content will be anything from images, to youtube embeds and pictures. I'm trying to get a more comprehensive idea of how this language works and that's why I'm taking it one step at a time. I have no issue with visiting tutorials or looking at pre-made solutions. Thanks for your help. :)
I think I'm probably missing something. Users will always see the text "Live" because that's what's hard-coded in text.html. It doesn't matter if you change the text through JavaScript since it will only affect the browser that you're seeing. You need to save it to a persistence storage (ie. database) and dynamically display it on the page.
live2.html can use AJAX to send the changes to the server, which can then update live.html. But this is a poor way to do it, since it means that the contents of live.html are updated outside of your version control and/or content management system. It's better to use a real database and generate the page dynamically, as suke said.
First off this is what happens when someone learning programming languages doesn't fully comprehend what a language can and can't do. The original idea was to let a specific group of people know when it was a re-broadcast or when the show was live. I wanted the control of when to change that information to only be available to an admin of sorts. In the end the entire idea got scrapped and entirely impractical. The solution, essentially, doesn't exist in the context of the way I wanted to accomplish this. Years later...
The solution is to have live and rebroadcast inside div tags with CSS. Then use a JavaScript function to change the attributes of the divs to either be hidden or shown. The button or or link would need to exist on the same page as the live or rebroadcast text. This would also mean that there is no need for a separate frame. To have this element controlled from outside the page it's on could only be done by storing a value somewhere else and having that value periodically checked.
JSFiddle
The Script:
var x = document.getElementById("txt1");
var y = document.getElementById("txt2");
function htext() {
x.style.visibility = 'visible';
y.style.visibility = 'hidden';
}
function stext() {
x.style.visibility = 'hidden';
y.style.visibility = 'visible';
}
function ctext() {
var z = getComputedStyle(x).getPropertyValue("visibility");
if (z != 'hidden') {
stext();
} else if (z != 'visible') {
htext();
}
}
The CSS:
#txt1 {
visibility: hidden;
margin-left:0px;
}
#txt2 {
visibility:visible;
margin-left:0px;
}
The HTML:
<span id="txt1">Live</span>
<span id="txt2">Rebroadcast</span>
<br />
click
To be honest. I'm not entirely sure of the programming needed to store information somewhere else and have a check to see if certain conditions are true. The program above will essentially hide and show a div. I could probably go a step further and use JQuery to create and remove the actual div itself. In the end this is essentially close to the solution I ended up using and then later on discarding and giving up on the project.

Executing function on a click event in a mustache template

I have a page that is driven by a mustache template (along with javascript and jquery), and I can't figure out how to insert a function into this template. Essentially what I want is to add a link or button to the page that executes a function, "onTaskSelected(taskId)", when the user clicks on it. I've been searching for a way to accomplish this for several days now, and extensive mustache documentation/support/examples are woefully hard to find. Does anyone know how this could be accomplished?
Edit - Here is some of the code that I've tried:
data["B" + task.taskId] = {
changeTask : function(taskId) {
var self = this;
self.onTaskSelected(taskId);
},
taskId : task.taskId
};
Data gets loaded into the mustache template, which has the following within it:
<button onClick="{{#B8.changeTask}}B8.taskId{{/B8.changeTask}}">Change to task 8</button>
I've debugged the code to the point where data gets sent to the template to be converted to html, and B8 has set both changeTask and taskId correctly. However, by the time the html is displayed, the button looks like this:
<button onclick>Change to task 8</button>
Why is the onclick getting zapped, and how can I fix it? It doesn't need to be a button, but I do need a clickable element on the page with that text.
Update: I have since updated my template as follows:
<button onClick="{{#B8}}{{#changeTask}}8{{/changeTask}}{{/B8}}">Change to task 8</button>
Apparently I needed to nest my data templating in order to access the variables inside the "B8" object. However, now the problem I have is that it's trying to execute the "changeTask" function when it creates the html from the template. How can I get it to wait to execute until I click the button?
Finally got it working, but I ended up going a completely different route. Wanted to post it here in case anyone else had the same problem. I formatted the mustache to give the button a name rather than try to insert the onClick method, then I cycled through every button in that section of the DOM using jquery and add an onClick method to the buttons that had the right names.
Edit: Technically I also changed my buttons to links, which I'll show in the code below, but it should also work for buttons as well.
template:
<a name="{{{B8}}}">Change to task 8</a>
jquery (partial example):
$('a[name="' + buttonData[B8].name + '"]').click(function() {
self.onTaskSelected(buttonData[B8].taskId);
});
Hope that is helpful for others.
While your own answer is correct in essence, there is an easier option to select with jQuery:
$(link+'[name|="'+buttonData[B8].name+'"]')
Hope this helps u in the future.
Btw - I am myself still searching for a solution to the original problem...

Invoking jQuery function without an element

So, I use jQuery quite extensively and I am well aware of the "right" way to do the below, but there are times where I want to solve it in a more generic way. I'll explain.
So, I may have a link, like this: <a href='menu' class='popup'>Show menu</a>. Now, I have a jQuery function that fires on click for all a.popup that takes the href-attribute and shows the <div id='menu'></div> item (in this case). It also handles URL's if it can't find a DOM item with that ID.
No problem here. But, there are times when I don't have the same control over the coe where I can create a selectable target that way. Either because the code isn't created by me or because it is created through a chain of function that would all need a huge ovrhaul which I won't do.
So, from time to time, I would like to have this code:
Show menu
This would be in a case where I can only submit the label and the HREF for a link. No class, no nothing.
Problem here is that the function popup() has no idea about what element invoked it, and in most cases that's not a problem for me, since I only need to know where the mouse cursor was upon invokation.
But in some cases, I use someone elses jQuery functions, like qTip or something else. so I still want to fire off qTip(); when clicking a link that runs this JS function, but what do I attach it to to make it show? I can't just runt $().qTip(); because that implies $(this) and "this" is undefined inside the function.
So how do I do it? Any ideas?
Is there anyway you change the javascript method to javascript:popup('menu', this);? I've used this method successfully many times.
Instead of referring to "this" try referring to $('a:focus') to refer to the link that was clicked.
Here's a quick and, as #Crescent Fresh would add, dirty (☺) sample:
<body>
<p>Show popup()</p>
<div id="menu" style="display:none">Today's menu</div>
<script type="text/javascript">
function popup(elm) {
$('#' + elm).show();
alert( $('a:focus').text() )
}
</script>
</body>
I tried just ":focus" but IE7 returned too much content. I tested this in FF 3.6.3, IE7, Chrome 4.1.249.1064 (all on Windows) and it seems OK, but I see now (when I was just about to hit "Post Your Answer") this relies on the browser's native support for querySelectorAll - see this jQuery Forum post ":focus selector filter?" and the jQuery.expr entry in the jQuery Source Viewer (where it appears Paul's idea was not implemented).
How about
Show menu
Once you get the event object you can virtually do anything to it.

Categories