Fire click event once per (different) class - javascript

I'm trying to have a click event fire on any tag with the same class only once.
I tried using '.one', although, it removes itself after the first class tag is clicked.
$(document).ready(function() {
$(".dropdown").one('click', function() {
...
});
});
The code is bought in from another .php file on the same directory with some server information so there are multiple (no end) in the number of tags with the same class.
<div class = \"dropdown\" id=" . $row["name"] . "dropdown" . ">
<div>". $row["email"] . "</div>
<div>name:" . $row["name"] ."</div>
<div>". $row["email"] ."</div></div>
";
Any recommendations?

As per your comments what you actually needs to do is apply a check of text available already or not?
$(document).ready(function() {
$(".dropdown").on('click', function() {
if(empty($('<text wrapper class or id>').text())){
// add code to bring the info
}
//rest other code.
});
});
Note : I fyou can show your code HTML then I can Update my code to give you concreete answer. The above will guide you how to proceed.

Related

Insert some text after a specific div into WordPress frontend

I am customizing the front end of Woocommerce, so I'd like to add the text "/ Per Month" after my final price before the user clicks the Add to Cart Button.
I have tried through javascript
jQuery('.woocommerce-variation-price').append(" / month")
but while it works when I run it from the console it fails when I run it through a file in the template. I can still the code when I check the page code but it does nothing.
I was thinking maybe I could achieve this through a WordPress hook.
I have inserted this in functions.php
add_filter( 'the_content', 'permonth_filter' );
function permonth_filter ( $content ) {
if ( is_single() ) {
$content .= '<div class="permonth-filter"> / Per Month </div>' . "
";
} // End IF Statement
return $content;
} // End wpcandy_filterhook_signoff()
That adds some text at the end of a blog post.
Is there a way to add some text after a specific div with a specific class? woocommerce-variation-price
Make sure that you are running your JavaScript after the page has loaded.
jQuery( document ).ready(function($) {
// Run your code
$('.woocommerce-variation-price').append(" / month");
}); // end document ready

Autocomplet() selectable Li

