Adding functions with jquery replace() markup - javascript

I have a jquery replace() putting in list items that I want to attach a function to. I don't know exactly how to do this though.
function replaceListItems(){ $('ul.options').replaceWith('<ul class="options"><li class="btn"><img src="btn.png" /></li></ul>');}
Here's the function I'd like to attach:
$("ul.options li").click(function(){myFunction()});
Seems like it gets removed if I assign it before the list items gets replaced/created.
Thanks in advance for the help!
-m

Replace:
$("ul.options li").click(function(){myFunction()});
with:
$("ul.options li").live('click',function(){myFunction()});
this way jQuery also attaches the click handler to the replaced/created elements.
Reference: http://api.jquery.com/live/
Demo: http://jsfiddle.net/CWH4D/

jsBin demo
function replaceListItems(){
$('ul.options').replaceWith('<ul class="options"><li class="btn"><img src="http://placehold.it/40x40/cf5&text=BTN" /></li></ul>');
}
$("ul.options").on('click','li',function(){
replaceListItems();
});
More on: http://api.jquery.com/on/

Related

How to get the current/this object on button click using bind event?

I have following code:
$(document).bind('click', '.btn-yes .btn-no', function() {
$(this).toggleClass("btn-warning");
alert("test"); // <-- this works...
});
.btn-yes and .btn-no are two classes which are attached to buttons. When they are clicked, I want the btn-warning class to get attached to that button, but this is not working...
Can anyone let me know what I am doing wrong?
You need to have a comma , between your selector:
'.btn-yes, .btn-no'
and you should use event delegation only if your elements are dynamically generated after page load.
If such a case then the preferred method is .on() as per latest jQuery library. You can see this in action in the snippet below.
$(document).on('click', '.btn-yes, .btn-no', function() {
$(this).toggleClass('btn-warning');
});
.btn-warning{background:red; color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class='btn-yes'>Yes</button><button class='btn-no'>No</button>
Problem:
When you don't use comma , in your selector such as in this case you are actually trying to bind a click event on the child .btn-no which has the parent .btn-yes.
Try this:
$(document).bind('click','.btn-yes .btn-no',function(e){
$(e.target).toggleClass("btn-warning");
});
'.btn-yes .btn-no' denotes to the btn-no inside btn-yes not separate elements. So, separate your elements with a comma and use click event for that.
I also recommend you to use on instead of bind method:
$(document).on('click', '.btn-yes, .btn-no', function(){
$(this).toggleClass("btn-warning");
});
If you have jquery version 1.7+ use on method
$(document).on('click', '.btn-yes,.btn-no', function() {
$(this).toggleClass("btn-warning");
});

Added Div not working click function

In my scenario , i have to use class to add div , this may easily solve with onClick function, but i require this to complete my task,
.click(function() is not working on new element , javascript /jquery may store element onload or what???
FIDDLE
<div class="add">
<div class="anyRow">Hello<hr/></div>
</div>
$('.anyRow').click(function(){
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
You have to use on() method as the deprecated live() one, to delegate click for future new elements.
$(document).on("click", ".anyRow", function() {
$('.add').append('<div class="anyRow">Hello</hr></div>');
});
If you are using in real case (as in posted jsFiddle) jQuery v1.6.4, you should use .delegate() method:
$('.add').delegate('.anyRow', 'click', function () {
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
-DEMO-
http://learn.jquery.com/events/event-delegation/
For older jquery versions you can use live function if html is changed dynamically (I saw you using an older jquery version in the fiddle)
$('.add').live( 'click', function () {
$('.add').append('<div class="anyRow">Hello</hr></div>')
});
The method bellow applies event handlers to elements even before they exist
$("#parent-element").on("click", "#new-element", function() {
// your code
});

jQuery radio button on change does not work

I have seen this question and I have seen this fiddle.
My Fiddle here. It's a simple question. Why doesn't it work?
#html
<input checked="checked" id="article_format_html" name="article[format]" type="radio" value="html">Some meaningful value
<input id="article_format_text" name="article[format]" type="radio" value="text">Another Value
#js
$("input[name='article[format]']:radio").change(alert('hola'));
Edit:
On popular demand I did this:
.change(function(){alert('hola')});
Fiddle.
Result: Doesn't work.
Edit 2: (Why I had the problem)
So, JS-Fiddle wraps your js code in the head of the iframe that is your Result section. For jQuery selectors (or any js that manipulates the DOM) to work properly, it has to be executed *after* the DOM element has been rendered. Hence, wrapping your code on ready and/or just before body closes, is the safest way to ensure that your query selectors don't return undefined.
Use a callback or anonymous function block
You are using jQuery 1.11 (better to use .on syntax)
Demo: http://jsfiddle.net/abhitalks/e5ByP/2/
$("input[name='article[format]']:radio").on("change", function() {
alert('hola');
});
You code is not working because you are not wrapping your jQuery inside document.ready function:
$(document).ready(function()
{
$("input[name='article[format]']:radio").change(function()
{
alert('hola')
});
});
FIDDLE DEMO
The code with .on() should be:
$(document).on('change',"input[name='article[format]']:radio",function(){alert('hola')});
Working fiddle:
http://jsfiddle.net/e5ByP/10/
Wrap that in a anonymous function and DOM ready:
$(function () {
$("input[name='article[format]']:radio").change(function () {
alert('hola')
});
});
Demo:http://jsfiddle.net/e5ByP/6/
That is because you have incorrect change handler syntax. also you need to wrap the code in DOM ready :
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
Demo
In your code you not wrap handler with .change()
handler is A function to execute each time the event is triggered.
Type: Function( Event eventObject )
Try This :
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
Working Example
Please use anonymous callback function in change event
$("input[name='article[format]']:radio").change(function(){
alert('hola');
});
Put the code in document ready and try like this. Please see the syntax too
$(function () {
$("input[name='article[format]']:radio").change(function () {
alert('hola')
});
});
put that in side document raedy
like this:
$(document).ready(function () {
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
});
demo
Use the below code
Always use DOM manipulation and events only after DOM gets fully loaded
$(document).ready(function(){
$("input[name='article[format]']:radio").change(function(){alert('hola')});
});
You forgot the $(document).ready() and also u forgot to write function() in change()
$(document).ready(function(){
$("input[name='article[format]']:radio").change(function(){
alert('hola')
});
});

.replace in JavaScript/jQuery

I am using .replace method to replace onclick function on anchor tag but it is not working.
<script type="text/javascript">
$(function(){
var htm= $('.jitu').html();
htm.replace("show()",'showme()');
})
</script>
<div class="jitu">me </div>
You should use :-
$('.jitu a').attr('onclick','showme()');
http://jsfiddle.net/Fxfvn/
Explanation on your code:-
What you are doing is just replacing a string not the real DOM. ALso this is not an ideal way to change an attribute. here html is just an html string and no reference...
var htm= $('.jitu').html();
htm.replace("show()",'showme()');
Since you are using jquery. You can directly bind
$('.jitu a').removeAttr('onclick').click(showme); //(if you have onclick. to avoid duplicate alert)
else
$('.jitu a').click(showme);
Use the .attr( attributeName, value ) function instead.
Another approach:
$('.jitu').find('[onclick="show()"]').attr('onclick', 'showme()');
http://jsfiddle.net/CfpBP/
However you should consider using more unobtrusive way to bind events. For example:
$('.jitu a').click(showme);
Just doing a string replacement doesn't do anything if you're not applying the final value to the element; this would work but I would not recommend it:
var $jitu = $('.jitu');
$jitu.html($jitu.html().replace('show()', 'showme()'));
The more correct way is to unhook the old onclick and replace it with a new click handler:
$('.jitu > a')
.prop('onclick', null)
.on('click', showme);
Demo
It would be even better if you didn't even have the inline onclick="show()" in the first place and just use $(element).on(event, fn) to register your click handlers.
This should do the trick:
htm.onclick = function() { showme(); };

run a function when a user clicks on any list element

This is probably a very common question, but I was unable to find an answer myself;
All my list elements call the function setQuery like this
onClick="admin_stats.setQuery(this);"
rather than [hardcode] add this to every list element, is there a way to simply have it run when a list element is clicked?
I'm not very familiar with jQuery Live or binding/unbinding, but I think they would play a role here?
Before I reinvent a rather square-looking wheel I thought I might ask =)
edit: my list elements look like
<ul>
<li id="usersPerMonth" onClick="admin_stats.setQuery(this);">Users per Month</li>
<li id="statsByUser" onClick="admin_stats.setQuery(this);">Stats by User</li>
</ul>
the this.attr("id") is then used to look up what the actually SQL text looks like, from a json-style variable:
queries : {
usersPerMonth : " ... some sql ...",
statsByUser : " ... some sql ...",
...
}
so that's why I have the divs named that way (and I'm open to design suggestions)
$(function() {
$('#myList').delegate('li', 'click', function() {
admin_stats.setQuery( this );
});
});
This assumes your <ul> element has the ID myList. It will handle clicks inside of it on any <li> elements, calling your function, and passing this as the argument.
The .delegate() code is wrapped in $(function() {}); so that it doesn't run until the DOM is ready. This is a shortcut for jQuery's .ready() function.
Yes - use jQuery like this:
$('li').live("click", function(event){
admin_stats.setQuery(event.target);
});
This is assuming you want to set it to every li element. You can find the documentation for live here: http://api.jquery.com/live/
What live does makes sure that all elements passed to it will always have the click handler in the function specified.
jQuery is probably your best bet. Are you adding new elements on the fly, or will the elements be there when the attach is ready to go? If they're "satic" in the sense that once the page is loaded that's it, you could use:
$(document).ready(function(){
$('li').bind('click',function(e){ // may need to change the selector to be more specific
admin_stats.setQuery(this);
});
});
that needs to fire onClick... so:
$('li').click(function(){
admin_stats.setQuery($(this));
});
In jQuery you select elements using CSS-style selectors (can use this if more elements will not be added; this uses .click()):
$(function() {
$('#liContainer li').click(function() {
admin_stats.setQuery(this);
});
});
We put the whole thing inside $(function() { ... }); because the page needs to be ready before binding the event handler. Alternatively, you could do it like this if more elements are added. This uses .delegate():
$(function() {
$('#liContainer').delegate('li', 'click', function() {
admin_stats.setQuery(this);
});
});

Categories

Resources