I have a form with several checkbox fields and a corresponding Comments fields for each checkbox. I dynamically create these fields. For example, the checkbox field, tag1, would correspond to comments1. When the checkbox is checked, I don't want to require comments. When it is not checked, I want to require comments.
Sometimes the fields are pre-populated based on a user's last input. In other words, the checkbox may already be checked when the page loads or it may not be. I have logic set to build the corresponding comments field as required or not required based on this.
Everything situation seems to be working except one. When I check the box and then uncheck the box, the form allows me to submit with no comments. Below is what I have tried.
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#comments' + this.id.replace('tag', ''));
otherInput.removeProp('required', !checkbox.is(':checked'));
if (!checkbox.not(':checked')){
otherInput.prop('required',true);
}
});
--------------------second attempt
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#comments' + this.id.replace('tag', ''));
otherInput.prop('required', !checkbox.not(':checked'));
otherInput.removeProp('required', !checkbox.is(':checked'));
});
Both of these solve the same situations, except the one noted above. Please advise.
Just toggle the 'required' property based on checkbox status
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#comments' + this.id.replace('tag', ''));
otherInput.prop('required', !checkbox.is(':checked'));
});
See this JSFiddle
When the "submit" button is pressed, do your validation:
psuedocode:
onSubmitPressed: function(){
if(checkbox is checked){
// alert user field is required;
return false;
}else{
return true;
}
Looks like I had some bad syntax, however it was not throwing an error. I changed my first attempt to:
$(document).on('change', 'input[type=checkbox]', function() {
var checkbox = $(this),
otherInput = $('#comments' + this.id.replace('tag', ''));
otherInput.removeProp('required', !checkbox.is(':checked'));
if ($(this).is(':not(:checked)')){
otherInput.prop('required',true);
console.log('working');
}
});
This now adds and removes the required attribute based upon the checkbox being checked or not checked.
Related
Currently working on jquery clone where user click add it will clone the div perfectly but I have dropdown. If user select cellphone in drop down and in other dropdown if user select the same cellphone it should duplicate found and the dropdown value has to clear.
$('.slt_major select option:selected').each(function(i, e) {
alert("check");
//Check if values match AND if not default AND not match changed item to self
if ($(e).val() == cI.val() && $(e).val() != 0 && $(e).parent().index() != cI.index()) {
alert('Duplicate found!');
cI.val('0');
}
});
I was not able to see where the error was even the alert was not generating. Here is the fiddle link.
Thanks.
So here it is: DEMO
First I would like to correct your adding part since you were adding duplicate ids into internal elements of cloned row. So just change your code as below and check for inline comments.
$(document).on("click", ".btn_more", function () {
var $clone = $('.cloned-row:eq(0)').clone();
$clone.find('[id]').each(function(){
this.id=this.id +(count) //change the id of each element by adding count to it
});
$clone.find('.btn_more').after("<input type='button' class='btn_less1 phn_del' value='Del' id='buttonless"+count+"'/>")
$clone.attr('id', "added"+(count)); //just append count here
$clone.find('.preferred').attr('checked', false);
$clone.find('.sslt_Field').val(0);
$clone.find('.txt_CC').val('');
$clone.find('.txt_Pno').val('');
$(this).parents('.em_pho').after($clone);
count++; //increment count at the end.
});
Now to check for duplicate options you can do it as below. Also check inline comments:
//attach event handler to document since you need event delegation on dynamically created elements
//attach change event to class 'sslt_Field'
$(document).on('change','select.sslt_Field',function(event) {
var cI = $(this); //store a reference
var others=$('select.sslt_Field').not(cI);
//store reference to other select elements except the selected one
$.each(others,function(){
//iterate through remaining selects
if($(cI).val()==$(this).val() && $(cI).val()!="")//check if value has been
//already selected on other select
{
$(cI).val('');//empty the value
alert('already selected');//display alert.
}
});
});
I've checkbox list that load by ajax and I want to show the checked value in page while user checking each checkbox. Please see below image.
Hear That country and City load from the ajax according to the parent selection. Here there are 4 cites are checked and I want to show those all selected city values below the check boxes.
I've used below jquery code but it doesn't work.
$("#cites input[type='checkbox']").click(function(){
var checkedc = $(this).val();
$('#show_city').html(checkedc);
});
Use .on()
You have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );
like this
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
if (this.checked) {// check if the checkbox is checked
var checkedc = this.value;
$('#show_city').html(checkedc);
}
});
or
$('parentElementPresesntAtDOMready').on('click','#cites input[type="checkbox"]',function(){
// code here
});
Updated After OP's comment
.map()
$(document).on('change', '#cites input[type="checkbox"]', function () {
var checkedc = $('#cites input[type="checkbox"]:checked').map(function () {//use map to create array of checked elements
return this.value;
}).get().join(); //than join array with comma to string
$('#show_city').html(checkedc);
});
I'm completing Tushar's answer so that you get all the checked cities :
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
var listChecked = "";
if (this.checked) {// check if the checkbox is checked
if (this.checked) {
var value = $(this).val();
listChecked = listChecked + value + ";";
}
}
$('#show_city').html(listChecked);
});
I am dealing with the following jQuery issue in IE.
For a form I need to replace the default placeholders fields, this is done by jquery, placeholder is hidden and the value of it is added to a position:absolute label on the input.
This all works as I want but, the problem I am facing; When I am filling down te form, the values are set (in a session). After submit I go to the second step. I can go back to the first stap by clicking a link.
This is the situation when I just fill down the form element OR I do a hard browser refresh
like F5.
When I just hit the link in the tempalte to go back one stap, this is the result
The custom placeholder (as a label in red) should be hidden but won't do this as I aspect I should have to. I am facing this issue only in IE (?)
Below some js code I am using;
$(function(e) {
//id itterator if the inputs don't have ids
if ($('input#firstname').val()) {
console.log( "ready!" );
$('.firstname-label').hide();
}
var phid=0;
$.fn.placeholder = function(){
return this.bind({
focus: function(){
$(this).parent().addClass('placeholder-focus');
},blur: function(){
$(this).parent().removeClass('placeholder-focus');
},'keyup input': function(){
$(this).parent().toggleClass('placeholder-changed', this.value!=='');
}
}).each(function(){
var $this = $(this);
//Adds an id to elements if absent
if(!this.id) this.id='ph_'+(phid++);
//Create input wrapper with label for placeholder. Also sets the for attribute to the id of the input if it exists.
$('<span class="placeholderWrap"><label class="'+this.id+'-label" for="'+this.id+'">'+$this.attr('placeholder')+'</label></span>')
.insertAfter($this)
.append($this);
//Disables default placeholder
//$this.attr('placeholder','').keyup();
});
};
console.log('set placeholders');
$('input').each(function() {
var input = $(this);
var id = $(this).attr('id');
if (!$(this).val() && $(this).attr('id') != 'photo') {
$('input#' + id).placeholder('');
console.log(id);
} else {
// do nothing
}
});
});
Thanks in advance!
I have a LOT of radio buttons on a form I'm creating.
The reason why I am using radio buttons and not check box's is because I only want to let a user select one or none.
The bad thing about a radio button though is, once selected, it can't be undone. I am trying to add the feature of clearing a group of radio box's when it's clicked for the second time.
My method that I am implementing now works if I have a group of radio buttons I want to target individually but not if I want to implement it for ALL radio button groups on the page.
When I use multiple radio button groups, it will randomly un-select a radio button when I try to select a different option.
If anyone could help me out, it would be greatly appreciated.
JSFIDDLE for only one group of radio buttons (works)
If you change to this code instead and target an individual name, it works.
$('input[name="rad"]').click(function()
JSFIDDLE for multiple groups of radio buttons (doesn't work)
I am trying to be able to target all my radio button groups at once, because there are a LOT.
$(function(){
$('input[type="radio"]').click(function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name="rad"]').data('waschecked', false);
});
});
So you just need a way to check/uncheck reliably by name groups.
Something like this should work:
$('input[type="radio"]').on('click change', function () {//on click/change
$(this).prop('checked')//if checked
? $(this).prop('checked',false).data('waschecked', false)//uncheck
: $(this).prop('checked',true).data('waschecked', true)//else check
.siblings('input[name="'+$(this).prop('name')+'"]').data('waschecked', false);//make siblings false
});
kept the .data('waschecked', ...) in case you needed to have that value, but it works without it like this:
$('input[type="radio"]').on('click change', function () {//on click/change
$(this).prop('checked')//if checked
? $(this).prop('checked',false)//uncheck
: $(this).prop('checked',true);//else check
});
made a fiddle: http://jsfiddle.net/filever10/ZUb65/
Try changing the line to use the name attribute of the clicked radio in the selector expression
$radio.siblings('input[name='+ $(this).attr('name') +']').data('waschecked', false);
You just need to clear your "waschecked" flag on the other radios of the same group.
http://jsfiddle.net/jammykam/BtLxY/15/
And just in case you do need to target using onchange: http://jsfiddle.net/jammykam/BtLxY/27/
$('input[type="radio"]').on('change', function(){
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name='+ $(this).attr('name') +']').data('waschecked', false);
});
If you are using a simple primary to secondary relationship then try this out:
$('input[type="radio"][name="main_radios"]').on('change', function(){
$('input[type="radio"][name="secondary_radios"]').prop('checked', false);
$('input[type="radio"][name="third_radios"]').prop('checked', false);
$('input[type="radio"][name="fourth_radios"]').prop('checked', false);
// combine it all into one call if you really feel like it
$('input[type="radio"][name="secondary_radios"], input[type="radio"][name="third_radios"], input[type="radio"][name="fourth_radios"]').prop('checked', false);
});
Uncheck all radios that are not "this" name
// Listen for ANY radio to be changed
$('input[type="radio"]').on('change', function(){
// remember name of selected radio
var checked_name = $(this).attr('name');
// target only radios that are not "this" name and uncheck them
$('input[type="radio"]').filter(function(){
if($(this).attr('name') != checked_name){
return true;
}
else{
return false;
}
}).prop('checked', false);
});
I've seen many check/uncheck all checkboxes scripts. But far most does not respect that if I toggled all checkboxes using the "checked all"-checkbox and then uncheck a single one in the list, the "checked all" checkbox is still checked.
Is there an elegant way of handling this case?
$('#checkAll').click(function() {
if(this.checked) {
$('input:checkbox').attr('checked', true);
}
else {
$('input:checkbox').removeAttr('checked');
}
});
$('input:checkbox:not(#checkAll)').click(function() {
if(!this.checked) {
$('#checkAll').removeAttr('checked');
}
else {
var numChecked = $('input:checkbox:checked:not(#checkAll)').length;
var numTotal = $('input:checkbox:not(#checkAll)').length;
if(numTotal == numChecked) {
$('#checkAll').attr('checked', true);
}
}
});
Demo: http://jsfiddle.net/ThiefMaster/HuM4Q/
As pointed out in the question's comment, a regular checkbox is not perfect for this. My implementation disables the "check all" box as soon as one checkbox is unchecked. So, to uncheck all still-checked checkboxes you'll have to click twice (first to re-check the unchecked ones and then to uncheck all other ones).
However, with a tri-state checkbox this might still be necessary as the state order might be unchecked->indefinite->checked->unchecked, so you'd need two clicks to come from indefinite to unchecked.
Since you probably don't want to check ALL checkboxes on your page with "Check All", replace input:checkbox with e.g. .autoCheckBox or input.autoCheckBox:checkbox and give those checkboxes class="autoCheckBox".
If you want all checkboxes inside a certain form, simple use #idOfYourForm input:checkbox or form[name=nameOfYourForm] input:checkbox
You can achieve this by attaching a click handler to each of the target checkboxes, and have that handler un-check the "control" checkbox based on the collective state of those target checkboxes. So, something like this:
// Control checks/unchecks targets
$('#controlcheckbox').click( function(){
$('.targetcheckboxes').attr('checked', this.checked );
});
// Targets affect control
$('.targetcheckboxes').click( function(){
if( $('.targetcheckboxes:not(:checked)').length ){
$('#controlcheckbox').attr('checked',false);
}
});
Even better -- you could attach this logic to an enclosing container element, and watch for the event using .delegate():
$('#some_container').delegate('.targetcheckboxes','click',function(){...} );
$("#selectall").click(function(){
var checked = $("#selectall").attr("checked");
$(".selectone").attr("checked",checked);
});
For setting select all
$(".selectone").click(function(){
var net = $(".selectone").map(function(){ return jQuery(this).attr("checked");}).get();
var flg = true;
if(jQuery.inArray(false, net)){
flg= false;
}
$("#selectall").attr("checked",flg);
});
Perhaps something like this:
$('tbody input:checkbox').change(function(){
if ($(this).closest('tbody').find('input:checkbox').not(':checked').length) {
$('#checkAll')[0].checked = false;
}
});
This assumes that #checkAll is in the thead section of your table.