I'm having some trouble getting this work, I'm using JQuery to get a list of results from mySQL, the results include a name and handler link (JQuery) that should trigger a function/event, but it is not working for some reason
Here is the code from my first page:
This script runs a query and gets the results from the ajax_load.php file using JQuery:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
</script>
<script type="text/javascript">
$(function() {
$("#lets_library").bind('submit',function() {
var value_name = $('#name').val();
if(value_name)
{
$("#find_library").html('Loading results...');
}
$.post('ajax_load.php',{value_name:value_name}, function(data){
$("#search_results_library").html(data);
});
return false;
});
});
</script>
This other script in the same first page is for the click handler, showing the ID clicked, but it is not working:
<script type="text/javascript">
$(document).ready(function(){
/// shows my ID from the result row ///
$('.next-click').click(function() {
alert("my id: " + $(this).data("id"));
});
});
</script>
This is part of the code from the ajax_load.php that returns the results with the link and ID to be clicked:
while($row = mysql_fetch_array($result_query))
{
echo '
<table width="100%" border="1">
<tr>
<td>
';
echo '<a href="#" class="next-click" data-id="'; echo $row['ID']; echo '">';
echo $row['name'];
echo '</a>
</td>
</tr>
</table>';
}
The problem is, when I click on the link it adds an # to the end of the URL page and nothing happens like the script is not even there.
Please help!
You need to use event delegation as the link is created dynamically
$(document).ready(function () {
/// shows my ID from the result row ///
$('#search_results_library').on('click', '.next-click', function () {
alert("my id: " + $(this).data("id"));
});
});
When you use $('.next-click').click(..), the click handler will get registered to only those next-click elements which exists in the page when the script is executed. The elements added later will not get the triggers.
So the solution is to bind the handler to an element which already exists in the dom(which is an ancestor of the target element), but pass a additional selector which will specify the actual target we are looking for. jQuery's .on() method provides this functionality
Try this:
$("#search_results_library").on('click', '.next-click', function(e) {
e.preventDefault();
alert("my id: " + $(this).data("id"));
});
Related
I have a button thats value is set based on a mysql query in php like so:
echo "<td><button class='jsontable' onclick='Copythat(this.value)' value='" . $row['json'] . "'> " . $row['name'] . "</button></td>";
the text of the button is the name row, which works currently.
and a function that i have basically in place to try and grab the string and send it to the load function. the load function needs to receive only text of that mysql row json
function Copythat(el.val) {
var jsontoload = $(el.val).html();
load(jsontoload);
}
If you pass this to your function, you get the context of the element where the event occurred. Once you've got that, you can pass it to jQuery and you can get the "value" attribute using the .val() shortcut method.
Note that function Copythat(el.val) { needs to be something simply like function Copythat(val) { - function parameters must be standalone variables, they cannot be written like object properties.
function Copythat(input) {
var attrValue = $(input).val();
alert(attrValue);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
You could also convert the whole thing to jQuery and ditch the inline event handler:
$(function() {
$(".jsontable").click(function(event) {
var attrValue = $(this).val();
alert(attrValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='jsontable' value='Something'>A button</button>
Or it should also be noted that for something as simple as this you don't really need jQuery at all:
function Copythat(input) {
alert(input.value);
}
<button class='jsontable' onclick='Copythat(this)' value='Something'>A button</button>
Another further simplification if you literally only need the value to go into your function:
function Copythat(input) {
alert(input);
}
<button class='jsontable' onclick='Copythat(this.value)' value='Something'>A button</button>
i have a code where i on click on #add it appends some html which have unique class name with them. The code is appended something like this
<script>
var x = 1;
$("#add").click(function() {
$("#form").last().append('<input name="item' + x + '" placeholder="name" type="text" class="jj' + x + '"/><input type="text" class="xx' + x + '" name="some' + x + '">');
x = x + 1;
});
</script>
Also i have scripts written for these classes already loaded at starting of the page
<script>
var npp = "something";
$(document).ready(function() {
//o
$(".jj").click(function() {
$(".xx").val(npp);
});
//1
$(".jj1").click(function() {
$(".xx1").val(npp);
});
//2
$(".jj2").click(function() {
$(".xx2").val(npp);
});
//3
$(".jj3").click(function() {
$(".xx3").val(npp);
});
});
</script>
in console it shows no error, but also the script isn't executing for the elements added by append function, also the script is being executed for first element already present in html inside form.
<form id="form" action="..." method="post">
<input type="text" name="item" class="jj">
<input type="text" name="some" class="xx">
</form>
<button id="add">Add new field</button>
My actual is somewhat different but the basic functioning/logic is same. Kindly advice why my script isn't working.
Here is a good answer explaining your problem: Read it here with examples
And I quote:
Because those are dynamically added elements to the existing HTML, so
you need to delegate it using on event
handler attachment with the document.
so instead of:
$(".jj").click(function(){
$(".xx").val(npp);
});
do:
$("body").on('click' , '.jj', function () {
$(".xx").val(npp);
});
And so on...
Instead of using .click function use on to be applied on any elements you add to your html code.
Example:
$("body").on('click' , '.jj2' , function(){
$(".xx2").val(npp);
});
I have created a table to display my SPARQL query result in the <td>, the result does display however I want it that when the<td> (result) is clicked on it displays a message box. Right now an extra <td> is displayed at the top and it only works for that particular one. Nothing seems to happen when clicking on the actual result <td>:
My code:
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
<body>
<script type="text/javascript">
PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX type: <http://dbpedia.org/class/yago/>
PREFIX prop: <http://dbpedia.org/property/>
SELECT ?country_name
WHERE {
?country rdf:type type:Country108544813.
?country rdfs:label ?country_name.
}
"Limit 1"
].join(" ");
alert("this query: [" + query + "]");
var queryUrl = url + "?query=" + encodeURIComponent(query) + "&format=json";
</body>
The JavaScript code I got it from an online material so still getting my head around it , the main use of it is to display the query result. So yeah answers are really appreciated and thanks for reading:)
So first off, your html is a little off... Your table is outside the tag, when it should be inside it: (note a td usually would be in a too)
<body>
<table id="results">
<tr><td class="td" onclick="myFunction()"></td></tr>
</table>
<script type="text/javascript">
....
But to your question more precisely: you have created one cell, and attached an onclick event handler to it and it only. The javascript code you grabbed actually appends new rows and cells to the table, and those don't have onclick handlers assigned.
So I'd try something like this instead:
<script type="text/javascript">
var table = $("#results");
table.on("click", "td", myFunction); // <-- magic!
var url = "http://dbpedia.org/sparql";
The "magic" line is the sweet part: it attaches the handler on the whole table, but filter the events by the "td" selector. Ideal when you are adding DOM elements dynamically...
And then you don't need to set your initial td, then one that is empty at the top of your table and clickable... Instead, just place an empty table on your page:
<body>
<table id="results"></table>
<script type="text/javascript">
....
Hope this helps!
While looking over your code you seam to only have the click event on the static
<table id="results">
<td class="td" onclick="myFunction()"></td>
</table>
When you add the dynamical the is no class or onclick event. You can fix this by either adding the onclick to the td dynamically or running a script that sets all the tds in that table to have the same click event.
function getTableCell(fieldName, rowData) {
//var td = $("<td></td>");
var td = $("<td class="td" onclick="myFunction()"></td>");
var fieldData = rowData[fieldName];
//alert("fieldName = ["+fieldName +"] rowData[fieldName][value] = ["+rowData[fieldName]["value"] + "]");
td.html(fieldData["value"]);
return td;
}
or
$("#results td").click(function(){
var x;
if (confirm("Press a button!") == true) {
x = "You pressed OK!";
} else {
x = "You pressed Cancel!";
}
}
I want to Click on a Website button that are already going on.
For example:
like url: www.google.com..
I want to Click Google Search button programmatically by using any method in PHP, Javascript, Jquery and Ajax.
if Anyone know Solution. Please tell my and provide the source code.
Note: We dn't need to create own button we want to click on a website button by using class and id.
I want to try this..look like this but not success..I want to click Learn HTML button that are show on iframe...in w3school website..
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<iframe src="http://www.w3schools.com" width="800" height="400"></iframe>
<script>
//setInterval(function () {$("#hand_1151079882").click();}, 3000);
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
//using javascript
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
</script>
<input type="button" class="cli" name="clime" value="submit" onclick="clime()">
you need set id for iframe
var iframe = document.getElementById('w3schools-home');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
innerDoc.getElementsByClassName('w3-btn')[0].click();
[0] is for button Learn HTML, there 19 element have class w3-btn
Tested and Work on w3schools Try it Yourself ยป
IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.
as Requested, here example PHP for get Element and Recreated to your own sites.
<?php
$url='http://www.w3schools.com/css/default.asp'; // or use $_GET['url']
$scheme=parse_url($url)['scheme'];
$host=parse_url($url)['host'];
$domain=$scheme.'://'.$host;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch,CURLOPT_TIMEOUT,30);
curl_setopt($ch,CURLOPT_POST, 0);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML(substr(curl_exec($ch), curl_getinfo($ch, CURLINFO_HEADER_SIZE)));
$xpath = new DOMXpath($dom);
$aElement = $xpath->query('//a');
$length = $aElement->length;
$links=array();
for ($i = 0; $i < $length; $i++) {
$element = $aElement->item($i);
if ($element->tagName=='a' && trim($element->textContent)<>'') {
foreach ($element->attributes as $attr) {
$attrName = $attr->nodeName;
$attrVal = $attr->nodeValue;
if($attrName=='href' && str_replace(';','',$attrVal)<>'javascript:void(0)'){
if(substr($attrVal, 0, 1)=='/'){
$links[trim($element->textContent)]=$domain.$attrVal;
}else if(substr($attrVal, 0, 4)=='http'){
$links[trim($element->textContent)]=$attrVal;
}
}
}
}
}
foreach ($links as $key=>$value) {
echo ''.$key.' | ';
}
You can create a javascript function to get URL from iframe and than request AJAX to PHP that have script ABOVE, you can use echo(but need foreach as example from my script) or json_encode to array $links, then reCREATED button from other url/website to your sites.
or just echo to your sites.
My script still need improvement to handle value of attribut href that use '../' or 'foldername/'
just reminder, for get access ELEMENTS on iframe that pointing to different domain is impossible.
You seem to be missing the element with the id w3-btn which gets clicked programmatically.
Also, it seems both of these are doing the same thing ...
function clime(){
setInterval(function () {document.getElementById("#w3-btn").click();}, 3000);
alert();
}
and
$(document).ready(function () {
$(".cli").on('click', function(event){
$("#w3-btn").trigger('click');
});
});
both are trying to click an element with id w3-btn, just in different ways. You only need one of them.
This might help:
<script>
jQuery(function(){
jQuery('#modal').click();
});
</script>
I got this answer from here.
How to reload div (without refresh the page) with different values?
I have this code:
$value1 = 'value1';
jQuery(document).ready(function($){
$('#content').doSomthing({
string: {
id: '<?php echo $value1; ?>'
}
});
<div id="content"></div>
<a onclick"">replace with value 2<a/> //when press this the id will be 'value2'
I dont mind to use only jquery if i need to, but what way i need to do this?
are you looking for this,
<script>
$(document).ready(function () {
$('#anchor').click(function () {
$("#content").html($(this).html());
});
});
</script>
<div id="content">
</div>
<a id="anchor">replace with value 2<a />
Try this:
$("a").click(function(e){
e.preventDefault(); //stop page refreshing
var value = this.innerHTML.match(/value \d+/);
if(value){
value = value[0];
$('#content').html(value);
}
});
You better assign a class to that anchor element and register the click event as $("a.className").