I have checkbox that I'm using to toggle whether an input field is "required" using jQuery. This is part of Foundation Abide validation. So, at the end of the input field it needs to add/remove the word "required".
The box is checked by default. When the user unchecks the box it adds "required" to the input as it should (else if). However, if you recheck the box, the "removeProp" doesn't remove "required". What am I doing wrong on this? I've tried both prop and attr functions with the same result.
<input type="checkbox" id="billing" checked>
<input type="text" id="b_name" pattern="alpha" required>
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').removeProp('required');
}
else if (!$(this).is(':checked')) {
$('#b_name').prop('required', true);
}
});
Try this:
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').prop('required', false);
}
else {
$('#b_name').prop('required', true);
}
});
You can clearly see the behavior there. Once it removes the property it is not adding the property back.
You can see the same case mentioned at Jquery docs for .removeProp().
As it says -
Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
So you can set it to false and true on check and uncheck rather than removing the property completly
$('#billing').change(function() {
// Same as Shipping Address
if ($(this).is(':checked')) {
$('#b_name').prop('required', false);
}
else if (!$(this).is(':checked')) {
$('#b_name').prop('required', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="billing" checked>
<input type="text" id="b_name" pattern="alpha" required>
Related
I'm trying to achieve condition, when input has value greater than 1 and radio button is checked then remove disabled class from the anchor.
This is my code
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
$("input").keyup(function () {
if ($("#age").val().length > 1 && $('input[name=education]:checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
It is triggering after input has value without checking radio is checked.
Can anyone help me with this?
Thanks in advance.
Using :checked is fine. But it doesn't return a boolean. You need to check that it returns an element. $(':prop').length > 0 (or using prop('checked')).
Some other stuff you need to change.
The condition should not be on the $("#age").val().length but on the $("#age").val() itself.
Use checkbox, not radiobutton. radiobutton is used to choose one option from others, not to set true/false.
You need to check the values on input keyup, but also on change of the radio (or checkbox).
Try this:
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education']").is(':checked')) {
$("#diploma").removeClass("disabled");
} else {
$("#diploma").addClass("disabled");
}
});
Use prop('checked') to check radio, refer code below,
$( document ).ready(function() {
$("input").keyup(function () {
if ($("#age").val().length > 1 && $("input[name='education'][value='univeristy']").prop("checked")) {
$("#diploma").removeClass("disabled");
console.log("Removed class 'disabled'");
} else {
$("#diploma").addClass("disabled");
console.log("Added class 'disabled'");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input name="age" id="age" type="text">
<input name="education" type="radio" value="univeristy">
Calculate
</body>
Run this code and see console log.
onclick of one radio button i have to check one condition if true i have to check it or restore to same old status,
html
<input type="radio" name="test" id="radio0" onclick="myFunction()" checked />
<input type="radio" name="test" id="radio1" onclick="myFunction()" />
<input type="radio" name="test" id="radio2" onclick="myFunction()" />
JS
globalCondition = false;
function myFunction()
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
As I said in comment return in the function will not do anything as you're not returning the function value in the in-line code.
Although the other solutions offered are correct, to keep your code unobtrusive, you should not have inline JS at all (remove the onclick='s).
I realize the question was not tagged jQuery, but maybe it should have been: Instead on onclick you should use a jQuery event handler, selecting only the set of radio buttons.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/KVwL3/1/
globalCondition = false;
$(function(){
$("[name=test]").click(function(e){
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
return false;
// or
e.preventDefault();
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
});
});
Notes:
DOM ready event:
$(function(){ YOUR CODE HERE }); is a shortcut for $(document).ready(function(){ YOUR CODE HERE});
Selectors
If an attribute [] selector = value contains special characters it needs to be quoted:
e.g.
$('[name="IstDynamicModel[SD_WO_CREATE]"]')
There are any number of selectors that will choose just the three radio buttons. As this is a simple one-off connection, at startup, there is no real speed difference between any options, but you would normally try and make the selector specific in ways that might make use of various lookup tables available to the browser:
e.g.
$('input[type=radio][name="IstDynamicModel[SD_WO_CREATE]"]')
This will be slightly faster as it will reduce the slowest check (the name=) to only radio inputs.
try this:
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
}
else
{
e.preventDefault();
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
USe like this
<input type="radio" name="test" id="radio1" onclick="return myFunction()" />
javascript
globalCondition = false;
function myFunction(e)
{
if(globalCondition)
{
//some codes and it will check clicked radio button anyway
return true;
}
else
{
return false; // i tried this but its not working
/*here i don't want to check clicked radio button, and previously
checked button should be checked*/
}
}
I have a radio button selection that jquery is able to loop through them and read the values for each one just fine, but jquery can only detect when one of them has been selected. When selecting the other one, jquery just ignores it and tells me none have been selected.
jquery:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = false;
}
});
html:
<input type="radio" id="upload" name="banner_type" value="upload" />
<input type="radio" id="html" name="banner_type" value="html" />
"upload" is being ignored by jquery, "html" is not
Im doing it this way:
valid=false;
$('[name="banner_type"]').each(function() {
if($(this).is(':checked'))
valid = $(this).val();
});
So each time You check for radio being checked, valid value is renewed.
here's fiddle for You. Function "check" checks validity, returning false if none is selected.
http://jsfiddle.net/CLaDG/
The else part is setting value for valid but not returning it. Also the value is always false for second radio button. Try this:
$('[name="banner_type"]').each(function() {
console.log($(this).val());
if($(this).is(':checked')) {
valid = $(this).val();
return valid;
} else if(!$(this).is(':checked')) {
valid = $(this).val();
return valid;
}
});
This can be written shorter and better but right now I am just fixing the issue I see.
not sure which version of jQuery you are on, but try using jQuery.prop as well as delegated event on the container might be cleaner, such as:
$('.your-radios-container').on('change','[name="banner_type"]',function(){
valid = $(this).prop('checked');
});
I have forked your fiddle to show you how it could work:
http://jsfiddle.net/AcMBR/2/
I have the following set of checkboxes:
Original:
<INPUT TYPE="checkbox" ID="db1" class="db" checked>
<INPUT TYPE="checkbox" ID="db2" class="db" checked>
<INPUT TYPE="checkbox" ID="db3" class="db" checked>
<INPUT TYPE="checkbox" ID="db4" class="db" checked>
</br>
Other:
<INPUT TYPE="checkbox" ID="other" class="other" onclick="otherBoxes('other',this)">
and the following javascript:
<script language="JavaScript" src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
function otherBoxes(it,box)
{
$(function()
{
$(':checkbox').click(function()
{
if (this.checked)
{
$('.db').prop('checked',false);
}
}
)
}
)
}
</script>
What I am trying to do is set someting up so that when I check the 'other' checkbox, the 'Original' checkboxes are all unchecked.
I then want to have the reverse, so that if one (or more) of the 'Original' checkboxes are checked, the 'other' checkbox is unchecked.
The Javascript I have so far kind of does the first part of this, in that if I check, then uncheck, then check the 'other' box again, the 'Original' boxes are unchecked.
However, I would like it to work when the box is checked the first time.
It also has the unintended consequence, that after the 'other' box has been checked, the 'original' boxes refuse to be checked, even if I uncheck the 'other' box.
I've found lots of examples of similar situations, but none the same, and I haven't been able to adapt any that I have found. How can I do this please?
You can try something like that
$('.other').on('click' , function() {
$('.db').each(function(){
$(this).removeAttr('checked');
})
});
$('.db').on('click', function(){
$('.other').removeAttr('checked');
});
here it is a working jsfiddle http://jsfiddle.net/vQTFm/
P.S. : I suggest you to avoid using similar names beetwen ids and classs because it CAN be confusing.
You should bind the events using jQuery instead of in the HTML.
Here is some code that does what you want, it binds to the change event on the checkboxes and then checks whether it was the other or db checkboxes that were checked and unchecks the required check-boxes:
$(function() {
$('.db, #other').on('change', function() {
if (this.checked) {
if ($(this).is('#other')) {
$('input:checkbox').not('#other').prop('checked', false);
} else {
$('#other').prop('checked', false);
}
}
});
});
Working example - http://jsfiddle.net/YD5SE/2/
Use the following JS code:
<script type="text/javascript">
function otherBoxes(it,box)
{
if (box.checked)
{
$('.db').prop('checked',false);
}
}
</script>
I have a page that has a number of checkboxes in it. I would like to write a function that will be called when the ckeckbox is clicked, that determines if the checkbox is checked or not.
<input type="checkbox" onclick="toggleVis('id', this);"/> ID
<input type="checkbox" onclick="toggleVis('edit', this);" checked="checked"/> Edit
<input type="checkbox" onclick="toggleVis('last', this);"/> Last
Note some checkboxes start checked.
I figured that there must be a way to do this based on a reference passed, so I passed the this value as a parameter.
function toggleVis(name, checkbox)
{
//if(checkbox.checked())
console.log('checked');
if($('.'+name).css('display') != "none")
$('.'+name).css('display', 'none');
else
$('.'+name).css('display', 'table-cell');
}
I am open to use jQuery.
You were close.
if(checkbox.checked) {
console.log('checked');
//...
}
There's no checked() method, but there is a checked property. Note that your code may only work on clicks. Perhaps onchange would be better?
Look at the checkboxobj.checked property (instead of calling it like a function). In your case, you could reference if (checkbox.checked) { ... }. More information can be found on this website
If you wanted to do this with jQuery you might try the following. Note that I'm binding to the checkbox instead of including the 'onclick' or 'onchange' directly on the HTML element.
$('[type=checkbox]').click(function(){
if( $(this).attr('checked') ){
console.log('checked');
if($('.'+$(this).attr('name')).css('display') != "none") {
$('.'+$(this).attr('name')).css('display', 'none');
} else {
$('.'+$(this).attr('name')).css('display', 'table-cell');
}
}
});
And a JQuery-based solution:
var checked = $(checkbox).is(':checked');
Helpful if you want to find the checkbox first by some JQ selector.
<input type="checkbox" class="checkthis"> ID
<input type="checkbox" class="checkthis" checked="checked"> Edit
<input type="checkbox" class="checkthis"> Last
$(input.checkthis).click(function() {
if($(this).is(':checked') {
// do checked stuuf
} else {
// do not checked stuff
}
});