it's been 3 days trying to fully understand why i can't make this script function for keyboard navigation.
Search, display and replace are working fine, but when i try to browse the List and press Enter to select one option, it does not.
The Form
<form action="/busqueda.php" method="get" autocomplete="off">
<input name="dataa" class="boxbuscar" type="text" id="despliega" onKeyUp="autocomplet()">
<input src="/img/btn-buscar.png" type="image" class="lupa">
<ul id="lista"></ul>
The PHP
<?php
function connect()
{
return new PDO('mysql:host=localhost;dbname=dbname', 'dbuser', 'dbuserpw', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
$pdo = connect();
$keyword = '%' . $_POST['keyword'] . '%';
$sql = "SELECT * FROM tbl_productos WHERE nombre LIKE (:keyword) ORDER BY nombre ASC LIMIT 0, 15";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, DO ::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach($list as $rs)
{
// put in bold the written text
$reemplazador = str_replace($_POST['keyword'], '<b>' . $_POST['keyword'] . '</b>', $rs['nombre']);
// add new option
echo '<li onclick="set_item(\'' . str_replace("'", "\'", $rs['nombre']) . '\')">' . $reemplazador . '</li>';
}
?>
and the JS
function autocomplet() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $('#despliega').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {
keyword: keyword
},
success: function(data) {
$('#lista').show();
$('#lista').html(data);
}
});
} else {
$('#lista').hide();
}
}
// set_item : this function will be executed when we select an item function set_item(item) {
// change input value
$('#despliega').val(item);
// hide proposition list
$('#lista').hide();
}
Any ideas?
Update:
Short answer: This is a better option a link
Keyboard navigation of the list doesn't work out of the box like you want it to. You need to listen to the keyboard events on the list and trigger corresponding actions. Try something along the lines of:
$(document).on('keyup', function(e) {
if (e.which === 38) {
// Arrow Up is pressed
}
if (e.which === 40) {
// Arrow Down is pressed
}
if (e.which === 13) {
// Enter is pressed
}
})
Then you want to have a variable, let's call it current which stores the currently highlighted list item. You will change current when arrow up/down is pressed. You'll also have to add some style to the current list item to indicate which one is highlighted to the user. When enter is pressed, you just call set_item(current) - passing current list item to set_item function.
You also should probably add/remove this listener when the list is shown/hidden, so it doesn't fire on the document when the list is hidden.
Here are the docs for JQuery keyup event. Also check out a tutorial on JavaScript keyboard events.
That all said, you might be better off not reinventing the wheel and using a ready autocomplete widget. Here is JQuery UI Autocomplete, here is Awesomplete (search for "Ajax example" on the page to see an example implementation with the backend server).
P.S. Here is some advice about your code:
don't render javascript on the server. The best way to receive the list from the server would be to receive a JSON object listing all the items and then build list out of it. If you have to return HTML, don't put javascript callbacks in it. So just return <li data-item='1'>One</li> and then use $('#list li').on('click', ... to set the listener for all the items. This way you keep javascript and php as separate as possible
use English for naming variables, functions, etc. One day you will have show your code to someone and using variable names in spanish will make it very difficult for non-Spanish speakers to read your code
learn to use indentation. Proper indentation makes it far more easier to read your code and understand what is going on. Here is a javascript style guide. You can probably find the same thing for PHP as well. There are also online tools that can do it for you try this one. I recommend properly styling your code before posting it in a question, so it will be easier for the community to read.
enter does not work automatically you have to tie your function to enter key event

Animate on table that is generated dynamically

I want to apply a plugin on a certain table that is being generated dynamically through a php script. This is the plugin : CLICK
Now from what i read in the comments i should You first need some form of server side component, say a PHP script, which generates the html table from the data in the database. Then pass the URL of this PHP script into a jQuery ajax call. In the "success" callback, set the innerHTML of some holding div to the response of the ajax call, then select this newly created DOM table element and put it into the plugin.
Hope that makes sense!
Here's what i got so far.
HTML
<div class="testin">
<script>
testin();
</script>
</div>
JS
function testin(){
var load = $.get('functions.php',{gameNo:"1",function:"testin"});
$(".testin").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".testin").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".testin").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
php
if($_GET['function']=="testin")
{
echo '<table class="template" style="display:none"><thead><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr></thead><tbody></tbody></table>';
$gamenumber = $_GET['gameNo'];
echo'<table border="1" class="actualTable"><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr>';
$sql = mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gamenumber' ORDER BY round_name")
or die(mysql_error());
$i=1;
while($row = mysql_fetch_array($sql))
{
$tempSnumber = getcurrentshot($row['round_id'],$row['player_id']);
echo'<tr>';
echo'<td>'.$gamenumber.'</td>';
echo'<td>'.$row['round_name'].'</td>';
echo'<td>'.$row['player_id'].'</td>';
echo'<td>'.$row['target_name'].'</td>';
echo'<td>'.$tempSnumber.'</td>';
echo'<td>'.$row['round_score'].'</td>';
echo'<td>'.$i.'</td>';
echo'</tr>';
$i++;
}
echo'</table>';
}
The function fills the div just fine. I also create the template table in the php script.
Now my problem is how to invoke the plugin and what should i pass ass objects?
Invocation is like $(oldTableElement).rankingTableUpdate(newTableElement) but i'm confused due to the fact that it's being generated dynamically.
I'm new to JS so any help would be appreciated.
First off, I would put your javascript outside the div with class "testin".
Below you JS function you can add the jquery call like in the code below.
See this link for more info: http://api.jquery.com/on/
$(document).ready(function(){
$("table tr").on( "click", function() {
//your custom code goes here.
});
});
What this does is make sure then any element that matches the "table tr" will get an click handler, no matter when it gets created.

One Page Checkout scrolling to the bottom of screen on next

On my magento site, I am getting a strange behaviour in onepagecheckout that I’d like to fix. Basically, on Step 2, after entering all the data required and I click on the continue button, the page automatically scrolls down to the bottom of the screen so instead of seeing the shipping option, you see the footer and have to scroll up to choose the shipping. So my question is how can I keep the forms in onepagecheckout “focused” so that the screen stays on it when the continue/next button is clicked. I’ve tried changing the shipping.save() function on the onclick event to something like:
function test() {
shipping.save();
document.getElementById('checkoutSteps').scrollIntoView();
}
But that clearly did not work. So how can I set the page to stay on the onepagecheckout when next is clicked?
Sorry I forgot to add, the button already has an existing click event. Basically, the button looks like this:
<button type="button" class="button" title="<?php echo $this->__('Continue') ?>" onclick="shipping.save()"><span><span><?php echo $this->__('Continue') ?></span></span></button>
I'm not sure if this matters but whenever I try to add a second function onclick (onclick="shipping.save(); testFunction();"), the second function is automatically removed.
I encountered the same problem.
In your checkout/onepage.phtml, add this code:
checkout.gotoSection = function (section, reloadProgressBlock) {
Checkout.prototype.gotoSection.call(this, section, reloadProgressBlock);
$('opc-' + section).scrollTo();
};
below
var checkout = new Checkout(....);
Hope this help.
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
In addition to Williams answer:
Most custom templates do not "rewrite" base/default/template/checkout/onepage.phtml so it would be some overhead to copy this file to your template just to add this ...
You still can use this with adding a new template file:
For your templates layout local.xml add this:
<checkout_onepage_index>
<reference name="before_body_end">
<block type="core/template" name="checkout.scroll" as="checkout.scroll">
<action method="setTemplate">
<template>checkout/onepage/scroll.phtml</template>
</action>
</block>
</reference>
</checkout_onepage_index>
Create .../template/checkout/onepage/scroll.phtml with this content:
<script type="text/javascript">
//<![CDATA[
document.observe("dom:loaded", function() {
if (typeof checkout !== 'undefined') {
checkout.gotoSection = function (section, reloadProgressBlock) {
Checkout.prototype.gotoSection.call(this, section, reloadProgressBlock);
$('opc-' + section).scrollTo();
};
}
});
//]]>
</script>
Same result, just without editing base template files.
This can also help, I simply add this code in my checkout.gotoSection and it worked fine.
gotoSection: function (section) {
section = $('#opc-' + section);
section.addClass('allow');
// added this line
section.get(0).scrollIntoView();
},

