onclick function on a radio or checkbox input? - javascript

Is it possible to have a function execute when a radio or checkbox is clicked?
I tried this:
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()" value=1 <?PHP echo $on;?>>
It doesn't work. I could wrap it in a label and put the onclick function on that, but I need it only on the radio button and not the label. Is this possible?
UPDATE:
Thanks for your answers! I tried it with another function and it worked fine. Part of the original function was to set the checkbox to "checked" and apparently that was conflicting with it. I made a duplicate function with that part removed and it works fine. :)

Basically, and normally yes. If the Javascript function is declared properly and/or file containing the function is included properly on the page. See example:
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()">
<script>
function select_on() {
alert('Hello');
// do whatever you want here.
}
</script>

Your snippet works for me. You might have a trigger attached to this element, and that can eat up your default event handling.

It works just fine, you have errors elsewhere or there's an element on top of your checkbox and you're not really clicking on it.
See it here:
function select_on() {
alert('it works!');
}
<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on()" value=1 />

<input name="email_notification" id="email_not1" type="radio" class="form_radio" onclick="select_on(this)">
<script>
function select_on(node) {
if(node.checked) {
alert('checked true');
} else {
alert('checked false');
}
}
</script>

You can use jquery change function here.
Sample code:
$('input:radio[name="email_notification"]').change(function() {
//do whatever you need here
});
Or if you want to trigger a function for every clicks you can simply use:
$('input:radio[name="email_notification"]').click(function() {
//do whatever you need here
});

Related

Retrieving data from a form loaded with jQuery and passing it to a parent page

