how can i make a button with the id #createEditListCloseBtn get disabled if a dialog box with the id #acronyms is empty?
I've tried the following:
if($("#acronyms").children("option:selected").length < 1)
{
$("#createEditListSaveBtn").addClass("state-btn-disabled")
.attr("disabled", "disabled");
}
You can use this:
$("#submit").prop("disabled", true);
setInterval(function () {
if ($("#username").val().length >= 1 && $("#password").val().length >= 1) {
$("#submit").prop("disabled", false);
} else {
$("#submit").prop("disabled", true);
}
}, 100);
It checks the values of two fields if they are equal or more than "1" and if so, it enables the submit button.
FIDDLE HERE: http://jsfiddle.net/nn8s2e8h/
If the problem is that your function only runs once when the page loads, then what you need is an event handler:
function updateDisabledStatus() {
if($("#acronyms").children("option:selected").length < 1)
{
$("#createEditListSaveBtn").addClass("state-btn-disabled")
.attr("disabled", "disabled");
} else {
$("#createEditListSaveBtn").removeClass("state-btn-disabled")
.removeAttr("disabled");
}
}
updateDisabledStatus();
$("#acronyms").on('change', updateDisabledStatus);
Unlike captain theo's answer, this doesn't waste the user's processing power checking the status 10 times a second.
Incidentally, do you really need to have a CSS class and a disabled attribute?
Related
I have a form with a series of radio items. If a user chooses a specific entry on one of the radio items (missing item) I use JQuery to add a bootstrap is-invalid class to two specific inputs on the form along with a label asking them to add detail and disable the submit button to stop them submitting the form.
$(function () {
$("input[name=optradio]:radio").click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
}
});
});
I would like to add further checks to make sure the user updates the two inputs (ones a textarea) before I re-enable the submit button.
I know I can use the following to check for input changes
$("textarea[name=sentTo]").on("input", function(){
$('textarea[name=sentTo]').removeClass('is-invalid');
});
This works fine. However I am at a loss how to integrate it all together:
So basically user selects the radio, is-invalid gets added to 2 input fields and the submit button disabled - user completes 2 fields as required and only when both fields have been updated do we then re-enable the submit button.
I am thinking I need an if statement but I can't seem to get the code right.
I tried
if `$("textarea[name=sentTo]").on("input") && $("textarea[name=dateSent]").on("input")`
but this doesnt work
Thanks to Mamum I am using the code below.
$(function () {
$('input[name=optradio]:radio').click(function () {
if ($('input[name=optradio]:checked').val() == "2") {
$('textarea[name=sentTo]').addClass('is-invalid');
$('input[name=dateSent]').addClass('is-invalid');
$('#removedMSG').text("You must update this field prior to saving");
$('#removedMSG2').text("You must update this field prior to saving");
$('#submit').prop('disabled', true);
$('#submit').addClass('btn-danger');
$('#submit').removeClass('btn-primary');
} else {
$('textarea[name=sentTo]').removeClass('is-invalid');
$('input[name=dateSent]').removeClass('is-invalid');
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
});
var sentTo = false;
var dateSent = false;
$("textarea[name=sentTo], input[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') {
sentTo = true;
$(this).removeClass('is-invalid');
}
if($(this).attr('name') == 'dateSent') {
dateSent = true;
$(this).removeClass('is-invalid');
}
if(sentTo && dateSent){
$('#submit').prop('disabled', false);
$('#submit').addClass('btn-primary');
$('#submit').removeClass('btn-danger');
}
});
You can pass multiple selector separated by comma and use this keyword to refer the current element inside the event handler function:
var sentTo = dateSent = false;
$("textarea[name=sentTo], textarea[name=dateSent]").on("input", function(){
if($(this).attr('name') == 'sentTo') sentTo = true; //true for sentTo
if($(this).attr('name') == 'dateSent') dateSent = true;//true for dateSent
if(sentTo && dateSent){ // if both are true
$(this).removeClass('is-invalid');
sentTo = dateSent = false;
}
});
I have a form which consists of some elements such as a select-input and a checkbox.
The submit-button is disabled and I want to enable the button only if two conditions are fulfilled. An initial version works well, but only if clicking on the checkbox is the last step. But it should be a function that reacts on both, clicks/changes in the select and the checkbox.
The following code is working but with the problem explained above.
$('#toscheck').click(function() {
if ($(this).is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
The following solution doesn't work:
$('document').ready(function() {
if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
But how can I solve this? What I have found on SO wasn't really helpful.
Again: it should work as following; if the checkbox is selected AND the selected option has a value, the button would be enabled.
Thanks in advance.
First, store you element in variables:
let $toscheck = $('#toscheck'),
$ctry = $("#ctry"),
$pjo = $('#pjo'),
$sjo = $('#sjo');
Then, create your validation function with the stored variables. Note that I replace attr and removeAttr with .prop, it is better:
function checkThings(){
if ($toscheck.is(':checked') && $ctry.val().length > 0) {
$pjo.prop('disabled', false);
$sjo.prop('disabled', false);
} else {
$pjo.prop('disabled', true);
$sjo.prop('disabled', true);
}
}
Then, bind the events:
$toscheck.add($ctry).on( 'change', checkThings );
Note that I used change on both elements since it does work with inputs and checkboxes.
Final code :
let $toscheck = $('#toscheck'),
$ctry = $("#ctry"),
$pjo = $('#pjo'),
$sjo = $('#sjo');
function checkThings(){
if ($toscheck.is(':checked') && $ctry.val().length > 0) {
$pjo.prop('disabled', false);
$sjo.prop('disabled', false);
} else {
$pjo.prop('disabled', true);
$sjo.prop('disabled', true);
}
}
$toscheck.add($ctry).on( 'change', checkThings );
$(document).ready(function() {
$('#toscheck,#ctry').change(function() {
if ($('#toscheck').is(':checked') && $("#ctry").val().length > 0) {
$('#pjo').removeAttr('disabled');
$('#sjo').removeAttr('disabled');
} else {
$('#pjo').attr('disabled', 'disabled');
$('#sjo').attr('disabled', 'disabled');
}
});
});
use this code
.change function detects change and then on call check whether your AND condition is met or not
and add #toscheck in quotes i.e. '#toscheck'
$('#toscheck,#xyz,#abc').change()
for detecting change for multiple elements
I have a button that is created on each slide in a quiz game. Radio buttons containing the answer choices are appended from an object onto each slide as you cycle through the questions. I want to require that a radio button be clicked on before you can access the nextQuestion button. You can find the .append() on line 5 of the code below (inside of the loadQuestion function). What method would be the best way to achieve the desired result? If you need more of the code, let me know.
var loadQuestion = function (){
$('.question-name').html(name + (qnum) +"/"+ total);
$('.question').html(questions[count].question);
for(var i=0; i<questions[count].options.length; i++) {
$('.inputs').append('<input type="radio" name="question" value="'+questions[count].options[i]+'">'+questions[count].options[i]+'<br>')
}
};
/*--- First Question ---*/
var name = "Question ";
var qnum = 1;
var count = 0;
var total = questions.length;
loadQuestion();
/*--- When the Next Question Button is Hit ---*/
nextQuestion.click(function() {
$('.inputs').html("");
qnum++;
count++;
if (qnum <= 4) {
loadQuestion();
} else if (qnum == 6) {
$('.question-name').html("Your Score:");
$('.question').html("You got X out of 5 questions correct!");
nextQuestion.html("Home Screen").click(function() {
location.reload();
});
} else if (qnum == 5){
loadQuestion();
$('.next-question').html("Get Score!");
}
});
$(document).ready(function () {
$('#nextButton').attr('disabled', true);//disable the button by default on page load
$("input[type=checkbox]").on("click", function () {
if (this.length > 0) {
$('#nextButton').attr('disabled', false);//enable only when the checkbox is checked
}
});
});
I hope this helps!
Security note: Anybody can remove the disabled attribute from the button tag using developer tools in the browser. Use the backend to validate the checkbox value.
There's more than one way to go about this:
"Prevent button press until radio is selected"
From a ui/ux perspective your request raises the following question: "If the user isn't supposed to click on the button until the radio is selected, why is the button available for them to press before the radio is selected?" So, let's start there.
//pseudo-code - use delegate binding '.on()' for dynamically generated elements
$('.inputs').on('click', 'input[name="question"]', function({
if ($(this).is(':checked')) {
$('#nextButton').attr('disabled', false);
} else {
$('#nextButton').attr('disabled', true);
} /*... snip ...*/
}));
Or, you could generate the nextButton after an answer is selected much in the same way that you are currently generating the radio button - just remember to use delegate event binding. This is probably the "better way" because as has already been pointed out by #zadd, the disabled property can be circumvented.
Without reinventing the wheel, you could also just check to see if there's a radio selected when the button is pressed.
// pseudo-code again
nextQuestion.click(function() {
if($('input[name="question"]:checked').length > 0){
// checked!!! go do stuff!!!
} else {
// not checked! i should probably throw an alert or something...
alert('please answer the question before proceeding...');
}
});
With the help of answers I found here, I try to disable submit button and send an alert message when clicked on it until there's not at least 2 checkboxes checked.
What I am doing wrong ?
var selected = $('#frmCompare :checkbox:checked').length;
function verifCompare() {
if (selected >= 2) {
//good
$('#frmCompare').submit();
} else {
//bad
alert('Veuillez selectionner au moins 2 produits à comparer...');
return false
}
}
$(document).ready(function () {
$('#btnCompare').attr('disabled', 'disabled');
$('#frmCompare :checkbox').change(function () {
//alert(selected);
if (selected >= 2) {
$('#btnCompare').attr('enabled');
}
});
});
At this point, only alert message works.
Fiddle
EDIT : added fiddle
There is no enabled attribute in HTML.
$('#btnCompare').prop('disabled', selected < 2);
You also need to recalculate the value of selected at every change, you can't just go with what it was set to at page load.
You initialize the count of checked checkboxes just once, when your script is first parsed. The count will not be recomputed later. This line:
var selected = $('#frmCompare :checkbox:checked').length;
should be inside the verification function, not outside.
You should change your code as
$('#frmCompare :checkbox').change(function(){
//update selected variable
selected = $('#frmCompare :checkbox:checked').length
if (selected >= 2) {
$('#btnCompare').attr('enabled');
}
});
What I want to do is take an input for a zipcode and in jQuery if input#zip has 5 characters then function. Also same for a list box when the user chooses one of the choices, might be simpler?
$('#zip-input').keyup(function(){
if($(this).val().length == 5) {
//do your stuff here
}
})
For your zip scenario:
$("#zip").keypress(function() {
if ($(this).val() && $(this).val().length == 5) {
someFunction($(this).val());
}
});
For your listbox scenario:
$("#listbox").change(function() {
if ($(this).val()) {
someFunction($(this).val());
}
});
You might want to use a keyup event handler for instance.
$('input').bind('keyup', function(){
if($(this).val().length >= 5){
alert('5 characters');
return false;
}
});
Perhaps use the .change(). Each time change is fired get the length of the input and, if its 5 or more, run your code.