Enable Radio Button Checked On Load - javascript

I'm wanting to ensure the "Email" radio button is checked on load rather than the phone.
For some reason the "Phone" radio button is checked onload yet both inputs are showing, I don't quite understand that.
DEMO HERE
Here is my jQuery
var ebuForm = {
init : function() {
ebuForm.showInput();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.prop('checked', true);
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val()=="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
}
};
$(function() {
ebuForm.init();
});

Working demo http://jsfiddle.net/2F88K/ or http://jsfiddle.net/775X2/
Order of the change event
triggering the cahnge event will do the trick.
If I may recommend: Try keeping your change event outside. see this radioInput.prop('checked', true).trigger("change");
The use of radioInput.prop('checked', true) is kind of interesting which I wont encourage. :) think that radio buttons are either / or i.e. one of the 2 will be selected at one point.
Hope rest fits your need. :)
Code
var ebuForm = {
init : function() {
ebuForm.showInput();
},
showInput : function(e) {
var radioInput = $("input[type='radio']"),
emailRadio = $("input[value='email']");
radioInput.change(function(){
var emailInput = $('.email-input'),
phoneInput = $('.phone-input');
if($(this).val() =="email") {
emailInput.show();
phoneInput.hide();
console.log('Email Enabled');
} else {
emailInput.hide();
phoneInput.show();
console.log('Phone Enabled');
}
});
radioInput.prop('checked', true).trigger("change");
}
};
$(function() {
ebuForm.init();
});

First input[value='email'] is not such a good selector -- use #email instead. The reason the phone radio button is checked is because you are checking it with the code:
radioInput.prop('checked', true);
Your probably wanted to write:
emailRadio.prop('checked', true);
And remember you cannot check both phone and email! They both have the same name.

Try this
JS Fiddle
The key here is $('#email').prop('checked', true).trigger('change');

Many ways to do this...
Solution #1: (HTML)
You could use checked="checked"
JSFiddle Demo
Solution #2: (JQuery)
var email = $("#email");
email.prop('checked', true);
And to hide the phone input on page load, you can trigger the change event:
email.prop('checked', true).trigger('change');
JSFiddle Demo

Related

jQuery - Enable/Disable a button following checkboxes state

