How to enable submit button if at least two checkboxes are checked? - javascript

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');
}
});

Related

Jquery - Identify if radio button value has not changed

Is it possible to identify if the value of radio button has not changed?
Currently I am trying to change the confirmation message of submit button on button changed, and do not want any message if the value has not changed. I have something like this now:
$('input[type="radio"]').change(function() {
var selected = $('input:checked[type="radio"]').val();
if(selected == 'true') {
$("#submit_button").data("confirm", "foo");
} else if(selected == 'false') {
$('#fee').hide();
$("#submit_button").data("confirm", "bar");
}
This will change confirm message to foo if button selected is true, and bar if button selected is false. However, what if I want to return nothing (no message), if radio button by default is true, and selected is true?
You can start a variable outside the event:
var radioChanged = 0;
And, in your event increase it:
$(':radio').change(function() {
radioChanged += 1;
// your code ...
});
Then, later on:
if (radioChanged > 0) {
alert('Change function occurred ' + radioChanged + ' times.');
} else {
alert('Radio button not changed.');
}
As i understand your expected behaviour, check if any radio has no more its default checked value:
$('form').on('submit', function() {
var anyRadioChanged = !!$(this).find('input[type="radio"]').filter(function() {
return $(this).is(':checked') != this.defaultChecked;
}).length; // '!!' to get boolean but it doesn't really matter here
if(anyRadioChanged) {
// show message(???)
}
})
you can hide message element just adding display: none to it or use jquery hide method
$('#someElementId').hide();
or
$('#someElementId').css("display","none")

prevent button press until radio button selected

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...');
}
});

Preventing next tab if current tab have empty field

I have a form having few questions set, each displayed at a time (like a slide). I want to prevent next set if current set has an empty field. Below is my script that navigates through each questions set. Any help would be highly appreciated.
$(document).ready(function() {
var $questions = $('#questions .question');
var currentQuestion = $('#questions .question.active').index();
$('#next').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion++;
if (currentQuestion == $questions.length - 1) {
$('#next').css('display', 'none');
$('#submit').css('display', 'inline');
}else{
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
}
$('#back').css('display', 'inline');
$($questions[currentQuestion]).slideDown();
});
});
$('#back').click(function() {
$($questions[currentQuestion]).slideUp(function() {
currentQuestion--;
if (currentQuestion == 0) {
$('#back').css('display', 'none');
} else {
$('#back').css('display', 'inline');
}
$('#next').css('display', 'inline');
$('#submit').css('display', 'none');
$($questions[currentQuestion]).slideDown();
});
});
});
Here is my JSFiddle
I came across your question and decided to fork your fiddle.
You should make a function that checks your conditions before continuing on to the next tab.
In your case, the conditions would be: All fields must be filled
I've added this function that checks the active section and returns true / false, in order to continue.
function validateFormSection() {
var valid = true; //As long as it's true, we may continue
var section = $('.question.active'); //Find the active section
var inputs = section.find('input'); //Get all its inputs
inputs.each(function(index, el) {
if ( $(el).val() == "" ) {
valid = false;
}
});
return valid;
}
JSFiddle here
On the third page, the form would submit whether all fields are empty or not.
You can prevent this by hooking onto the submit function and checking for empty fields.
If they're empty, we use e.preventDefault(); to keep it from submitting.
If they're filled, we simply submit by doing $('form').submit();
$('form').submit( function (e) { //Hook into the submit event
var valid = validateFormSection(); //Check if our fields are filled
if ( valid ) { //They are filled?
$('form').submit(); //Very well, let's submit!
} else {
e.preventDefault(); //If not, prevent the (default) submit behaviour
}
});
The fiddle has been edited to reflect these changes.
You could use if(!$('.question').eq(currentQuestion).find('input').filter(function(){return this.value==""}).length) to check if there are empty fields. Fiddle: http://jsfiddle.net/ilpo/cuqerfxr/1/
$('.question') selects all the questions
.eq(currentQuestion) selects the question you're currently at
.find('input') selects all the input fields inside the current question
.filter(function(){return this.value==""}) selects only empty input fields
.length counts the amount of matches, e.g. amount of empty inputs
if(number) returns true with a positive value, e.g. if there were any empty inputs
! in front of it all inverts it, returning true if there are no empty fields

