Odd behavior when detecting checkbox change with javascript - javascript

I have the following HTML code:
<label class="radio">
<input type="radio" name="msgTo" value="optiona" checked="checked">
<i></i>Option A</label>
<label class="radio">
<input type="radio" name="msgTo" value="optionb">
<i></i>Option B</label>
<label class="radio">
<input type="radio" name="msgTo" value="optionc">
<i></i>Option C</label>
<label class="radio">
<input type="radio" name="msgTo" value="optiond">
<i></i>Option D</label>
<label class="radio">
<input type="radio" name="msgTo" value="optione">
<i></i>Option E</label>
and I'm trying to do stuff depending on which option is checked with this code:
$('input[name="msgTo"]:checked').on('change', function() {
alert('option changed');
if ($('input[name="msgTo"]:checked').val() == 'optionc') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
} else if ($('input[name="msgTo"]:checked').val() == 'optiond') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').show();
$('.my_select_box').trigger('chosen:updated');
} else if ($('input[name="msgTo"]:checked').val() == 'optione') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
} else if ($('input[name="msgTo"]:checked').val() == 'optionb') {
$('#outsideMsgWarning').hide();
$('#destEspecificos').show();
$('#locEspecificas').hide();
$('.my_select_box').trigger('chosen:updated');
} else {
$('#outsideMsgWarning').hide();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
$('.my_select_box').trigger('chosen:updated');
}
});
When I select the 2nd, 3rd, 4th or 5th option, nothing happens (should hide/show some options) but when I go back to the first one (which would be the ELSE in javascript), the alert is shown. The alert is just for testing purposes.
I've also tried adding brackets [] to the checkboxes names but got the same result.
Why doesn't javascript detect every change?
Thanks in advance!!!