I'm using ASP.NET MVC 4 to develop a web app. I have a page which contains a submit button which should be enabled only if one of my two checkboxes (or both of them) is (are) enabled. The thing is, I'm trying to add an "or" operator in the following script but it does not give me what I want. So, here's my script :
The jQuery sample
And this is the part I'd like to improve :
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
the_terms.click(function() {
if ($(this).is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});
And I can't find a way to tell my document "Okay, if one of these 2 checkboxes (or both of them) is (are) checked, we can press on the button. If not, don't allow it".
Any idea guys?
It can be done with:
Fiddle
$('.checkbox').change(function(){
$('#submitBtn').prop('disabled', !$('.checkbox:checked').length > 0)
});
Note:
This find the checkboxes by class name checkbox so it will work with two checkboxes, whereas your original code is looking at a single checkbox via its ID.
Use the change event not click.
Simply use
$(".checkbox").click(function() {
$("#submitBtn").prop("disabled", !$('.checkbox:checked').length);
});
DEMO
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
$('.checkbox').change(function(){
$("#submitBtn").prop("disabled", !(the_terms.is(":checked") || the_terms2.is(":checked")));
});
});
// Make a function to be called on onload or on click
function checkTerm() {
jQuery('input[type="submit"]').attr('disabled',!jQuery('input.term:checked').length > 0 ) ;
}
// Call the function on load
$(document).ready(checkTerm) ;
// And call it on check change
jQuery(document).on('change','input.term',checkTerm) ;
Try below modified script , please check if it works as you want.
$(document).ready(function() {
the_terms = $("#the-terms");
the_terms2 = $("#the-terms2");
if(the_terms.is(":checked") || the_terms2.is(":checked"))
{
$("#submitBtn").removeAttr("disabled");
}
else
{
$("#submitBtn").attr("disabled", "disabled");
}
the_terms.click(function() {
if ($(this).is(":checked") || the_terms2.is(":checked")){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
the_terms2.click(function() {
if ($(this).is(":checked") || the_terms.is(":checked") ){
$("#submitBtn").removeAttr("disabled");
} else {
$("#submitBtn").attr("disabled", "disabled");
}
});
});

Activate check and reset button after complete all inputs

I have 6 input fields and I need to make check and reset buttons active after all inputs were completed.Ill attach a fiddle and some code.
JSFiddle
$('.input').on('input', function() {
limit();
checkBtn.disabled = false;
resetBtn.disabled = false;
});
You could find empty inputs using a selector. If there are empty inputs, disable buttons; otherwise enable them.
$('.input').on('input', function() {
if($('input[value=""]').length) {
checkBtn.attr("disabled", "disabled");
resetBtn.attr("disabled", "disabled");
} else {
checkBtn.removeAttr('disabled');
resetBtn.removeAttr('disabled');
}
});

Form validation not working with <select>s

I have JavaScript code that checks if all the fields in a form are filled, if not it pops up a bootstrap alert using jquery. This works fine with text inputs, but when checking selects, it always fires the error, even if an option is filled.
JavaScript Code:
$(document).ready(function () {
$('form[name="register"]').on("submit", function (e) {
var username = $(this).find('input[name="username"]');
var preferredClass = $(this).find('input[name="preferredClass"]');
if ($.trim(username.val()) === "" || ($.trim(preferredClass.val())) === "") {
e.preventDefault();
$("#formAlert").slideDown(400);
} else {
$("#formAlert").slideUp(400, function () {});
}
});
$(".alert").find(".close").on("click", function (e) {
e.stopPropagation();
e.preventDefault()
$(this).closest(".alert").slideUp(400);
});
});
The entire code and (Kind of) working example can be found in this JSFiddle.
you have wrong selector for your select
Replace this
var preferredClass = $(this).find('input[name="preferredClass"]');
With this:
var preferredClass = $(this).find('select[name="preferredClass"]');
Working Demo
Your select element selector is wrong.
Try to change the selector statement:
$(this).find('select[name="preferredClass"]');
Then your validation will be ok.
Hope this is helpful for you.

Onsubmit validate change background requried fields?

Anyone know of a good tutorial/method of using Javascript to, onSubmit, change the background color of all empty fields with class="required" ?
Something like this should do the trick, but it's difficult to know exactly what you're looking for without you posting more details:
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
//Else block added due to comments about returning colour to normal
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
This attaches a listener to the onsubmit event of the form with id "myForm". It then gets all elements within that form with a class of "required" (note that getElementsByClassName is not supported in older versions of IE, so you may want to look into alternatives there), loops through that collection, checks the value of each, and changes the background colour if it finds any empty ones. If there are any empty ones, it prevents the form from being submitted.
Here's a working example.
Perhaps something like this:
$(document).ready(function () {
$('form').submit(function () {
$('input, textarea, select', this).foreach(function () {
if ($(this).val() == '') {
$(this).addClass('required');
}
});
});
});
I quickly became a fan of jQuery. The documentation is amazing.
http://docs.jquery.com/Downloading_jQuery
if You decide to give the library a try, then here is your code:
//on DOM ready event
$(document).ready(
// register a 'submit' event for your form
$("#formId").submit(function(event){
// clear the required fields if this is the second time the user is submitting the form
$('.required', this).removeClass("required");
// snag every field of type 'input'.
// filter them, keeping inputs with a '' value
// add the class 'required' to the blank inputs.
$('input', this).filter( function( index ){
var keepMe = false;
if(this.val() == ''){
keepMe = true;
}
return keepMe;
}).addClass("required");
if($(".required", this).length > 0){
event.preventDefault();
}
});
);

How to uncheck a radio button by clicking on it a second time

I have been searching in a lot of topics but I haven't found anything that really correspond to my problem :
I want to make radio buttons uncheckable (i.e. uncheck a radio button by clicking on it when it's already checked).
I found some solutions using a hidden radio button as a temporary comparison object but this doesn't fits to my existing context, so I would like to do the same without another radio button.
I tried to simply test and change the status/value of the radio button on "onclick" event but it hasn't been very successfull...
Thanks in advance,
Clem.
That's not what radio buttons are. If you try to make this work, you will just confuse your users.
If you want something that can be checked and then unchecked, use a checkbox. Radio buttons are for selecting exactly one of some set of options.
better so:
onclick="
var isChecked = $(this).attr('is_che');
if (isChecked) {
$(this).removeAttr('checked');
$(this).removeAttr('is_che');
}
else {
$(this).attr('checked', 'checked');
$(this).attr('is_che', 'true');
}"
I know this sort of action is non-standard for radio buttons, but the poster requested the functionality. The following is code that I've used in the past. I've found it not to be the most optimized (assuming a large # of radio buttons), but I also haven't taken the time to do that optimization.
// Allow for radio button unchecking
$(function(){
var allRadios = $('input[type=radio]')
var radioChecked;
var setCurrent = function(e) {
var obj = e.target;
radioChecked = $(obj).attr('checked');
}
var setCheck = function(e) {
if (e.type == 'keypress' && e.charCode != 32) {
return false;
}
var obj = e.target;
if (radioChecked) {
$(obj).attr('checked', false);
} else {
$(obj).attr('checked', true);
}
}
$.each(allRadios, function(i, val) {
var label = $('label[for=' + $(this).attr("id") + ']');
$(this).bind('mousedown keydown', function(e){
setCurrent(e);
});
label.bind('mousedown keydown', function(e){
e.target = $('#' + $(this).attr("for"));
setCurrent(e);
});
$(this).bind('click', function(e){
setCheck(e);
});
});
});

Categories