jQuery problems with function

What i'm trying to do here is if the selection is equal to value 10 the click function to be available only if selection is equal to 10. But when i change to other ex. category with different value the radio click function is still available. ?
I have 6 radio boxes with value 1,2,3,4,5,6 so what i want to do if value == 4 to slidedown another div while i'm in category with value 10.(selection).
How can i fix this problem ? Here is my sample code.
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
if(selection == '10'){
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown'+selection).slideUp();
} else {
$('#slidedown'+selection).slideDown();
}
});
});
Thanks, any help will be appreciated.
EDIT : I want to slideUp the currect div which is slided down by the category value if radio box with value 4 is checked.
You should have another selection var inside the click callback:
$('#category').on('change', function () {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
});
$("input:radio[name='checkbox']").click(function() {
var selection = $('#category').val(); //This does the trick
var radio = $(this).val();
if(radio == '4' && selection == '10') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Also, callbacks must be separated for not binding a new listener each time
Hope this helps. Cheers
Use the disabled property to enable and disable the radio buttons.
$('#category').change(function() {
var selection = $(this).val();
$('#slidedown'+selection).slideDown(200);
$('input:radio[name=checkbox]').prop('disabled', selection != '10');
});
$("input:radio[name='checkbox']").click(function() {
var radio = $(this).val();
if(radio == '4') {
$('#slidedown_another').slideUp();
} else {
$('#slidedown_another').slideDown();
}
});
Your code is adding a handler when the select has the correct value, but it never removes the handler when the select changes to a different value. Also, every time they select 10 it was adding another handler, so the handler would then run multiple times.

Detect HTML Option Value Using jQuery [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to get the text of the selected option of a select using jquery?
I have the following script:
<select id = "people">
<option value = "0">Choose</option>
<option value = "1">John</option>
<option value = "2">David</option>
</select>
How Can I use jQuery to detect the value of the option that is currently selected?
i.e. (pseudo-ish code)
if(people.option.text == "Choose"){
//Alert - Please make a selection
}else{
//Valid - do something
}
EDIT: code not working
echo("<script>");
echo("$(document).ready(function(){");
echo("$(\"#go\").click(function(e){");
echo("var selText = $(\"#people option:selected\").text();");
echo("if(selText == \"Choose\"){");
echo("}else{");
echo("window.location.href = \"viewprofile.php\";");
echo("}");
echo("});");
echo("});");
echo("</script>");
It constantly triggers the else statement and navigates away...
EDIT: Got it working -> changed .text() and val()
From your example looks like you want to get the selected text, not value.
So have this:
var selText = $("#people option:selected").text();
if(selText == "Choose") {
//Alert - Please make a selection
} else {
//Valid - do something
}
To get selected value and check it, have such code:
var selValue = parseInt($("#people").val(), 10);
if (selValue == 0) {
//Alert - Please make a selection
} else {
//Valid - do something
}
if (jQuery('#people option:selected').val()=="Choose"){
}
else{
}
Check the value that is selected using val, then take the appropriate action. Shown below in a form submission handler to prevent form submission. You might also want to consider using the validate plugin for this particular case, making the field required, and having the default option have no value.
$(function() {
$('form').submit( function() {
var selectedPerson = $('#people').val();
if (!selectedPerson || selectedPerson == '0') {
alert('you must choose an option for people');
return false;
}
// continue form validation and submission
});
});
To get the value of the selected <option>, use:
$('select').val()
To get the HTML content of the selected <option>, use:
$'select :selected').html()
And to check if a certain <option> is selected, use:
if ($('option').is(':selected')) ...
How about this:
$("select option:selected").each(function () {
if($(this).text()=="Choose") ...
else ...
});
if ($('#people [value!=0]:selected').length > 0){
//selected
} else {
//not selected
}

Categories

Resources