Radio button click event is not getting fired - javascript

This may seem to be duplicate question as people already asked such question and I read the answers too. But still this is not working for me. When I click on radio button, nothing happens. Below is my HTML code:
<div id="bank-details" class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<input type="radio" id="bank" name="pmt-method-radio" value="ACCOUNT" checked="checked">
<label for="bank">Checking Or Savings Account </label>
<input type="radio" id="card" name="pmt-method-radio" value="CARD">
<label for="card">Credit/Debit Card</label>
</div>
</div>
And below is my jquery code:
$('input[type="radio"]').click(function(){
alert("fired");
alert($("input[name=pmt-method-radio]:checked").val());
});

Use jquery when document ready
$( document ).ready(function() {
$('input[type="radio"]').click(function(){
alert("fired");
alert($("input[name=pmt-method-radio]:checked").val());
});
});
The ready event occurs when the DOM (document object model) has been
loaded. Because this event occurs after the document is ready, it is a
good place to have all other jQuery events and functions. Like in the
example above. The ready() method specifies what happens when a ready
event occurs.

Here is the working piece with your code only without any changes
https://jsfiddle.net/zooym4ow/
Common mistakes one usually make.
Either jquery library is not included or it's not included before the mentioned code.
Radio button was not loaded in browser when the code was getting executed. This happens if the code was included within <head> tag.
To handle this, either wrap your code within document.ready event handler as mentioned by #AmanRawat or put all of your code at the end in <body> as shown below.
$(document).ready(function(){
//Your code goes here
});
OR
<body>
<!-- Your DOM elements here -->
<script>
//Your code goes here
</script>
</body>

Related

jquery - event handler works if pasted into Console but not when included through .js file

