I am using the following code to check if at least one checkbox is selected from my checkboxlist in asp.net. I am using jGrowl to throw up a message which works, but the message is still displayed if a selection is made. Any ideas? Also, story_type is an asp label, I am using the code below, but I can't get the jGrowl message to display...
var story_type = document.getElementById('story_type').value;
var agile_list = document.getElementById('agile_factors');
var arrayOfCheckBoxes = agile_list.getElementsByTagName("input");
for (counter = 0; counter < arrayOfCheckBoxes.length; counter++) {
if (arrayOfCheckBoxes[counter].checked) {
return true;
} else {
(function($) {
$.jGrowl("Please Choose up to 3 Agile Factors", { theme: 'smoke', closer: true });
})(jQuery);
return false;
}
}
if (story_type == "[SELECT TYPE]") {
(function($) {
$.jGrowl("Please Select Story Type", { theme: 'smoke', sticky: true, closer: true })
return false;
})(jQuery);
return true;
}
Since you have jQuery you can do this to simplify your code a bit:
<div id="options">
<input type="checkbox" name="opt1" /> Option 1
<input type="checkbox" name="opt2" /> Option 2
<input type="checkbox" name="opt3" /> Option 3
<input type="checkbox" name="opt4" /> Option 4
</div>
<div>
validate
</div>
<script type="text/javascript">
;(function() {
$("#validate").click(function() {
validateInputs();
});
function validateInputs() {
alert($("#options input:checked").length + " checked");
}
})();
</script>
Here is a jsFiddle of the above code; http://jsfiddle.net/rvXHG/
Related
I have this kind of structure:
Radio Buttons:
o Enable o Disable
Check Boxes
[]checkBox1
[]checkBox2
[]checkBox3
[]checkBox4
The Above controls are generated dynamically.
<asp:RadioButtonList runat="server" ID="rbSubsidiaries" onclick = "Radio_Click()"/>
<asp:CheckBoxList runat="server" ID="cblSubsidiaries" Enabled="False"/>
What I want is: When the user click on the RadioButton Enable All the checkboxes get enable otherwise disable.
I am at the point where I can see that if the user has clicked on enable radio button.
function Radio_Click() {
if ($('#<%=rbSubsidiaries.ClientID %> input:checked').val() == 'enable') {
alert('enable is clicked');
}
}
But I don't know how to enable all the checkBoxes.
Picture that Contains the the rendered structure of the CheckBoxList. First Two check Boxes.
Try something like this:
$("#cblSubsidiaries > input[type='checkbox']").prop("disabled", false)
Update:
$("#contentpage_0_content_0_cblSubsidiaries input[type=checkbox]").prop("disabled",false)
This is the code which will help you
Html
<input type="radio" name="check" value="enable" class="enableList">Enable
<input type="radio" name="check" value="disable" class="disableList">Disable
<div class="container">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car </div>
Script
$(document).ready(function () {
$('.enableList').change(function () {
if ($(this).prop('checked') == true) {
$('.container').find('input:checkbox').each(function () {
alert ("enable check box");
});
}
});
$('.disableList').change(function () {
if ($(this).prop('checked') == true) {
$('.container').find('input:checkbox').each(function () {
alert("disable check box");
});
}
});
});
this is working fidler
https://jsfiddle.net/Ln7y6v0n/
Something like this should work:
$('#contentpage_0_content_0_cblSubsidiaries input[type=checkbox]').each(function() {
$(this).prop('checked', true);
});
$(document).ready(function () {
$('#<%=RadioButtonList1.ClientID%>').change(function () {
$('#<%=RadioButtonList1.ClientID%>').each(function () {
var checked = $(this).find('input:radio:checked');
if (checked.val() == "Enable") {
$('#<%=CheckBoxList1.ClientID%>').each(function () {
var checked = $(this).find('input:checkbox');
checked.prop('checked', true);
});
}
else {
$('#<%=CheckBoxList1.ClientID%>').each(function () {
var checked = $(this).find('input:checkbox');
checked.prop('checked', false);
});
}
});
});
});
protected void Page_Load(object sender, EventArgs e)
{
ListItem item = new ListItem();
item.Text = "Enable";
item.Value = "Enable";
RadioButtonList1.Items.Add(item);
ListItem item1 = new ListItem();
item1.Text = "Disable";
item1.Value = "Disable";
RadioButtonList1.Items.Add(item1);
for (int i = 1; i <= 4; i++)
{
ListItem chkitem = new ListItem();
chkitem.Text = "Checkbox" + i;
chkitem.Value = "Checkbox" + i;
CheckBoxList1.Items.Add(chkitem);
}
}
<div>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"></asp:RadioButtonList>
<br />
<hr />
<asp:CheckBoxList ID="CheckBoxList1" runat="server"></asp:CheckBoxList>
</div>
I am learning jquery. I have made a simple html file with minor validations in jquery , but they are not behaving properly. The issue is:
If Enter name first and then select the checkbox, everything seems to be working fine .
But if I select gender first and then enter name , it keeps alerting me to select gender.
Is there an issue with the way which the code has been implemented?
<script src="jquery.js"></script>
<script>
$(document).ready(function () {
$("#Name").focus();
$("#target").submit(function () {
var fn = $("#Name").val();
if (fn == "" && fn.length == 0) {
alert('Name is mandatory');
$("#Name").focus();
return false;
}
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
if (!status) {
alert("Select Gender");
$("#gender").focus();
return false;
}
return true;
});
});
</script>
<form id='target' action='MyResult.html'>
First Name:
<input type='text' name='Name' id='Name' />
<br/>Gender:
<input type='radio' name='gender' id='gender' value='male' />Male
<input type='radio' name='gender' id='gender' value='female' />Female
<br/>
<input type='submit' value='Registration' />
</form>
IDs must be unique. You can use Attribute value selector in combination with :checked to filter out whether radio button is checked or not.
var status = $(":radio[name=gender]:checked").length > 0;
instead
var status = false;
$("#gender").each(function () {
if ($(this).is(":radio:checked")) {
status = true;
}
});
DEMO
I am getting errors. The script is not working. Help
thanks in advance.
I want to check if all my set of radio buttons are checked when button next is click.
other ways of doing this also are welcome
<div class="qheader">
9) What's the world's most widely spoken language?</div>
<div class="qselections">
<input type="radio" value="a" name="question9">a) English<br>
<input type="radio" value="b" name="question9">b) Spanish<br>
<input type="radio" value="c" name="question9">c) Mandarin<br>
<input type="radio" value="d" name="question9">d) French<br>
</div><br>
<div class="qheader">
10) Which continent is host to the most countries in the world?</div>
<div class="qselections">
<input type="radio" value="a" name="question10">a) Asia<br>
<input type="radio" value="b" name="question10">b) Africa<br>
<input type="radio" value="c" name="question10">c) Europe<br>
</div>
</div>
<input type="button" value="Next" name="B3" onclick="showdesc()">
<script>
$(function() {
$(document).on('click', 'form', function () {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
});
});
</script>
function clicked() {
var validate = true;
var unanswered = new Array();
// Loop through available sets
$('.qselections').each(function () {
// Question text
var question = $(this).prev().text();
// Validate
if (!$(this).find('input').is(':checked')) {
// Didn't validate ... dispaly alert or do something
unanswered.push(question);
validate = false;
}
});
if (unanswered.length > 0) {
msg = "Please answer the following questions:\n" + unanswered.join('\n');
alert(msg);
}
return validate;
}
JSFiddle
I reproduced your problem with slight modifications, works well for me. I guess it's just a syntax error in the portion of your code, not present in the fiddle. Cross check and let me know.
Try and modify your click call, make it direct like in the fiddle.
//try this script
if(!$(this).find("input[name=radio]").is(':checked')){
alert("hi");
}
I have a requirement that a user should select the checkbox values from a pop-up and click on submit on pop-up and the selected values should get displayed back to the parent page.
I was playing with some radio box values which I am able to push to the Parent window but struggling with checkbox values.
Here is what my pop-up looks like and my code is
<p>Please Select a language:</p>
<div id="myDialog" title="Select Language">
<br /><br />
<input type="checkbox" name="countryCheckbox[]" value="English" checked = "checked" /> English <br/>
<input type="checkbox" name="countryCheckbox[]" value="French" /> French <br/>
<input type="checkbox" name="countryCheckbox[]" value="Norwagian" /> Norwagian <br/>
<input type="checkbox" name="countryCheckbox[]" value="Swedish" /> Swedish <br/>
<input type="checkbox" name="countryCheckbox[]" value="Hindi" /> Hindi <br/>
<input type="checkbox" name="countryCheckbox[]" value="Chinese" /> Chinese <br/>
<br /><br />
<label for="yes">Yes!</label><input type="radio" id="yes" value="yes" name="question" checked="checked"><br>
<label for="no">No!</label> <input type="radio" id="no" value="no" name="question">
</div>
<p id="text">Selected Languages are: </p>
and my Jquery code that works for the selected radio button is as below
$(function(){
var execute = function(){
var answer;
$("input").each(function(){
(this.checked == true) ? answer = $(this).val() : null;
});
$("<p>").text("You selected " + answer).appendTo($("body"));
$("#myDialog").dialog("close");
}
var cancel = function() {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
I'm trying to add the following JQuery code to display the selected checkbox values on the parent pages
$('#myDialog').submit(function(ev){
ev.preventDefault();
var arr = [];
$('input:checkbox:checked').each(function(){
arr.push($(this).val());
});
$(opener.document).contents().find("#text").text(arr.join(","));
self.close();
});
Please suggest as I'm still struggling to integrate the JQuery code of selected checkboxes to be displayed on the parent page.
you would need to iterate over each input and then store that in an array to append it to the body..
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length ; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
});
Check Fiddle
Code
$(function () {
var execute = function () {
var answer = [];;
$("input").each(function () {
if (this.checked) answer.push(this.value);
});
for (var i = 0; i < answer.length; i++)
$("<p>").text("You selected " + answer[i]).appendTo($("body"));
};
var cancel = function () {
$("#myDialog").dialog("close");
}
var dialogOpts = {
buttons: {
"Submit": execute,
"Cancel": cancel
}
};
$("#myDialog").dialog(dialogOpts);
});
EDIT
var cancel = function () {
$("#myDialog").dialog("close");
}
var saveAndCancel = functionI() {
execute();
cancel();
}
var dialogOpts = {
buttons: {
"Submit": saveAndCancel ,
"Cancel": cancel
}
};
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Count the number of checkboxes selected without reloading the page?
I have an order form that asks the User which type of pass they would like (1-3 days), and gives them the option to choose the days they want the pass for.
Currently, when they choose 3 days, my JQuery selects all 3 checkboxes for them, and deselects when they choose 1 or 2 day(s). However, what I'm trying to do is:
When they select 2 day pass, it only allows them to check a maximum of 2 boxes. When they select a 1 day pass, it only allows them to check 1 box.
I'm drawing a blank as to what needs to go in my validateDays() function - the best way to go about running this validation or whether this is actually the best route to take.
Every method I think of using requires the checkboxes to have the same Name/ID - but due to other parts of the form (omitted), they unfortunately can't.
Any ideas / pointers?
HEAD Section JavaScript:
<script type="text/javascript">
function validateDays() {
$('#matthewpeckham').find('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('#matthewpeckham').find('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
else {
$('#matthewpeckham').find('input[type="checkbox"]').not(':checked').prop('disabled', false);
}
})
$('input[name="other_1"]').change(function () {
$('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('#matthewpeckham').find('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
jQuery('#3daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', true);
});
jQuery('#2daypass , #1daypass').click(function() {
jQuery('#other_2 , #other_3 , #other_4').prop('checked', false);
});
});
</script>
BODY Section HTML:
<input name="other_1" type="radio" value="3daypass" id="3daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="2daypass" id="2daypass" onClick="validateDays();">
<input name="other_1" type="radio" value="1daypass" id="1daypass" onClick="validateDays();">
<input name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">
Here's a jQuery solution: jsFiddle example
$('input[type="checkbox"]').click(function () {
var pass = parseInt($('input[name="other_1"]:checked').val(), 10) //1,2,3
var days = $('input[type="checkbox"]:checked').length;
console.log(days, pass);
if (days == pass) {
$('input[type="checkbox"]').not(':checked').prop('disabled', true);
}
})
$('input[name="other_1"]').change(function () {
$('input[type="checkbox"]').prop({
'checked': false,
'disabled': false
});
if (parseInt($(this).val(), 10) == 3) $('input[type="checkbox"]').prop({
'checked': true,
'disabled': false
});
});
You need to check the number of checked boxes in your validate function:
function validateDays() {
var numBoxesChecked = $("input:checkbox:checked").length;
if (document.getElementById("2daypass").checked && numBoxesChecked > 2) {
// invalid
}
if (document.getElementById("1daypass").checked && numBoxesChecked > 1) {
// invalid
}
}
Keep in mind that any javascript validation can be bypassed, so ensure you are performing some type of validation on your server as well.
Also note you may want to change the numBoxesChecked selector if there are other unrelated checkboxes on the page, such as limiting it to a container e.g.
var numBoxesChecked = $('#someContainer').find("input:checkbox:checked").length;
jQuery exposes a checkbox selector that should prove useful here.
Your validateDays function can then do something along these lines
var checkedBoxes = jQuery(":checkbox:checked");
var numChecked = checkedBoxes.length;
...
else if (document.getElementById("2daypass").checked) {
if (numChecked > 2) { /*do something*/ }
}
else if (document.getElementById("1daypass").checked) {
if (numChecked > 1) { /*do something*/ }
}
else {
// DO NOTHING
}
...
However, you might have an issue with "reverting" the box. You might be able to do simply
jQuery(this).prop('checked', false)
I'm not an expert in this area by any means but here is what I do on a site of mine, you should be able to modify it to suit your needs...just remember to give your inputs the same class name.
<script type="text/javascript">
function Check() {
var count = 0;
var checkBoxes = document.getElementsByClassName('chkValidation');
for (var index = 0; index < checkBoxes.length; index++) {
if (checkBoxes[index].type == 'checkbox') {
if (!checkBoxes[index].disabled) {
count = checkBoxes[index].checked ? (count + 1) : count;
}
}
}
if (count > 3) {
alert('Question two - please select a maximum of 3 sub questions to ask.');
return false;
}
return true;
}
You could also do it dymanically, using a function like so:
$('.checkbox').on('click', function(e) {
var num_checked = 0;
$('.checkbox').each(function() {
if ( $(this).prop('checked') ) num_checked++;
});
var max_checked = $('input[name="other_1"]:checked').val();
if ( num_checked > max_checked ) {
$(this).prop('checked', false);
}
});
Assuming a few small modifications to your html:
<input name="other_1" type="radio" value="3" id="3daypass">
<input name="other_1" type="radio" value="2" id="2daypass">
<input name="other_1" type="radio" value="1" id="1daypass">
<input class="checkbox" name="other_2" type="checkbox" id="other_2" value="Tues 5 Feb">
<input class="checkbox" name="other_3" type="checkbox" id="other_3" value="Wed 6 Feb">
<input class="checkbox" name="other_4" type="checkbox" id="other_4" value="Thurs 7 Feb">
Demo: http://jsbin.com/osecep/1/
It's not perfect, and you'd probably want to clear the checkboxes when the number of days is changed, but that should set you on the right track.