.replace in JavaScript/jQuery - javascript

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(); };

Related

Add click event on div tag using JavaScript

I have a div tag in my form without id property. I need to set an on-click event on this div tag.
My HTML code:
<div class="drill_cursor" >
....
</div>
I don't want to add an id property to my div tag.
How can I add an on-click event on this tag using JavaScript?
Pure JavaScript
document.getElementsByClassName('drill_cursor')[0]
.addEventListener('click', function (event) {
// do something
});
jQuery
$(".drill_cursor").click(function(){
//do something
});
Try this:
var div = document.getElementsByClassName('drill_cursor')[0];
div.addEventListener('click', function (event) {
alert('Hi!');
});
Just add the onclick-attribute:
<div class="drill_cursor" onclick='alert("youClickedMe!");'>
....
</div>
It's javascript, but it's automatically bound using an html-attribute instead of manually binding it within <script> tags - maybe it does what you want.
While it might be good enough for very small projects or test pages, you should definitly consider using addEventListener (as pointed out by other answers), if you expect the code to grow and stay maintainable.
Recommend you to use Id, as Id is associated to only one element while class name may link to more than one element causing confusion to add event to element.
try if you really want to use class:
document.getElementsByClassName('drill_cursor')[0].onclick = function(){alert('1');};
or you may assign function in html itself:
<div class="drill_cursor" onclick='alert("1");'>
</div>
the document class selector:
document.getElementsByClassName('drill_cursor')[0].addEventListener('click',function(){},false)
also the document query selector https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
document.querySelector(".drill_cursor").addEventListener('click',function(){},false)
Separate function to make adding event handlers much easier.
function addListener(event, obj, fn) {
if (obj.addEventListener) {
obj.addEventListener(event, fn, false); // modern browsers
} else {
obj.attachEvent("on"+event, fn); // older versions of IE
}
}
element = document.getElementsByClassName('drill_cursor')[0];
addListener('click', element, function () {
// Do stuff
});

adding onclick event on replace with jquery

I'm having a problem on putting onclick event on a replaceWith on jquery. My function on the 2nd onclick event is not functioning. This is my sample code.
sample.html
<div id = "first_div" onClick = "replace()">First</div>
my.js
function replace() {
$('#first_div').replaceWith("<div id = 'sec_div' onclick='flyout('fb')'>Second</div>");
}
When I click the first_div it works. It shows the 2nd_div, but when I click the 2nd div it doesn't do anything.
function flyout(data){
if (data == "fb") $('#sec_div').replaceWith("<div>Last</div>");
}
The reason your code doesn't work is that you're not passing a function to the 'onclick' of the #sec_div element. You have it defined as onclick="flyout('fb');", but the flyout function doesn't return anything. I changed the code below so that flyout returns a function and encapsulates the value of data in its closure, in case you want to use this same function with different values for the data parameter.
Also, I have a provided a solution which helps to separate your HTML from your Javascript. Using jquery you can accomplish that by using the delegate method to bind a function to any event.
HTML:
<div id="first_div">First</div>
JS:
$("body").delegate('#first_div', 'click', replace);
$("body").delegate('#sec_div', 'click', flyout("fb"));
// change replace to:
function replace() {
$(this).replaceWith("<div id='sec_div'>Second</div>");
}
// change flyout to:
function flyout(data){
return (function(){
if (data == "fb") {
$(this).replaceWith("<div>Last</div>");
}
});
}
EDIT:
According to the latest jquery documentation use of the live method is deprecated, use delegate instead.
There is no click event bound to the new div.
Either add a new listener after the replaceWith() call or else use live() to listen at the document level.
You haven't escaped it properly in the function replace. The
onclick='flyout('fb')'
part has three four single quotes. the second quote closes the first quote and the third quote starts a new string. Try escaping it as follows
element="<div id = 'sec_div' onclick='flyout(\"fb\")'>Second</div>"
$('#first_div').replaceWith(element);
Also checkout http://jsfiddle.net/5Stuh/

Why doesn't this javascript code work?

http://jsfiddle.net/FZQuM/2/
I want the div 'divi' to show what is in the input box 'hitbox'.
EDIT: it's really not difficult to place this code here, especially if it's this short
document.getElementById('hitbox')
.onchange(document.getElementById('divi')
.innerHTML = document.getElementById('hitbox').value;
The native onchange event doesn't work like its jQuery counterpart.
Use
document.getElementById('hitbox').onchange = function() { ..... }
The onchange will fire only after the textbox lose focus - to see it "live" use something like onkeyup event:
document.getElementById('hitbox').onkeyup = function() {
document.getElementById('divi').innerHTML =this.value;
};
(You can also use this while in the event handler)
Test case: http://jsfiddle.net/FZQuM/10/
Use .value instead of .text
And i made it an anonymous function:
document.getElementById('hitbox').onchange = function () {document.getElementById('divi').innerHTML = this.value};
Use "value" property instead of text. And use onchange event as property and not as onchange()
http://jsfiddle.net/FZQuM/3

how do we change onclick function via .attr() in jquery?

i got this url
<a class="remove_item' rel="4" onclick="javascript:jQuery(#blablabla)" href="javascript:;' >remove</a>
i'm using this simple find and replace
item.find('a.remove_class').attr({
title:'hello',
click:'hello();'
} );
but it seem it's not working. i still not able to replace javascript:jQuery(#blablabla) with another function.
To set onClick you should use something like this $("a").attr("onclick", js);
where js is a string containing your javascript code.
Try attaching the event handler using the below code snippet in your page body:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('.remove_item').click(hello);
});
</script>
jQuery has no built-in way to assign event handlers in that way. Use the DOM0 method to set the onclick handler instead:
item.find('a.remove_class').each(function() {
this.onclick = function() {
alert("Clicked!");
};
});
Also, don't put javascript: in you event handler attributes. It's incorrect and only works by coincidence.
Why not just do this.
<script type="text/javascript">
$(document).ready(function() {
$("a.remove_item").click(function() {
alert("You have clicked my <a>!!");
//do other stuff
});
});
</script>
The attr doesn't recognises the onclick attribute, get the html element (.get(0)) and use "raw" functions to extract the onclick attribute.
On Firefox the following works:
$("element").get(0).getAttribute("onclick")
You can remove by using
$("element").get(0).removeAttribute("onclick")
or setting a empty string
$("element").get(0).setAttribute("onclick", "")

How do you override inline onclick event?

This seems deceptively simple.
How do you override the onclick event in the following HTML using JavaScript?
<a id="sample" href="..." onclick="alert('hello world')" />...</a>
I've tried it with jQuery, but that didn't do the trick:
$('#sample').attr('onclick','alert("done")')
Assume the HTML is pre-written and cannot be changed, other than manipulating it with JavaScript.
Try this:
// Setting the DOM element's onclick to null removes
// the inline click handler
$("#sample")[0].onclick = null;
$("#sample").click(function() { alert("done") });
This can also be done without jQuery:
document.getElementById("sample").setAttribute('onclick','alert("done")');
<a id="sample" href="..." onclick="alert('hello world'); return false;" />...</a>
Or
$('#sample').attr('onclick','alert("done"); return false;')
Despite being able to set the return false; either directly in the onclick or by using jQuery, it doesn't actually require jQuery to be used at all. The benefit is if for whatever reason your jQuery script leads to a 404, your code will still work.
I found the answer here.
Try:
document.getElementById("sample").onclick = $.noop;
$.noop == function(){};
jQuery noop

Categories

Resources