I have an application using jquery 3.2.1
One of the pages contains 2 <form> elements which have the same class name, .products-ctp__search-form. The HTML for this is rendered on page load:
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>
I want to target the <input> elements in each form and use an event handler to deal with the user entering input into either of them. So I've written this inside a foo.js file and then linked it at the bottom of the page:
<!-- Form markup above is here -->
<script src="foo.js"></script>
The foo.js file contains:
$(function() {
$('.products-ctp__search-form input[type="text"]').bind("keyup change input",
function (e) {
console.log('debug');
console.log(e);
});
});
When I enter text into either input it doesn't log anything to the console.
But if I paste the script above into my console, it will, e.g.
debug
VM726:4 r.Event {originalEvent: InputEvent, type: "input", target: input#n1.form-control.form-control.input-border-secondary, currentTarget: input#n1.form-control.form-control.input-border-secondary, isDefaultPrevented: ƒ, …}
Strangely if I get rid of 1 of the inputs (e.g. removing the form containing n2 and keeping n1) it works fine. Other pages in the application have just 1 input and the equivalent code - when included from a linked .js file - works fine.
So I've read jquery works in console, but not in linked js file but this seems to suggest waiting for something to load. In this case the markup is rendered on page load (not via ajax, etc) and the jquery code is inside document.ready.
There is another post jQuery works in console but not in .js file which I read but again this seems to suggest having to wait for something to load. If this is the case then what am I supposed to wait for and how to I bind this?
The linked posts make sense when you're waiting for something like an image to load. But how does this work if it's just the markup of the page? Or is that not actually the problem?
jquery is included in the <head> of the document whereas the foo.js file is inside <body>. So I don't believe it's an issue of foo.js being included before jquery, etc.
I have tried your code and found that console.log(e) is causing issue (not sure why it is throwing error in console). Comment this part and don't use bind, use 'on' as bind is deprecated in jquery.
$(function() {
$(document).on("keyup change input", '.products-ctp__search-form input[type="text"]', function (e) {
console.log('debug');
//console.log(e);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<form class="products-ctp__search-form">
<input name="n1" type="text">
</form>
<form class="products-ctp__search-form">
<input name="n2" type="text">
</form>

jQuery document.ready() not firing for dynamically loaded content

I've got a PHP file (called aboutMe.php) that contains some HTML as follows:
<script type="text/javascript" src="/aboutMe.js"></script>
<div id="aboutme-gender" class="aboutme-block">
<div class="aboutme-question">My gender is:</div>
<div class="aboutme-error">Please select your gender.</div>
<div class="aboutme-answer">
<input id="gender-male" name="the-gender" type="radio" value="1" />
<label for="gender-male">Male</label>
<input id="gender-female" name="the-gender" type="radio" value="2" />
<label for="gender-female">Female</label>
</div>
</div>
The aboutme.js file contains a function as follows:
jQuery(document).ready(function($) {.....does stuff to the tags in the HTML});
This all works fine if the page is loaded directly. However when another page wants to load this dynamically as follows:
$("#load-aboutme-here").load("aboutMe.php");
...the document.ready() event doesn't fire and things don't get tagged.
I've seen similar posts but can't quite get what I need from them. Have done things like substitute the document.ready() for window.load() but then it doesn't even work at all when the aboutMe.php page is loaded directly.
Any ideas much appreciated - this is driving me nuts although I suspect it's an easy fix!
Thanks
Iain
Note that the document is the main page...not subsequent files you retrieve
The document was ready long before the ajax is done so any $(document).ready() that is called after it is ready will fire immediately. In your case it will fire before the elements exist
Move the script tag below the html that the code is referencing
<div id="aboutme-gender" class="aboutme-block">
.......
</div>
<script type="text/javascript" src="/aboutMe.js"></script>
If I understood your problem correctly, I believe you could just create a callback for the .load() function like so:
$("#load-aboutme-here").load("aboutMe.php", null, function()
{
// Code to be executed when aboutMe.php is loaded.
// i.e. The code in aboutMe.js
});

$.fn.submit() event don't trigger inside an <iframe>

Simply speaking, I have a form, and a field.
<!-- inner.html -->
<form id="inner_form">
<input type="text" name="username" />
<input type="submit" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#inner_form').submit(function() {
alert('Inner submit is triggered!');
});
});
</script>
The above code goes well: when I click the submit button, it triggers the submit event of #inner_form, and alerts the sentence: Inner submit is triggered!
My problem is, when I make another page, and loads the inner.html inside an <iframe>:
<!-- outer.html -->
<iframe id="the_frame" src="inner.html">
</iframe>
<button id="outer_submit">Submit Inner</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$('#outer_submit').click(function() {
// it don't trigger the inner submit() event!
$('#the_frame').contents().find('#inner_form').submit();
});
});
</script>
As the above code (which might not working well in the snnipet), I click the #outer_submit button, and the #inner_form do submitted, but the event I defined inside it don't triggered!
Why do this happen? And if I want the inner event triggered well with outer action, how can I got it?
While I can't give you an answer as to 'why', here's some discoveries I made while testing this:
Replacing the .submit() action with
$('#the_frame').contents().find('#inner_form input[type="submit"]').click();
Will trigger the alert. This isn't a proper fix though, because there's more ways to submit a form. Still, it shows that the events are not completely broken. So I dug deeper.
I tried using native javascript events instead of jquery's .submit([function]) bind in inner.html:
<form id="inner_form" onsubmit="alert('hi')">
That actually shows the alert. And so does this:
$('#inner_form')[0].onsubmit = function() {
alert('Inner submit is triggered!');
}
So there seems to be something wrong with the way jQuery sets and/or detects its own submit() method.
One more try:
$('#inner_form').on('submit', function() {
alert('Inner submit is triggered!');
});
This also shows the submit!
My wild guess is that for some reason when the events in inner.html are being bound, it doesn't know the form yet, even though the bind is wrapped in an implicit document.ready event through $(function(){ .. });.
As for the how and why of this I remain in the dark, but the fix is simple: wrap your event binds in an .on() method.

jQuery .on click event does not occur