I have a 'parent' page that is using the following bit of code to pull in a form from a different page on the same domain. There are reasons why I can't just place the form directly on the 'parent'.
<script type="text/javascript">
jQuery("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
function() {}
).hide().fadeIn(1000);
</script>
The form that is pulled in looks like this:
<form action="https://example.com/form/" method="post" id="profile-edit-form" class="standard-form base" target="hiddenFrame">
<label for="field_1">Name</label>
<input id="field_1" name="field_1" type="text" value="Joey-Jojo Jr. Shabadoo">
<input type="submit" name="profile-group-edit-submit" id="profile-group-edit-submit" value="Save Changes " />
<input type="hidden" name="field_ids" id="field_ids" value="1" />
<input type="hidden" id="_wpnonce" name="_wpnonce" value="a62f8d5fec" />
<input type="hidden" name="_wp_http_referer" value="/form/" />
</form>
When 'submit' is clicked, https://example.com/form/ is opened in a hidden iframe and the user name gets properly saved. This all works well.
I would like the user name on the currently loaded 'parent' page to update via jquery, so that the user has some immediate visual feedback that the name change has taken place.
My approach has been to try and take the value out of the 'field_1' input when 'submit' has been clicked, and pass that variable onto a div in the parent page with an id of 'display_name'.
$(document).ready(function(){
function nameUpdate(){
$("#profile-group-edit-submit").click(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
}
nameUpdate();
});
I've also tried adding window.parent.
before the the #display_name selector section and it didn't change anything.
I've used this approach on another button/div combo on the same page and it works, the difference is that that particular button is in an iframe, not loaded by jquery. So I'm guessing my problem is related to that fact.
I've googled around, but have run out of ideas of how to phrase my question, what to look for, etc...
Any help would be greatly appreciated. Thanks!
Edit: For clarity, the div w/ id #display_name won't update.
Use jquery to handle the form submission.
$(document).ready(function(){
$('#profile-edit-form').submit(function(){
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
});
EDIT:
Due to your loading the form dynamically you need to bind the submit function after the load. So...
$(document).ready(function () {
var formLoaded = function () {
$('#profile-edit-form').submit(function () {
var updateName = $("#field_1").val();
$("#display_name").text(updateName);
});
};
$("#ai_temp_profile_edit").load(
"https://example.com/form/ #profile-edit-form",
formLoaded
).hide().fadeIn(1000);
});
If I am understanding it correctly, your problem is "display_name" field is not getting updated with the latest value.
If this is the problem then can you try below thing?
Instead of
$("#display_name").text(updateName);
try using-
$("#display_name").val(updateName);
As per the documentation on jQuery site Val() works well with form Elements whereas text won't.
More on Val() method- https://api.jquery.com/val/#val2

How do I make this Javascript checkbox trigger action work like my CSS only example

I'm using the following code to test for "if" a checkbox is checked on page load.
If it is, then a certain additional field will be shown (called myfield):
<style>
#myfield {
display: none;
}
</style>
<input type="checkbox" id="mycheckbox" name="mycheckbox" />
<input type='text' id='myfield' name='myfield' />
<script>
if ($("#mycheckbox").is(":checked")) {
document.getElementById("id").style.display="block";
}
</script>
However, this only works when the page loads and the checkbox is already checked. It doesn't work live when the box isn't checked on page load, and you go to click the box. I want the hidden field to show up right away when the box is "checked" without the page having to reload. I then want myfield to hide right away when the box is unchecked.
Can any anyone point out the better/proper way to do this?
Additionally:
Of note: I do know how to do this in CSS using labels, but I need to use javascript other times.
Here's what works fine in modern browsers using just CSS: http://jsfiddle.net/3KTC3/
Here's that CSS only jsfiddle code:
<style type="text/css">
.label-for-check {
display:none;
}
.check-with-label:checked + .label-for-check {
display:block;
}
</style>
<div>
<input type="checkbox" id="check" class="check-with-label" />
<label for="check" class="label-for-check">
<br /><br />MyField<br />
<input type='text' id='myfield' name='myfield' size='10' />
</label>
<div>
You need to attach a change event handler. Your posted code only executes when page is loaded, it doesn't watch over your element's state.
Here's a jQuery equivalent to your CSS version with classes and adjacent selector:
$('.check-with-label').change(function() {
$(this).next().toggle(this.checked);
}).change();
Fiddle
Explanation: this references the checkbox being clicked, get the next element (equivalent to your CSS + selector) and toggle its display based on the checked state of the checkbox.
Another version that works only with your 2 given IDs:
$('#mycheckbox').change(function() {
$('#myfield').toggle(this.checked);
}).change();
Fiddle
Note that your CSS version is compatible with all desktop browsers including IE7 and above. Consider whether it is necessary to use JS for this.
edit: You have to trigger the change handler after attaching it, so if the checkbox is already checked when the page is loaded, the triggered handler will display the field.
Your problem is that jQuery will only check one time (when you load the site) if your checkbox is checked.
The change handler will fire every time the user changes the checkbox, if it is cheked it will show #myfield
Do something like this:
$('#mycheckbox').change(function() {
if ($(this).is(":checked")) {
$('#myfield').show()
}
});
$(document).ready(function(){
if($("#mycheckbox").is(":checked")) $('#myfield').show();
$('#mycheckbox').on('change', function(){
if($(this).is(":checked")) {
$('#myfield').show();
} else {
$('#myfield').hide();
}
})
});

jQuery input button click event listener

Brand new to jQuery.
I was trying to set up an event listener for the following control on my page which when clicked would display an alert:
<input type="button" id="filter" name="filter" value="Filter" />
But it didn't work.
$("#filter").button().click(function(){...});
How do you create an event listener for a input button control with jQuery?
First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
DEMO
$("#filter").click(function(){
//Put your code here
});
More on gdoron's answer, it can also be done this way:
$(window).on("click", "#filter", function() {
alert('clicked!');
});
without the need to place them all into $(function(){...})

jQuery form error checking

I'm doing a simple jQuery form checker for a website. I have two forms on the website: a login form and a signup form. My code is as followed:
$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if { hasError $('div.error').fadeIn() }
else { $(this).parents('form').submit() }
});
So my question is, both the login button and the signup button has a class called btn, how can I have the them check and submit their own form instead of checking all the forms on the page since $(this).parents('form') will get both the signup and login form?
Thank you!
no $(this) will get that form whose respective btn u have clicked. "this" keyword pass object of an ellement so don't worry this code will run fine.
There is something really wrong with your html markup if $(this).parents('form') returns more than one element. Also, consider to shorten your code to just
$('.btn').click(function(e) {
// DO SOME ERROR CHECKING HERE
if (hasError) {
e.preventDefault();
$('div.error').fadeIn();
}
});
give them id, and take it like this.
$('#btn1).click(....
$('#btn2).click(....
Change your HTML form structure so that when when you click either button, you are able to select the corresponding form.
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
<form action="get">
<input type="text" value="1" />
<input type="button" class="btn" />
</form>
And jQuery:
$(function(){
$(".btn").click(function(){
$(this).closest("form").submit();
});
});
EDIT
A better selector for your error handling
$(this).closest('form').find('.required').each(function(){
});
http://jsfiddle.net/c9GXZ/6/
If you want to go ahead with your code then you can go just take look on .parent() and .parents() method of jQuery.
The .parents() and .parent() methods are similar, except that the latter only travels a single level up the DOM tree.
Try, to use $(this).closest('form').submit() instead of $(this).parents('form').submit(). I am not user but I think you have included form inside a form(check or share your HTML as well.)
$('.btn').click(function(e) {
e.preventDefault();
// DOES SOME ERROR CHECKING HERE
if (hasError) { $('div.error').fadeIn(); } //some syntax change
else { $(this).closest('form').submit() } ///will get the nearest form element and stop there and will submit it as per your code...
});
UPDATE
replace this
$('.btn').click(function(e) {
with this
$('.btn').on('click',function(e){
This got it working in your jsfiddle url...

JQuery Custom Image From Checkbox to Radio

I am using the following code to make a custom checkbox with my own images and it works but it's using a Checkbox and I need to use Radio buttons.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#moreinfo").change(function() {
if(this.checked) {
$(this).prev().attr("src", "checkbox_unchecked.gif");
} else {
$(this).prev().attr("src", "checkbox_checked.gif");
}
});
});
</script>
Next...here's the HTML:
<label for="moreinfo">
<img src="checkbox_unchecked.gif"/>
<input name="moreinfo" type="checkbox" id="moreinfo" style="display:none">
</label>
If it a question of changing from checkbox to radio type or does the jquery need changing too?
How do I go about this?
Change the type="checkbox" to type="radio" (and add some more radio buttons for testing, grouping them via the name attribute, they may not have the same id as IDs are unique!). Then, you also need to handle the click event of the replacement images.
But actually, that's going beyond your original question, which you could have solved by simply trying it out. ;)
A Radio Button uses also the attribute checked. So you can switch the element without changing the script (perhaps the gifs).
But your script will never run, because your checkbox/radio button is not displayed.
So you need some functionality to change the status when clicking the image.

Categories

Resources