Your initial selector that sets up the event binding is looking only for radio buttons that are checked:
$('input[name="msgTo"]:checked').on('change', function() {
Since the first radio button is pre-checked by default, only that one will be affected.
Change the line to:
$('input[name="msgTo"]').on('change', function() {
So that all radio buttons in the group get bound to the event handler.

Change the onchange event like this $('input[name="msgTo"]').on('change', function() .you should remove the :checked
$('input[name="msgTo"]').on('change', function() {
if($(this).is(':checked')){
alert('option changed');
}
if ($('input[name="msgTo"]:checked').val() == 'optionc') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
} else if ($('input[name="msgTo"]:checked').val() == 'optiond') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').show();
$('.my_select_box').trigger('chosen:updated');
} else if ($('input[name="msgTo"]:checked').val() == 'optione') {
$('#outsideMsgWarning').show();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
} else if ($('input[name="msgTo"]:checked').val() == 'optionb') {
$('#outsideMsgWarning').hide();
$('#destEspecificos').show();
$('#locEspecificas').hide();
$('.my_select_box').trigger('chosen:updated');
} else {
$('#outsideMsgWarning').hide();
$('#destEspecificos').hide();
$('#locEspecificas').hide();
$('.my_select_box').trigger('chosen:updated');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="radio">
<input type="radio" name="msgTo" value="optiona" checked="checked">
<i></i>Option A</label>
<label class="radio">
<input type="radio" name="msgTo" value="optionb">
<i></i>Option B</label>
<label class="radio">
<input type="radio" name="msgTo" value="optionc">
<i></i>Option C</label>
<label class="radio">
<input type="radio" name="msgTo" value="optiond">
<i></i>Option D</label>
<label class="radio">
<input type="radio" name="msgTo" value="optione">
<i></i>Option E</label>

You are selecting the checked input.
$('input[name="msgTo"]:checked')
Try this selector instead:
$('input[name="msgTo"]')

Related

Disable a specific checkbox using Javascript

I would like to request assistance on how can I disable a specific checkbox.
Scenario:
If I clicked the 'Yes to all' checkbox - the other checkbox will be disabled (Q1 to Q4)
If I selected one or more on the Q1 to Q4 checkbox - 'Yes to all' checkbox will be disabled
Code:
$('input[type=checkbox]').change(function() {
if ($(this).is(':checked')) {
$('input[type=checkbox]').attr('disabled', true);
$(this).attr('disabled', '');
} else {
$('input[type=checkbox]').attr('disabled', '');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You need to check weather the checkboxes selected or not as per your requirement,
Condition 1: if question selected length is more than 1, then disable the YTA
condition 2: if YTA is selected then disable all the Questions
If need anything else, please let me know.
$('.yta').change(function() {
if($('.yta:checked').length){
$('.q').attr('disabled', true);
}else {
$('.q').removeAttr("disabled");
}
});
$('.q').change(function() {
if($('.q:checked').length){
$('.yta').attr('disabled', true);
}else {
$('.yta').removeAttr("disabled");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q" type="checkbox" name="Q1" value="1" />Q1
<input class="q" type="checkbox" name="Q2" value="2" />Q2
<input class="q" type="checkbox" name="Q3" value="3" />Q3
<input class="q" type="checkbox" name="Q4" value="4" />Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA" />Yes to all
My answer with my philosophy:
Avoid jQuery if you can
Use small functions that do one thing
Have in mind that the same should work when used multiple times in a document
Prevent magic values in your code
Encapsulate as much as possible
So this seems like overkill, but this works
{
function checkAnswers(qNames, allName) {
const qSelector = qNames.map(e => `[name="${e}"]`).join(',')
const allSelector = `[name="${allName}"]`
const selector = `${qSelector},${allSelector}`;
const getValue = () => Array.from(document.querySelectorAll(selector)).filter(e => e.checked).map(e => ({[e.name]: e.value}))
const checkQ = value => value.map(e => Object.keys(e)[0]).filter(value => qNames.includes(value)).length > 0;
const checkAll = value => value.map(e => Object.keys(e)[0]).includes(allName)
const qDisable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = true)
const qEnable = () => Array.from(document.querySelectorAll(qSelector)).forEach(e => e.disabled = false)
const allDisable =() => document.querySelector(allSelector).disabled = true
const allEnable = () => document.querySelector(allSelector).disabled = false
return e => {
if (!e.target.closest(selector)) {return}
const value = getValue();
if (checkQ(value)) {
allDisable();
} else if (checkAll(value)) {
qDisable()
} else {
allEnable();
qEnable();
}
}
}
let qNames = ['QA1','QA2','QA3','QA4']
let allName = 'QAYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
qNames = ['QB1','QB2','QB3','QB4']
allName = 'QBYTA'
document.addEventListener('change', checkAnswers(qNames, allName))
}
:disabled + label {
color: lightgray;
}
<input type="checkbox" id="QA1" name="QA1" value="1"/><label for="QA1">Question 1</label><br>
<input type="checkbox" id="QA2" name="QA2" value="2"/><label for="QA2">Question 2</label><br>
<input type="checkbox" id="QA3" name="QA3" value="3"/><label for="QA3">Question 3</label><br>
<input type="checkbox" id="QA4" name="QA4" value="4"/><label for="QA4">Question 4</label><br>
<input type="checkbox" id="QAYTA" name="QAYTA" value="YTA"/><label for="QAYTA">Yes to all</label>
<br><br>
<input type="checkbox" id="QB1" name="QB1" value="1"/><label for="QB1">Question 1</label><br>
<input type="checkbox" id="QB2" name="QB2" value="2"/><label for="QB2">Question 2</label><br>
<input type="checkbox" id="QB3" name="QB3" value="3"/><label for="QB3">Question 3</label><br>
<input type="checkbox" id="QB4" name="QB4" value="4"/><label for="QB4">Question 4</label><br>
<input type="checkbox" id="QBYTA" name="QBYTA" value="YTA"/><label for="QBYTA">Yes to all</label>
You can do something like this.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="q1_q4" type="checkbox" name="Q1" value="1"/>Q1
<input class="q1_q4" type="checkbox" name="Q2" value="2"/>Q2
<input class="q1_q4" type="checkbox" name="Q3" value="3"/>Q3
<input class="q1_q4" type="checkbox" name="Q4" value="4"/>Q4
<input class="yta" type="checkbox" name="QYTA" value="YTA"/>Yes to all
<script>
$(".q1_q4").on('change', function(){
$(".yta").attr("disabled","disabled");
});
$(".yta").on('change', function(){
$(".q1_q4").attr("disabled","disabled");
});
</script>
See the perfect answer.
$('input[type=checkbox]').change(function() {
if ($(this).is('input[name="QYTA"]')) {
if ($(this).is(':checked')) {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', true);
} else {
$('input[type=checkbox][name!="QYTA"]').attr('disabled', false);
}
} else {
if ($(this).is(':checked')) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', true);
} else if($('input[type=checkbox][name!="QYTA"]:checked').length == 0) {
$('input[type=checkbox][name="QYTA"]').attr('disabled', false);
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
You can use the .prop function in jQuery to add and remove the disabled attribute easily. You would need to refine the selectors if you are using other checkboxes on the same page.
$('input[type=checkbox]').change(function() {
if (this.name == "QYTA" && this.checked) {
$('input[type=checkbox][name!="QYTA"]').prop("disabled", true);
} else if (this.name != "QYTA" && this.checked) {
$('input[type=checkbox][name="QYTA"]').prop("disabled", true);
} else {
$('input[type=checkbox]').prop("disabled", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1" />Q1
<input type="checkbox" name="Q2" value="2" />Q2
<input type="checkbox" name="Q3" value="3" />Q3
<input type="checkbox" name="Q4" value="4" />Q4
<input type="checkbox" name="QYTA" value="YTA" />Yes to all
My solution is to set up onchange event handler for each checkbox.
And then depending on the element which triggered the onchange event to perform a different operation.
if QYTA trigger the onchange then disable the Q1 to Q4 checkbox.
Else
disable the QYTA checkbox.
I make use of the logic difference between the checked and disabled attribute.
Here is my solution:
$("input[type='checkbox']").each(function() {
$(this).on('change', function() {
if (this.name=='QYTA'){
for (let i=1;i<5;i++){
$("input[type='checkbox'][name='Q"+i+"']").attr('disabled', this.checked);
}
} else{
$("input[type='checkbox'][name='QYTA']").attr('disabled', this.checked);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all
hope help u
$("input[type='checkbox']").each(function(){
$(this).on('click', function(){
var el = $("input[type='checkbox']").not($("input[name='QYTA']"));
var elAl = $("input[name='QYTA']");
if($(this).not(elAl).length == 0) {
if(elAl.is(':checked')){
el.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
} else if(el.is(':checked')){
elAl.attr('disabled',true);
} else {
$("input[type='checkbox']").removeAttr("disabled");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="Q1" value="1"/>Q1
<input type="checkbox" name="Q2" value="2"/>Q2
<input type="checkbox" name="Q3" value="3"/>Q3
<input type="checkbox" name="Q4" value="4"/>Q4
<input type="checkbox" name="QYTA" value="YTA"/>Yes to all

Link Radiobox button to Input

I have 2 radio button, each valued Yes and No respectively and 1 textbox.. If I checked on No button, the input textbox will open. If checked on Yes, textbox will disabled.
This code is working fine but I want to delete content that input to the textbox if the user checked Yes
function ismcstopu() {
var chkNo = document.getElementById("radio2_ismcstop");
var mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = chkNo.checked ? false : true;
if (!mcnostopreason.disabled) {
mcnostopreason.focus();
} else {
mcnostopreason.val('');
}
}
<input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" onclick="ismcstopu()" value="Yes">Yes
<input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" onclick="ismcstopu()" value="No">No
<label for="mcnostopreason">If No, Reason:</label>
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
.val is a jQuery construct but you are using DOM
Here is a better version using eventListener
Change the document.getElementById("container") to whatever container you have (your form for example)
Note: It is often better to test true than to test false
I also added labels to the radios so we can click the yes or no too
document.getElementById("container").addEventListener("click", function(e) {
const tgt = e.target;
if (tgt.name === "ismcstop") {
const mcnostopreason = document.getElementById("mcnostopreason");
mcnostopreason.disabled = tgt.value === "Yes";
if (mcnostopreason.disabled) {
mcnostopreason.value = '';
} else {
mcnostopreason.focus();
}
}
})
<div id="container">
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
</div>
jQuery version
$("[name=ismcstop]").on("click", function() {
if (this.name === "ismcstop") {
const $mcnostopreason = $("#mcnostopreason");
$mcnostopreason.prop("disabled", this.value === "Yes");
if ($mcnostopreason.is(":disabled")) {
$mcnostopreason.val("");
} else {
$mcnostopreason.focus();
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-check-input" id="radio1_ismcstop" name="ismcstop" value="Yes">Yes</label>
<label><input type="radio" class="form-check-input" id="radio2_ismcstop" name="ismcstop" value="No">No</label>
<label for="mcnostopreason">If No, Reason:
<input class="inputstyle-100" type="text" id="mcnostopreason" name="mcnostopreason" value="" disabled>
</label>
mcnostopreason is not a jQuery object. therefore you could do: var mcnostopreason = $("#mcnostopreason");
Or you could just change mcnostopreason.val('') to mcnostopreason.value = '' ( this will mean you don't need to change anything else)

How to enable disable sup tag in javascript

i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.
my view:
<label>code<sup id="star" disabled>*</sup></label>
>Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
> id="no"/>onchange="starenable()"/>no
my javascript:
function starenable() {
if (document.getElementById('yes').checked) {
document.getElementById("star").disabled = false;
} else if (document.getElementById('no').checked) {
document.getElementById("star").disabled = true;
}
}
i tried this but no change in view. any ideas?
Here is your solution https://jsfiddle.net/me9uwL2d/
<input type="radio" name="test" value="Yes" />Yes
<input type="radio" name="test" value="No" />No
<input type="text" />
$('input[type="radio"]').change(function() {
if( $(this).is(':checked') && ($(this).attr('value') == 'Yes')) {
$('input[type="text"]').val("*");
}else{
$('input[type="text"]').val('');
}
});
Input have disable attribute .Change the sub with input .And align the html code on proper format.Then add the * depend on checked radio button
Updated
note: sub tag not have a disable attribute
function starenable() {
if (document.getElementById('yes').checked) {
document.getElementById("star").disabled = false;
} else if (document.getElementById('no').checked) {
document.getElementById("star").disabled = true;
}
document.getElementById("star").innerHTML = document.getElementById('yes').checked ? '*' : '';
}
<label>code <sub id="star"></sub></label> Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()" />yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no
$(document).ready(function() {
$('input[type=radio][name=yes]').change(function() {
if (this.id == 'yes') {
$('#star').hide();
}
else if (this.id == 'no') {
$('#star').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<label>code<span id="star" >*</span></label>
Add to electronic
<input type="radio" name="yes" id="yes"/>yes
<input type="radio" name="yes"
id="no"/>no
use this
<label>code<sup id="star" style="visibility:hidden">*</sup></label>
Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()"/>yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no
function starenable() {
if (document.getElementById('yes').checked)
document.getElementById("star").style.visibility = "visible";
else if (document.getElementById('no').checked)
document.getElementById("star").style.visibility = "hidden";
}

Label -> Checkbox Text

I have this problem..
I have this HTML code for 2 groups of checkbox:
<label class="checkbox"><input type="checkbox" onClick="toggle_colors(this)" checked><i></i>All Colors</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox"><input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox"><input type="checkbox" onClick="toggle_brands(this)" checked><i></i>Tutte le Marche</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox"><input type="checkbox" name="brand" checked><i></i>Asus</label>
And I use this javascripts for select all/toggle all:
function toggle_brands(source) {
checkboxes = document.getElementsByName('brand');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
function toggle_colors(source) {
checkboxes = document.getElementsByName('colore');
for(var i=0, n=checkboxes.length;i<n;i++) {
checkboxes[i].checked = source.checked;
}
}
When the user click on the checkbox I need to know if the checkbox is selected or not, to send the details of the query by AJAX..
To know if the checkbox I use this javascript:
$( "[type=checkbox]" ).change(function() {
if(this.checked) {
alert('checked');
}
else {
alert('unchecked');
}
});
I want the text at the right of the selected checkbox..!
Ok.. With the parent work fine!
I have added this code to create the query:
function create_query(){
var query = "SELECT * FROM computers ORDER BY " + ($("#ordine option:selected").val()) + " LIMIT " + ($("#risultati option:selected").val());
$.ajax({
type: "POST",
url: "static/cerca_prodotti.php",
data: "query="+query,
dataType: "html",
success: function(risposta){
$("div#risultati").html(risposta);
},
})
}
$( "[type=checkbox]" ).change(function() {
if(this.checked) {}
else {}
});
$("#ordine").change(function() {
create_query();
});
But I need to modify the query when the checkbox was checked/unchecked!
When you change the checked property programatically, the change event will not get triggered, you need to trigger the event manually.
$('input[data-all-type]').change(function() {
$('input[name="' + $(this).data('allType') + '"]')[this.checked ? 'not' : 'filter'](':checked').prop('checked', this.checked).change();
})
$("input[type=checkbox]:not([data-all-type])").change(function() {
if (this.checked) {
console.log('checked', this);
} else {
console.log('unchecked', this);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" name="color-all" data-all-type="colore"><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore"><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" name="brand-all" data-all-type="brand"><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand"><i></i>Asus</label>
You can do that with only one function
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', $(source).is(':checked'))
//OR
$('input[name="' + things + '"]').prop('checked', source.checked);
}
function toggle_checkbox(source, things) {
$('input[name="' + things + '"]').prop('checked', source.checked);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'colore')" checked><i></i>All Colors</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>red</label>
<label class="checkbox">
<input type="checkbox" name="colore" checked><i></i>yellow</label>
<label class="checkbox">
<input type="checkbox" onClick="toggle_checkbox(this,'brand')" checked><i></i>Tutte le Marche</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Acer</label>
<label class="checkbox">
<input type="checkbox" name="brand" checked><i></i>Asus</label>
You can get text of the parent node of the checkbox in this way:
$( "[type=checkbox]" ).change(function() {
var text = this.parentElement.innerText;
if(this.checked) {
alert(text + ': checked');
}
else {
alert(text + ': unchecked');
}
});

Get only two values of multiple Checkboxes

I found this code on codeLAB and I'm trying to get true result only if "Cricket" and "Boxing" are checked. Currently it works if both of them are checked, but also when the others are selected.
https://jsfiddle.net/kubus1234/oksm8eaw/
$("button").click(function() {
var favorite = [];
$.each($("input[name='sport']:checked"), function() {
favorite.push($(this).val());
});
var test = [];
$.each($("input[name='sport']:checked"), function() {
test.push($(this).val());
});
if (favorite[1] == "cricket" || test[1] == "boxing") {
alert("Your are the best");
} else {
alert("Your are looser");
}
});
Any solution?
Not sure why you traversed the selected checkboxes twice, but here's one way to get your results:
$(document).ready(function() {
$("button").click(function() {
var selected = $("input[name='sport']:checked").toArray().map(function(checkbox) {
return $(checkbox).val();
});
if (selected.length === 2 && selected[0] === "cricket" && selected[1] === "boxing") {
alert("You are the best");
} else {
alert("You lose");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<h3>Select your favorite sports:</h3>
<label>
<input type="checkbox" value="football" name="sport">Football</label>
<label>
<input type="checkbox" value="baseball" name="sport">Baseball</label>
<label>
<input type="checkbox" value="cricket" name="sport">Cricket</label>
<label>
<input type="checkbox" value="boxing" name="sport">Boxing</label>
<label>
<input type="checkbox" value="racing" name="sport">Racing</label>
<label>
<input type="checkbox" value="swimming" name="sport">Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
This would be easily researchable but I'll post a solution anyway
1) I gave the checkboxes ids
2) I changed the JavaScript to check if both checkboxes are checked at once with .is(":checked")
<form>
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" id="chkFootball" value="football" name="sport"> Football</label>
<label><input type="checkbox" id="chkBaseball" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" id="chkCricket" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" id="chkBoxing" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" id="chkRacing" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" id="chkSwimming" value="swimming" name="sport"> Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
$(document).ready(function() {
$("button").click(function(){
if ($('#chkCricket').is(':checked') && $('#chkBoxing').is(':checked')) {
alert("Checked");
}
else {
alert("Not checked");
}
});
});
https://jsfiddle.net/oksm8eaw/2/
Please don't use javascript alerts. Alerts cause cancer...
... instead use ids, and jQuery html(): add this to the HTML: <div id="result"></div>
Solution
$(document).ready(function() {
$("button").click(function(){
var matchCount = 0;
$('input').each(function(){
if( this.value == "cricket" || this.value == "boxing") {
if(this.checked) matchCount++;
}
});
if(matchCount>1){
$("#result").html("YUP!");
} else {
$("#result").html("NOPE!");
}
});
});

Categories

Resources