Hi and thanks for reading. I've been trying to avoid using HTML onclick="__" references and instead putting these events in my .js file. After reading about jQuery's .click() and then .on() events, I tried to use this in my code for a button.
edit In my haste to make up a <p> that didn't have the rest of the contents, I entered "name" instead of "id". Many answers have recommended I either switch to a p[name=p+ or #p+ reference, but my main problem has been that I can't even hit the alert before the reference to the id/name. Thanks again for your answers.
HTML:
<p name="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
JS:
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("p" + $(this).attr("name")).remove();
});
});
The above code won't even get to the alert when I click the button. I've also tried referring to the button by name and ID, and going by $(document).ready($('.deleter')___.
I tried using the $(handler) format as well to have the click event be set after the document is ready. Neither way seems to work. At this point, I resorted to onclick="deleteButton()" and have a deleteButton() function in my .js file, but the function won't detect $(this) and just deletes all <p> tags.
The rest of my javascript is working. I haven't tried including this .on() at the bottom of the HTML, but I'm trying to avoid scripts in my HTML as well. For completeness' sake, I've been testing on both Chrome and Firefox, using a .jsp file to render the HTML.
Thanks again.
Edits
here's how I'm referencing my jquery and js, directly copy-pasted.
<script type="text/javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="javascript/index.js"></script>
</head>
here is how my html looks leading up to the div where the is inserted:
<body>
<div id="wrapper">
<div id="header">Card Draw Probability Calculator</div>
<div id="main">
<div id="cardList">
<fieldset>
<legend> Select cards for probability calculation</legend>
<div id="innerCardList"></div>
Here is how the <p> is generated:
function newestCardListLineMaker() {
var $newLine = $('<p id="newestPara"><input type="checkbox" name="new" value="none"/> <input class="cardText" type="text" maxlength="30" name="newestCard" /> Quantity <input type="text" maxlength="1" class="quantityText" name="newestQuant" /><button class="deleter" id="newestDelete">Delete</button><br/></p>');
$("#innerCardList").append($newLine);
On another note, which I should have seen before as significant: the HTML that the .click or .on(click, handler) is referencing has been created by another js function.
Try using .on() function, so your code would be:
$(document).ready({
$('.deleter').on('click', function(){
//do stuff here
});
});
Even better would be this:
$(document).ready({
$('div_above_.deleter').on('click', '.deleter', function(){
// do stuff here
});
});
Hope this helps you.
I have modify your javascript code check it.
$('.deleter').click(function() {
alert('click function works');
var p="p"+$(this).attr("name");
$('p[name='+p+']').remove();
});
working demo
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>​
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).hide();
});
});​
Edited Jsfiddle
For me it works. Didn't delete the Paragraph element though so your code should look like this instead:
<p id="pBananas"> junk </p>
<button class="deleter" id="dBananas" name="Bananas">Delete</button>
and
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
$("#p" + $(this).attr("name")).remove();
});
});
$(document).ready(function() {
$('.deleter').click(function() {
alert('click function works');
//alert($(this).attr("name"));
$("p[name=p" + $(this).attr("name") + "]").remove();
});
});​
The final code I used to complete the .on('click') event was:
$(document).ready(function() {
$("div#innerCardList").on("click", "button.deleter", function() {
var paraName = $(this).closest("p").attr("id");
$("#" + paraName).remove();
});
});
The HTML elements which I wanted to assign click events to were generated after the page was already loaded. I needed to delegate the events to the containing div.
Thanks for all the help and different perspectives!

Automatically making a div appear based on status of radio button with JavaScript

