Why doesn't this javascript code work? - javascript

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

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

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

Adding onClick event dynamically using jQuery

Due to a plugin being used, I can't add the "onClick" attribute to the HTML form inputs like usual.
A plugin is handling the forms part in my site and it doesn't give an option to do this automatically.
Basically I have this input:
<input type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
I want to add an onClick to it with jQuery onload for it to be like this:
<input onClick="myfunction()" type="text" id="bfCaptchaEntry" name="bfCaptchaEntry" style="">
How do I go about doing this?
I know this might not be standard practice but seems like the easiest option to do in my situation.
I'm a newbie to jQuery so any help is very much appreciated.
You can use the click event and call your function or move your logic into the handler:
$("#bfCaptchaEntry").click(function(){ myFunction(); });
You can use the click event and set your function as the handler:
$("#bfCaptchaEntry").click(myFunction);
.click()
Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
http://api.jquery.com/click/
You can use the on event bound to "click" and call your function or move your logic into the handler:
$("#bfCaptchaEntry").on("click", function(){ myFunction(); });
You can use the on event bound to "click" and set your function as the handler:
$("#bfCaptchaEntry").on("click", myFunction);
.on()
Attach an event handler function for one or more events to the
selected elements.
http://api.jquery.com/on/
try this approach if you know your object client name ( it is not important that it is Button or TextBox )
$('#ButtonName').removeAttr('onclick');
$('#ButtonName').attr('onClick', 'FunctionName(this);');
try this ones if you want add onClick event to a server object with JQuery
$('#' + '<%= ButtonName.ClientID %>').removeAttr('onclick');
$('#' + '<%= ButtonName.ClientID %>').attr('onClick', 'FunctionName(this);');
Try below approach,
$('#bfCaptchaEntry').on('click', myfunction);
or in case jQuery is not an absolute necessaity then try below,
document.getElementById('bfCaptchaEntry').onclick = myfunction;
However the above method has few drawbacks as it set onclick as a property rather than being registered as handler...
Read more on this post https://stackoverflow.com/a/6348597/297641
$("#bfCaptchaEntry").click(function(){
myFunction();
});
Or you can use an arrow function to define it:
$(document).ready(() => {
$('#bfCaptchaEntry').click(()=>{
});
});
For better browser support:
$(document).ready(function() {
$('#bfCaptchaEntry').click(function (){
});
});
let a = $("<a>bfCaptchaEntry</a>");
a.attr("onClick", "function(" + someParameter+ ")");
as #Selvakumar Arumugam suggested, but the function call on registering also
$('#bfCaptchaEntry').on('click', myfunction);,
rather than use
$('#bfCaptchaEntry').on('click', () => { myfunction});

onkeypress textbox issue

I have this:
<input type="text" ID="txtMy" name="txtMy" onkeypress="initialize();"/>
And in my .js file I have:
initialize()
{
var x = $("#txtMy").val();
}
But, if I have '2' in my textbox, and then I enter 4, the value of x is still 2. How to resolve this?
Use keyup
Here is how you do that in the unobtrusive way.
HTML
<input type="text" id="txtMy" />
Script
$(function(){
$("#txtMy").keyup(function (event) {
alert($(this).val())
});
});
Working Sample : http://jsfiddle.net/VmELF/4/
If you want to bind the functionality to a text box which is being injected to the DOM after the dom load( possible by an Ajax call etc...), you may use jQuery on
$(function(){
$("body").on("keyup","#txtSearchKey",function (event) {
alert($(this).val())
});
});
Your spelling of initialize in the onkeypress does not match the declaration (inititalize).
keydown and keypress events both execute BEFORE the entered key has actually appeared in the text box. If you want to get the new value of the input after the key has appeared, use the keyup event instead.
<input type="text" ID="txtMy" name="txtMy" onkeyup="initialize();"/>
initialize()
{
var x = $("#txtMy").val();
}
You should consider binding your event handlers in javascript using .on(), since you're using the library anyways. Keeping your logic (javascript) seperated from your view (html) is a good habit to get in to.
instead of markup event handler you can use jquery:
var x;
$("#txtMy").on("keyup", function(){
x = $(this).val();
alert(x);
})
A few things:
Use the keyup event. keypress is firing before the character is recorded.
Your initialize() function is misspelled in your HTML snippet.
See the working jsfiddle at http://jsfiddle.net/8XTLW/1/

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/

Categories

Resources