jQuery working with dropdown but not radio button - javascript

I need to rewrite this section of a jQuery script so that it is triggered by selection of a radio button and not a dropdown.
var check_engraving = $('#attrib-2');
if (check_engraving.val() == 4) {
enable_engraving = true;
$('#individual_engraving_wrapper').show();
The new radio button that needs to trigger it is:
<span class="EngraveAttribute4"><input type="radio" name="id[2]" value="540" id="attrib-2-540" /><label class="attribsRadioButton zero" for="attrib-2-540">I would like different engraving on each of these items</label><br /></span>
It's obviously no good changing it to
var check_engraving = $('#attrib-2-540');
if (check_engraving.val() == 540) {
as the value is always 540 regardless of whether or not it is selected.
I tried to use
$('input:radio[name="id[2]"]').change(function () {
if ($(this).val() == '540') {
enable_engraving = true;
$('#individual_engraving_wrapper').show();
}
});
which I thought was working ok, but if I update the quantity I have to deselect then reselect the radio button for engraving to be true. The old dropdown system stayed as true when the quantity was updated.
I'm sure this can be done, but I'm stumped on it. Any suggestions appreciated.

try this
$('input[type=radio][name="id[2]"]').change(function () {
if ($(this).val() == '540') {
enable_engraving = true;
$('#individual_engraving_wrapper').show();
}
});

Related

box checks even though an alert is thrown?

I would like to have it set up. So when it has gone above a certain value an alert is raised to inform the user has ticked too many boxes. The alert appears successfully but the checkbox in question keeps ticked. I have used this function before but it is not working this time. I don't know why. Thanks in advance for any help is given.
function cannotDoThreeATTandAwareness() {
var i = 0;
$('.ATT, #aware').each(function() {
if ($(this).is(':not(:visible)')) {
i += 3
}
});
$('.ATT').each(function() {
if ($(this).is(':checked')) {
i += 3
}
});
$('.awareness').each(function() {
if ($(this).is(':checked')) {
i += 1
}
});
if (i > 9) {
alert('You cannot select this paper as you have already selected your Core 2 paper');
};
return i == 10;
}
onclick =" if(cannotDoThreeATTandAwareness()){this.checked=false};"
Simply return the result you want inside the click event too.
function cannotDoThreeATTandAwareness() {
var i = 0;
// used 'true' to always make it fail, for the sake of example
if (true || i > 9) {
alert('You cannot select this paper as you have already selected your Core 2 paper');
};
return i > 9;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>
<input type="checkbox" onclick="return cannotDoThreeATTandAwareness()">
Click me
</label>
Another option would be to add an argument to the function, let's say e, and where you want to block the change, you can use e.preventDefault(). In order for this to work, you'll need to pass the event down to the function, here's a snippet:
function cannotDoThreeATTandAwareness(e) {
...
if (true || i > 9) {
e.preventDefault()
...
};
}
<input type="checkbox" onclick="cannotDoThreeATTandAwareness(event)">

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

How to validate textarea and checkboxes which are generated dynamically

This one seems really common question in StackOverflow. However, I am having difficulty in validating these textarea (Not to left blank) and checkboxes(At least one should be checked). I tried several validation Javascripts and frameworks but in vain.
I have textarea named "case_title0[]" whose will increase the number "0" to "1","2" and so on when user clicks "Add More" button. I want to validate at the point when user clicks the "Add More" button.
Secondly, I want the checkbox (name="editioncheck'+caseNum+'[]") which is dynamic as well to restrict user to leave it blank. The checkbox looks like "editioncheck0[]", "editioncheck1[]" and so on. It needs to be checked at least once to proceed to next "Add More" button. Until then "Add More" button should remain inactive.
So, I want these two type of validation in my form ie. textarea and checkbox.
Which is the simplest framework or custom code to use here?
I don't want fancy display as just alert() box should work in this regard.
Add common class to all textareas and common class to all checkboxes and perform validation.
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<textarea class="t"></textarea>
<input type="checkbox" class="c">
function validate() {
var err = false;
$('.t').each(function(){
if($(this).text().length < 1) {
err = true;
return false;
}
});
if(!err) {
/* code to validate checkboxes like above */
}
return !err;
}
Finally, I have figured out the solution and I am going to post it here. As there is no exactly similar solution to my problem I had to code from scratch. While doing so lot of online resources helped me a lot.
To validate textarea on the fly (dynamic generate of text area when user clicks "Add More" button), here is solution I applied:
var csn='case_title'+caseno; //here "caseno" is incremental number to uniquely identify elements
var csum='case_summary'+caseno;
var caset=document.getElementById(csn).value;
var casesum=document.getElementById(csum).value;
if (caset == null || caset == "") {
alert("Executive Summary must be filled out");
caseNum --;
return false;
}
if (casesum == null || casesum == "") {
alert("Summaries with links must be filled out");
caseNum --;
return false;
Next, to validate the checkboxes I did as follows:
var edval='editioncheck'+caseno;
var checkBoxes=document.getElementsByClassName(edval);
var isChecked = false;
for (var i = 0; i < checkBoxes.length; i++) {
if ( checkBoxes[i].checked ) {
isChecked = true;
};
};
if ( isChecked ) {
//alert( 'At least one checkbox checked!' );
} else {
alert( 'Select at least one edition!' );
caseNum --;
return false;
}
The solution seems similar to the concept of fr34k, so thanks a lot. However, I found this online here http://jsfiddle.net/qyE97/
So, every time user click "Add More" button this script is executed and validates for the textarea and checkboxes.

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.

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

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

Categories

Resources