I have a form which posts data to the same page. Based on the user's radio button selection I am inserting checked="checked" into the radio button form element to redisplay the correct selection. This works fine, however when the form is redisplayed (in case of bad input etc), I need a div to be revealed (containing the relevant fields from the form).
I have an onclick event that reveals the div in the first place (before the user has posted the form), and this works fine, but when I redisplay the form I don't want the user to have to manually reveal the form again by clicking.
Therefore I've been trying something along the following lines (heavily cut down for the purposes of this post)...
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
... but it returns an Object Required javascript error (as it does in the 'real' page):
Message: Object required
Line: 3
Char: 1
Code: 0
URI: http://localhost/repair_system/javascript_test.php
Why is this? Am I not correctly referencing the form element? Apologies if I'm being a "div" (deliberate bad pun intended!), I'm yet to learn about the fun and games of javascript!
Because your javascript is not wrapped inside a function, the browser is executing it as soon as it "gets to it". In this case, the JS is being executed before the browser has reached the html declaring your form.
The simplest fix therefore is to move the Javascript to after your form. A more robust solution would be to wrap you code in a function, and have that triggered somehow - from what you appear to be trying to do, in this case it'll be the onLoad event of the body tag:
<head>
<script language="JavaScript">
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
</head>
<body onload="showHelpDiv()">
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true"/>Yes
<input id="complete_no" type="radio" name="complete" value="false"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
Your code is being executed as the document is being loaded, and the DOM tree isn't ready yet. So it is trying to access an element that doesn't exist yet.
You probably want to instead write an event handler that toggles the div whenever the checkbox is checked.
I prefer jQuery, which abstracts away things like cross-browser event handling, provides lots of nice helpers and generally makes code look cleaner (when written properly). Something like this should work:
$(document).ready(function() {
$('#repair_complete').toggle($('#complete_yes').is(':checked'));
}
The above can be roughly translated as:
When the document loads, perform the following:
Add an event handler for the 'change' event to any elements of type 'input' with a name of 'complete'
When the event handler fires, toggle the visibility of the element with ID 'repair_complete' where it should be visible if the element with ID 'complete_yes' is checked
Update: The JS above now actually does what you want, originally I had it written as an onclick
This is because Javascript is executed just before rest of the objects are created.
Place your javascript code into the function body, and add this function into onclick event for whatever you need.
<link href="styles/style1.css" rel="stylesheet" type="text/css" />
<script language="JavaScript">
function test() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
</script>
<form action="javascript_test.php" method="POST">
<input id="complete_yes" type="radio" name="complete" checked="checked" value="true" onClick="javascript: test();"/>Yes
<input id="complete_no" type="radio" name="complete" value="false" onClick="javascript: test();"/>No
<input type="submit" value="Save">
<div id="repair_complete">
I'm a div!
</div>
</form>
It looks to me as though your script is firing before the form is drawn, you may want to move your script block to after the form element. Basically I think that the document.getElementById('complete_yes').checked is looking at null.checked, which would trigger the object required error.
You should make the action of the radio button be to change the visibility of the div (that is, "push" the status to it), rather than to "pull" the div status via the radio button status at render time (which as Andrejs said, will be unset).
Sounds like the problem is in your initialization code. The javascript is being called before the page is finished rendering. It's one annoying aspect of the "onload" event that in my opinion simply doesn't work as it should in every browser.
There's a cross-browser technique to call initialization code once and only once after the DOM is fully loaded.
Try this code in the HEAD of your HTML:
function showHelpDiv() {
if (document.getElementById('complete_yes').checked) {
document.getElementById('repair_complete').style.display = 'block';
} else {
document.getElementById('repair_complete').style.display = 'none';
}
}
function InitOnce()
{
if (arguments.callee.done) return;
arguments.callee.done = true;
showHelpDiv();
}
/* for Mozilla */
if (document.addEventListener)
{
document.addEventListener("DOMContentLoaded", InitOnce, null);
}
/* for Internet Explorer */
/*#cc_on #*/
/*#if (#_win32)
document.write("<script defer src=ie_onload.js><"+"/script>");
/*#end #*/
/* for other browsers */
window.onload = InitOnce;
And then you need to create an ie_onload.js file that contains this line for IE compatibility:
InitOnce();
I've tried other techniques but none work as perfectly as this. I believe I originally found this solution here:
http://dean.edwards.name/weblog/2005/09/busted/
I use it in an online application that receives 500 unique visits a day or so and this has been reliable for us.

Categories

Resources