I I am displaying and disabling fields based on user roles. I determine the user role through a basic radio button of two options admin and user. The admin has the ability to disable all textbox fields and button clicks. The problem: when the admin disables the fields, their also locked out from being able to type in the textbox or drag a div. How would it be possible for the admin to disable the fields only for the user?
If I click on radio button admin and then click button to disable fields, the admin can still type in text box and drag div but once I switch to radio button user I want to disable all fields. Once the admin enables fields then switching back to radio button user can also type in text box and drag divs.
jQuery:
/** Determine user role**/
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="admin"){
$("#adminControls").show();
}
if($(this).attr("value")=="user"){
$("#adminControls").hide();
}
});
/** Disable fields **/
var clickCount = 0;
$('#adminControl1').click(function (e) {
clickCount ++;
console.log(clickCount);
if (clickCount % 2 == 1){
$("#appendText").prop( "disabled", true );
$("#divText").prop( "disabled", true );
$('.draggable').draggable( "disable" );
$("#adminControl1").val("Enable All");
} else {
$("#appendText").prop( "disabled", false );
$("#divText").prop( "disabled", false );
$('.draggable').draggable( "enable" );
$("#adminControl1").val("Disable All");
}
});
HTML:
<h3>User Role:</h3>
<div id="roles">
<label><input type="radio" name="userRole" value="admin"> Admin</label>
<label><input type="radio" name="userRole" value="user" checked="checked"> User</label>
</div>
<br/>
<br/>
<div id="adminControls">
<h3>Admin Controls</h3>
<input type="button" id="adminControl1" value="Disable All" />
</div>
<br/>
<textarea rows="4" cols="50" id="divText" placeholder="Enter Text Here!"></textarea>
<input type="button" id="appendText" value="Add Div with Text" /><br/>
<div>
<div class="middle-side empty">
<h2 class="placeholder-title hidden">Place Inside Here</h2>
</div>
</div>
* Edit *
var clickCount = 0;
$('input[type="radio"]').click(function(){
clickCount ++;
if($(this).attr("value")=="admin"){
$("#adminControls").show();
$('#adminControl1').click(function (e) {
if (clickCount % 2 == 1){
$("#appendText").prop( "disabled", true );
$("#divText").prop( "disabled", true );
$('.draggable').draggable( "disable" );
$("#adminControl1").val("Enable All");
}
});
}
if($(this).attr("value")=="user"){
$("#adminControls").hide();
$("#appendText").prop( "disabled", false );
$("#divText").prop( "disabled", false );
$('.draggable').draggable( "enable" );
$("#adminControl1").val("Disable All");
}
});
Don't change the event binding inside another event binding. Since you haven't removed the old event binding, you end up running multiple handlers for the same event. You should put the click handler for the enable/disable button at top level.
For a binary option, use a boolean value, not a counter, which you can toggle with disable = !disable. You should also toggle it in the click handler for the enable/disable button, not the radio button.
var disable = true;
$('#adminControl1').click(function (e) {
$("#appendText, #divText").prop("disabled", disable);
$('.draggable').draggable(disable ? "disable" : "enable");
$("#adminControl1").val(disable ? "Enable All" : "Disable All");
disable = !disable;
});
Clicking on the radio button shouldn't enable or disable anything, it should just hide or show the admin controls depending on which button was clicked. Since the two choices are mutually exclusive, there's no need to test for each value, so I've changed it to use toggle, with an argument that specifies the desired state.
$('input[type="radio"]').click(function () {
$("#adminControls").toggle($(this).attr("value") == "admin");
});
Updated fiddle
UPDATE:
In this version, the enable/disable button just toggles the disable variable and the label of the button, it doesn't actually enable or disable anything. The radio button click handler checks the value of the variable when it's switching into user mode, and enables/disables the controls accordingly. When it's switching into admin mode, it enables everything.
var disable = false;
$('#adminControl1').click(function (e) {
disable = !disable;
$("#adminControl1").val(disable ? "Enable All" : "Disable All");
});
$('input[type="radio"]').click(function () {
if ($(this).attr("value") == "admin") {
var tempdisable = false; // Everything is enabled for admin
var adminmode = true;
} else {
tempdisable = disable; // Use the setting that admin assigned
adminmode = false;
}
$("#adminControls").toggle(adminmode);
$("#appendText, #divText").prop("disabled", tempdisable);
$('.draggable').draggable(tempdisable ? "disable" : "enable");
});
FIDDLE
Related
I'm currently working on a photography store website. Customers will be allowed to view photosets ranging from 100-500 images on a page. I want those customers to be able to click a "Select All" button (or other element) that checks all the checkboxes on the page. I am currently using jQuery to successfully accomplish this "Select All" feature after researching here on Stack Overflow.
Currently, the code that I am working with puts a checkbox on each image in the photoset. If the user clicks the checkbox, it triggers a custom event. However, I want the checkbox state of being checked (or the change from being unchecked to checked) to trigger the event, not the click. If the click triggers the event, the Select All feature I have using jQuery fails to work, since jQuery isn't "clicking" each of the checkboxes on the page, only changing the checkbox to selected. This means that the custom event doesn't load.
The code that currently works to trigger the event I need by clicking (which I do not want to do) the checkbox is:
$('.select-product').on('click', this.QuickOrder.loadProduct);
The code I am trying to develop isn't working, but it goes something like:
$('.select-product').change(function(){
var isChecked = $(this).is(':checked');
if(isChecked) {
this.QuickOrder.loadProduct;
}
});
I've used the .change() function after researching and finding that the change function registers the change in the condition of the checkbox. When this condition changes to true, I want QuickOrder.loadProduct to trigger. After that, everything should work.
Here is my jQuery "Select All" script for reference:
$(document).ready(function() {
$("#select_all").change(function(){
if(this.checked){
$(".select-product").each(function(){
this.checked=true;
})
}else{
$(".select-product").each(function(){
this.checked=false;
})
}
});
$(".select-product").click(function () {
if (!$(this).is(":checked")){
$("#select_all").prop("checked", false);
}else{
var flag = 0;
$(".select-product").each(function(){
if(!this.checked)
flag=1;
})
if(flag == 0){ $("#select_all").prop("checked", true);}
}
});
});
Any ideas on how to make this happen? Thank you!
As explained in Why isn't my checkbox change event triggered?:
The change event does not fire when you programmatically change the value of a check box.
Below I give two solutions (the first is from the aforementioned link):
1: Explicitly trigger the change event after changing the checkbox setting.
this.checked = true;
$(this).trigger('change');
2: Just programmatically delegate to the click event.
$(this).trigger('click');
Demo:
window.loadProduct = function(id) { alert('loadProduct() called on #'+id+'.'); };
// propagate select-all checkbox changes to all individual checkboxes
$("#select_all").change(function() {
if (this.checked) {
$(".select-product").each(function() {
// original code
//this.checked = true;
// solution #1: explicitly force a change event
this.checked = true;
$(this).trigger('change');
// solution #2: trigger click
//$(this).trigger('click');
});
} else {
$(".select-product").each(function() {
this.checked = false;
});
} // end if
});
// propagate individual checkbox changes back to the select-all checkbox
$(".select-product").click(function() {
if (!$(this).is(":checked")) {
$("#select_all").prop("checked", false );
} else {
var flag = 0;
$(".select-product").each(function() {
if (!this.checked)
flag = 1;
});
if (flag == 0) {
$("#select_all").prop("checked", true );
} // end if
} // end if
});
// call loadProduct() for any change of an individual checkbox
$('.select-product').change(function() {
var isChecked = $(this).is(':checked');
if (isChecked) {
loadProduct(this.id);
} // end if
});
.select_container {
margin-bottom:8px;
}
.img_container {
display:flex;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="select_container">
<input id="select_all" type="checkbox"/>
</div>
<div class="img_container">
<div>
<div><img src="https://www.gravatar.com/avatar/4fa45261dec56004145c653832504920?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check1" class="select-product" type="checkbox"/>
</div>
<div>
<div><img src="https://www.gravatar.com/avatar/fc03f6eed7d4d5e3233c5dde9f48480d?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check2" class="select-product" type="checkbox"/>
</div>
<div>
<div><img src="https://www.gravatar.com/avatar/fd882c2b5e410936a4a607b2e87465d9?s=128&d=identicon&r=PG&f=1"/></div>
<input id="check3" class="select-product" type="checkbox"/>
</div>
</div>
I want my form to meet a set of criterias before the submit button gets enabled, my form is in this order:
Text field, value has to be over 150
Set of radio selects, 1 has to be selected
TOS box, has to be checked
So far I have this:
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
Do I have to add this to everything I'm checking, for example keyup on the textfield, change on the select and checkbox and set true in variables that those fields are "OK" or how do I do it ?
You need to create a custom validate function, which you have to run onchange of your text field, and on click of your radio and checkbox click event.
Following psudo code might help you.
var textFieldValidationPassed = false;
function validateFormFields() {
//First checks if text field length is not less then 150.
// then check if one of the radio button is selected.
// then check for TOS box checked state;
if (textFieldValidationPassed && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
// enable submit button;
}
}
$('input:radio[name="radioset1"]', 'input.checkbox_check').click(function() {
validateFormFields();
})
$('#amount').keyup(function(){
if($(this).val().length > 149) {
textFieldValidationPassed =true;
validateFormFields();
}
})
it is a workaround but will work, make submit button initially...
$(":submit").on('focus',Validate);
function Validate(){
if ((parseInt($('#amount').val(), 10) > 149) && $('input:radio[name="radioset1"]').is(':checked') && ($('input.checkbox_check').is(':checked')))
{
// Enable Button here
}
else
{
//Disable button
}
}
You can just add click, change events at once like this
$("input").on("change, click", function(){
});
Write your logic within this.
Also you've checkbox validation wrong. Check box will be clicked.
$('input.checkbox_check').prop('checked')
Here is the complete code
$(function(){
$("input").on("change, click", function(){
if ((parseInt($('#UserName').val(), 10) > 149) && $('input:radio[name="gender"]').is(':checked') && $("#remember").prop('checked'))
{
$("#submit").removeAttr("disabled");
}
else{
$("#submit").attr("disabled", "disabled");
}
});
});
WORKING FIDDLE
You can use jQuery.validate. You can define custom validation methods too.
http://jqueryvalidation.org
You can use HTML5 validation. For example:
<input type="checkbox" required name="checkbox1" />
<input type="text" min="150" name="input1" />
You can see another example here http://www.w3schools.com/html/html5_form_attributes.asp
You can call it at textbox, radiobutton and checkbox onchange events.
EDIT:
$(document).ready(function () {
$("input").change(function () {
//call function.
});
});
I have the below javascript function which displays updated values after a UI slider selection on the click of a button. I have disabled the button across pages so that the button will not be clicked again.
$(function () {
var disabled = localStorage.getItem("updateDisabled");
if (disabled) $('#update').attr('disabled', disabled);
});
$("#update").click(function (){
this.disabled = true;
localStorage.setItem("updateDisabled", true);
$("#kwBody > tr").each(function() {
var $cells = $(this).children("td");
var found=false,count=0,currentCell;
for (var i=0;i<masterData.length;i++) {
currentCell=$cells.eq(i+1);
found = parseInt(currentCell.text(),10) >=masterData[i];
currentCell.toggleClass("found",found); //add or remove class to highlight
count+=found;
}
window.console && console.log(masterData,count);
$(this).toggle(count==masterData.length); // show if all cells >
});
In my page, I am trying to include another button like "Back" which when clicked on, will reload the initial page itself.
<form method="post" action"willdoit.php">
<input type = "button" value = "Back"></input>
</form>
However if I click on the button nothing happens.
<input type ="submit" value ="Back" />
This will submit your form. Your button you have will only be a button and do nothing.
Change the type to input type ="submit"
I have this markup :
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
<div class='A'>
<input type='radio' name='B' class='B' />
</div>
The desired functionality is to select the radio either by clicking parent div or the radio input itself and if the radio is already checked then click on parent will have no effect i.e return false.
I have made it to change on click of parent, but when i click on the radio button , nothing happens.
What's wrong with my approach ?
jQuery :
$('input:radio').closest('div').on('click', function (e) {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
console.log("Clicked : " + $(this).attr('class'));
});
Fiddle : http://jsfiddle.net/pSSc9/1/
May I suggest using label elements instead of divs? You'll get the same behavior and won't need javascript at all. CSS will take care of the appearance. I made that simple change in your fiddle, and it worked fine.
http://jsfiddle.net/jeffman/WQEDv/2/
$('.A').on('click', function (e) {
if ($(e.target).is('.B')) {
e.stopPropagation();
// So that event does not bubble when radio is selected
} else {
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
}
console.log("Clicked : " + $(e.target).attr('class'));
});
The problem with your code was you were returning false when the checkbox is clicked. So you were indirectly doing event.preventDefault() and event.stopPropagation() by doing return false;
You explicitly need to set the checked property to true only when clicked on the div. But when you click on the radio it performs the default action. So you need to stop the propagation of the event.
Check Fiddle
DEMO
e.preventDefault(); disables the radio button click event
$('input:radio').closest('div').on('click', function (e) {
$('input:radio', this).prop('checked', true);
});
The click event from the radio button is bubbling up to the div, so the callback gets triggered in both cases. The problem is that you're preventing the default action which, in the case of the radio button, is it becoming checked.
What you can do is add a condition that exits the callback if the element clicked was the radio button:
$('input:radio').closest('div').on('click', function (e) {
if ($(e.target).is('input')) {
return;
}
if ($('input:radio', this).prop('checked') === true) {
console.log("returning false");
return false;
}
$('input:radio', this).prop('checked', true);
console.log("Clicked : " + $(this).attr('class'));
});
Working example
I have multiple checkboxes and a submit button that is initially disabled. When checking a box the button is enabled and when unchecking, the button is disabled again.
If have multiple checkboxes selected but uncheck one, the button becomes disabled even though I have selected other checkboxes. How can I fix this issue?
<script type="text/javascript">
$(function() {
$(".checkbox").click(function() {
$(".delete").attr("disabled", !this.checked);
});
});
</script>
HTML
<input type="checkbox" name="msg[]" value="32" class="checkbox" />
<input type="checkbox" name="msg[]" value="44" class="checkbox" />
<input type="checkbox" name="msg[]" value="26" class="checkbox" />
<button type="submit" class="delete" disabled="disabled">Delete</button>
$(function() {
$(".checkbox").click(function(){
$('.delete').prop('disabled',$('input.checkbox:checked').length == 0);
});
});
Demo: http://jsfiddle.net/AlienWebguy/3U364/
Implement a counter to track how many are checked, rather than just disabling the button. Add 1 every time a box is checked, and subtract 1 every time a box is unchecked. Once the counter hits 0, disable the button. When it changes to 1, enable the button (if it changes to any higher number it will have already been enabled, so you don't need to enable it every time). Sample:
<script type="text/javascript">
var boxcounter;
$(function() {
boxcounter = 0;
$(".checkbox").click(function() {
if(this.checked) {
counter++;
if(counter == 1){
$(".delete").attr("disabled", "");
}
} else {
counter--;
if(counter == 0){
$(".delete").attr("disabled", "disabled");
}
}
}
}
</script>
Try this where I am basically checking if all the checkboxes are not checked then disable the button.
$(function() {
$(".checkbox").click(function() {
$(".delete").attr("disabled", !$(".checkbox:checked").length);
});
});
You need to check the state of the other boxes each time 1 box is toggled.
You can build an array of every checkbox.
Then, loop through testing for checked, and exit the loop on checked (this is what you care about).
If you reach the end of the loop and checked for all was false, then disable the button.
This will prevent one uncheck from disabling the button.
You're currently only checking "this" checkbox rather than all.
This code is Actually works without any error.
var boxcounter;
$(function() {
let boxcounter = 0;
$(".cgv-checkbox").click(function() {
if(this.checked) {
console.log('checked');
boxcounter++;
if(boxcounter == 3){
$("#register_form_Register").removeAttr("disabled");
}
} else {
boxcounter--;
if(boxcounter < 3){
$("#register_form_Register").attr("disabled", "disabled");
}
}
});
});
This will work with multiple checkboxes as well.