jQuery - how to determine which link was clicked

I have a simple piece of PHP which generates n copies of the following code:
<p class="ShowSDB_L2" class="center" onClick="FSD_L2('<?php print dbG;?>','<?php print $sLID;?>')">Click Here to See Data</p>
<div class="divSDB_L2">
</div>
It is generated using PHP, so the number of copies is unknown up front.
On another page I have the following Javascript (using jQuery)
function FSD_L2(dbG,SlID)
{
$(".divSDB_L2").load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
When the text above (Click Here to See Data) is clicked, it should add the contents of test15.php between the the two DIV tags.
#Test15.php
<?php
$dbG = $_GET['dbG'];
$SlID = $_GET['SlID'];
print $dbG . " & " . $SlID;
?>
The problem I have is how to determine which of the links was clicked? At present, if I have three copies, and click one, all three copies are activated.
I hope I have made this clear enough. I'm sure there must be a simple way, but I'm quite new to Javascript/jQuery.
Like Brian said, you could just put the same class on all of your links and use the $(this) keyword in jQuery inside of a click function to find out which link was clicked.
Here's a basic example of changing link colors on a nav using this technique: http://jsfiddle.net/9E7WW/
HTML:
<a class="nav">Test</a>
<a class="nav">Test2</a>
<a class="nav">Test3</a>
<a class="nav">Test4</a>
Javascript:
$(document).ready(function(){
$('.nav').click(function(){
// change all to black, then change the one I clicked to red
$('.nav').css('color', 'black');
$(this).css('color', 'red');
});
});
Am not sure I fully understand what it is you are having difficulty with, but the following is how I would do it.
<p class="ShowSDB_L2" class="center" data-dbg="<?php print dbG;?>" data-slid="<?php print $sLID;?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
$(document).ready(function() {
$(document).on('click', 'p.ShowSDB_L2', function(evt) {
var $p = $(evt.currentTarget),
dbG = $p.data('dbg'),
slid = $p.data('slid'),
$div = $p.next();
FSD_L2(dbG, slid, $div);
});
});
function FSD_L2(dbG, SlID, $div)
{
$div.load("test15.php?dbG="+dbG+"&SlID="+SlID).css('display','block');
}
The click handler is not hardcoded to each p tag. Instead with each p tag we store the required data, ie dbg & slid.
The click handler is then attached once at document ready. jQuery abstracts over the various browsers and passes to its handlers the event object as its first parameter. This object can then be used to find the element on which the event occurred. Refer: http://api.jquery.com/on/
Finally, we fetch the required data from the clicked element, find the div that needs to be updated and then call your custom function.
Here is a cross-browser way to find the element (target) that triggered the event (e):
function getTarget(e){
// non-ie or ie?
e=e||window.event;
return (e.target||e.srcElement);
};
Add the complete URL to your link (or p in this case) using a data attribute:
<p class="ShowSDB_L2" class="center" data-loadurl="test15.php?dbG=<?php echo $dbG; ?>&SlID=<?php echo $SlID; ?>">Click Here to See Data</p>
<div class="divSDB_L2"></div>
Then do all the binding directly in your jQuery so you have direct access to the link that was clicked:
$(document).ready(function() {
$('.ShowSDB_L2').on('click', function(e) {
e.preventDefault();
$('.divSDB_L2').empty().load($(this).data('loadurl')).show();
});
});

Categories