jQuery radio button on change does not work - javascript

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

Related

jQuery trigger on page load

How can I make jQuery run when my webpage has finished loading?
This is not what I want. All that this does is wait for the page to finish loading before any Javascript CAN be run.
$(document).ready(function(){
//Code here
});
What I want is for this to run when the page loads. I don't want it to wait for 'click' or 'change'. Can I add a 'load' or something to this?
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
A workaround I have been using is to use jQuery to "change" the selected option on a select box, thereby triggering the code I actually want to run.
I have seen a bunch of questions like this, but every time the answer just says to use $(document).ready(function(){//Code}); which is not what I'm looking for.
Any ideas?
EDIT: Here is a better example of what I'm looking for.
This code below will run when the element with the id of 'input' is clicked. That is the only time it will run. I would like for it to run as soon as it is ready - as soon as $(document).ready(function(){}); can run it.
$(document).ready(function(){
$(document).on("change", "#input", function(e) {
$("#output").val($(this).val());
});
});
I think that this would work, but I was hoping for a nicer solution and one that doesn't require me to rewrite everything as functions.
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
I think that this will run runWhenReady() when #input is clicked, and when the page finishes loading. My question is, is there a simpler way to do this?
I think the only way to do what I want is to name the function and call it two different ways.
$(document).ready(function(){
function xyzzy(){
$("#output").val($(#input).val());
}
//Call the function when #input is clicked
$(document).on("change", "#input", function(e) {
xyzzy();
});
//Call the function when the page loads
xyzzy();
});
This will call the function when the page has finished loading, as well whenever #input is clicked.
I think you're looking for $(window).load()
$(window).load(function(e){
// code here
});
Answer to your question in the comments:
$(document).on('click', '#input', function(e){
$('#output').val($(this).val());
});
Can I add a 'load' or something to this?
yes you can which will like $(window).on( "load", handler )
Also there is not much difference between the above code and
$( window).load(function() {
// Handler for .load() called.
});
The first method is just short cut of the second one
$(document).ready happens when all the elements are present in the DOM, but not necessarily all content.
$(document).ready(function() {
alert("document is ready");
});
window.onload vs document.onload
window.onload or $(window).load()
happens after all the content resources (images, etc) have been loaded.
$(window).load(function() {
alert("window is loaded");
});
From your Example:
$(document).ready(function(){
function runWhenReady(){
$("#output").val($(#input).val());
}
$(document).on("change", "#input", function(e) {
runWhenReady();
});
runWhenReady();
});
You could write:
$("#input").on("change", function() {...});
which defines a handler for your input. Everytime you change the value in the input it will call the function passed as argument. That make the whole $(document)... unneccessary.
If you want to run the function just once, as soon as possible wrap it in a IIFE like:
(function(){...});
Here is a pretty good blog post about IIFE:
http://benalman.com/news/2010/11/immediately-invoked-function-expression/

add simple onclick js to rails

I have a simple div in one of my views that I want to click to hide another element on the page. I put this in my application.js But it doesn't do anything. Did I put it in the wrong place?
function toggleNewPostForm {
$('.new-post-btn').hide();
}
Use document ready to make sure document is loaded before selecting an element from HTML and call your function inside
function toggleNewPostForm(){
$('.new-post-btn').hide();
};
$( document ).ready(function() {
toggleNewPostForm();
});
Try something like this
<div class="xyz">Click here!</div>
in javascript
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
Also check if event listener is added after document ready method? i.e
$(function(){
$(".xyz").click(function(){
$('.new-post-btn').hide();
});
});
If this is the only js you have, there will be no click-behaviour. You have to tell the element, that is has to react to a click-event.
Try this in your application.js-file:
function toggleNewPostForm() {
$('.new-post-btn').hide();
}
$(document).on('ready page:load', function(){
$('.new-post-btn').on('click', function(){
toggleNewPostForm();
});
});
P.S.: As RGraham points out, you have to write the parameter-paranthesis if you define a function.
P.P.S.: In ruby on rails, you should check against 'ready' and 'page:load' as document-ready-handlers, because Ruby on Rails uses the "Turbolinks"-library by default.

Onclick function based on element id

I'm working on a site with a visualization of inheritance relation.
I try to link each nodebox with specific URLs. The html of Element looks like this:
<g class="node" id="RootNode" transform="translate(0,453.125)">
I used
$('#RootNode').click(function(){//do something}
and also
document.getElementById("RootNode").onclick(){//do something}
Neither of them can find the element, nor setup the onclick function.
Have I misunderstood anything? Any information will be helpful. Thanks.
Make sure your code is in DOM Ready as pointed by rocket-hazmat
.click()
$('#RootNode').click(function(){
//do something
});
document.getElementById("RootNode").onclick = function(){//do something}
.on()
Use event Delegation/
$(document).on("click", "#RootNode", function(){
//do something
});
Try
Wrap Code in Dom Ready
$(document).ready(function(){
$('#RootNode').click(function(){
//do something
});
});
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
$(document).ready(function() {
$("#click").click(function(){
console.log("button clicked");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="click">Click Me</button>
You can try this one:
document.getElementById("RootNode").onclick = function() {
/* do something */
};

Adding functions with jquery replace() markup

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/

JavaScript / jQuery problem on Internet Explorer 7

I have a simple HTML page that looks like this:
...<div id="main">
Click here!
</div>...
I have a piece of jQuery JavaScript in the header that looks like this:
<script type="text/javascript">
$(document).ready(function() {
DoHello();
});
function DoHello()
{
$("div#main a").text("Click here!");
$("div#main a").attr("onmouseup", "javascript:alert('Hello!');");
}
</script>
When I click the HTML link in FireFox then I get an alert that says 'Hello!'. Why does this not work in IE7/8?
When I look at the (dynamically) build DOM in IE then I can see the onmouseup is present but it is never called. I have tried replacing onmouseup with onclick - same problem...
You shouldn't be using the JavaScript pseudo protocol for anything.
This should work:
function DoHello()
{
$("div#main a")
.text("Click here!")
.mouseup(function(){
alert('Hello!');
});
}
Don't use expando events, use jQuery!
$("div#main a").mouseup(function(){ alert('Hello!') });
instead of adding the onmouseup event like that why dont you just use the jQuery method like so:
$("div#main a").mouseup(function() {
alert("hello");
});
should work :) for more info check out - http://docs.jquery.com/Events/mouseup
You should use the bind function like this:
function DoHello(){
$("div#main a").bind("mouseup", function(e){
alert("Hello!");
});
}

Categories

Resources