Hi i have checkboxes and submit button.And for validation i need atleast 1 checkbox should be checked while clicking on submit button.I tried few ways in jquery but now working.Thank you.
Here is my code:
dashboard.php
<table id="fahrzeuge" >
<tr>
<td>
<input type="checkbox" name="Anzahl_Fahrzeuge_ohne_Bilder" id="Anzahl_Fahrzeuge_ohne_Bilder" checked />
<label for="Anzahl_Fahrzeuge_ohne_Bilder">Anzahl Fahrzeuge ohne Bilder</label><br>
<input type="checkbox" name="Fahrzeuge_ohne_Preis" id="Fahrzeuge_ohne_Preis" value="Fahrzeuge_ohne_Preis" checked />
<label for="Fahrzeuge_ohne_Preis">Fahrzeuge_ohne_Preis</label><br>
<input type="checkbox" name="Fahrzeuge_mit_Fehlern" id="Fahrzeuge_mit_Fehlern" value="Fahrzeuge_mit_Fehlern" checked />
<label for="Fahrzeuge mit Fehlern">Fahrzeuge mit Fehlern</label><br>
<input type="checkbox" name="Herausforderungen" id="Herausforderungen" value="Herausforderungen" checked />
<label for="Herausforderungen">Herausforderungen</label><br><br>
</td>
</tr>
</table>
dashboard.js
function getFahrzeuge() {
var opts = [];
$("#fahrzeuge input[type='checkbox']").each(function () {
if ($(this).is(':checked'))
{
opts.push($(this).attr("id"));
}
});
return opts;
}
$('#fahrzeuge .butt-rahmen').on('click', function(){
if($(this).attr('id') == 'saveId')
{
var opts = getFahrzeuge();
saveFahrzeugeWidget(opts);
}
});
You can simply do the check using :checked selector:
if($("#fahrzeuge input:checked").length){
//atleast one checked
}
Related
I'm relatively new to JS, so I'm getting a little stuck with this:
Let's say I have 40 checkboxes, but a user can select no more than 10.
I have the checkboxes set out, labelled checkbox1, checkbox2 etc right up to 40. The user cannot select more than 10. How would I go about doing this?
The way I thought of doing it would be like this, but I'm unsure whether or not this would work, due to obviously having 40 fields and then what if they uncheck one?
function checkValidation() {
if (document.getElementById('checkbox1').isChecked()) {
document.getElementById('validation').value() + 1;
}
}
So every time it's checked, it would add 1 to the textbox validation and then I could do an if statement to say if validation.value() > 8 then alert out to say they can't check anymore.
I think that's not the best way, as if they uncheck the box, my function won't take this in consideration?
Hopefully this makes sense, if anything needs clarification please let me know and I can explain further.
Try the following way:
$('#myBtn').click(function(){
var countCheckd = $('input[type=checkbox]:checked').length;
if(countCheckd >= 3){
console.log('You have 3 or more checked: ' +countCheckd);
}
else{
console.log('You have less than 3 checked: ' +countCheckd);
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />1
<input type="checkbox" />2
<input type="checkbox" />3
<input type="checkbox" />4
<input type="checkbox" />5
<br><br>
<input type="button" id="myBtn" value="Check"/>
You can add a class on all your considered checkboxe, called for example chk.
Then you declare your count function :
function countCheck(){
return $(".chk:checked").length;
}
Finally you add an event on your checkboxes click :
$(document).on("click",".chk",function(){
var numberChecked = countCheck();
//update your input
$("#validation").val(numberChecked );
});
Just make an event of checkbox click and check for the count of each click, in below example if the click is exceeded then 5 it gives an alert message and won't be allowed to click more checkboxes.
$(function(){
for(var i=0;i<=30;i++){
$(".test").append("checkbox "+i+"<input type='checkbox' name='chk[]' class='check' id='check_"+i+"'><br />");
}
})
$(document).on("click",".check",function(){
var checked = $(".check:checked").length
if(checked > 5){
alert("Maximum 5");
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class='test'>
</div>
You can try something like this:
$('input[type=checkbox]').on('change', function (e) {
if ($('input[type=checkbox]:checked').length > 10) {
$(this).prop('checked', false);
alert("Only 10 selection is allowed");
}
});
This code is unchecking previous checkbox if checked input's length more than 10:
$('input[type="checkbox"]').on('click', function(){
var max=0;
var t=$(this);
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')>max){
max=$(this).data('oops');
}
});
t.data('oops', (max+1));
if($('input[type="checkbox"]:checked').length>10){
$('input[type="checkbox"]:checked').each(function(){
if($(this).data('oops')==max){
$(this).prop('checked', false);
}
});
}
});
Without adding global variable.
See
This works:
// these are global variables
var checkBoxChecks = 0;
var maxChecks = 10;
$('input[type="checkbox"]').on('click', function()
{
// if the currently clicked checkbox is now checked
if(this.checked)
{
if(checkBoxChecks < maxChecks) checkBoxChecks++;
else
{
this.checked = false;
alert("You have reached the maximum amount of " + maxChecks + " checks.");
}
}
else checkBoxChecks--;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
I am trying to send checkbox values to other page to delete the selected rows with checkbox but when there is no checkbox clicked and try to send it should give alert for checkbox is empty and if the form is submitting after the checkbox is clicked then it should give alert whether to proceed or not this is my form
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="checkForm()">
<table id="mytable" border=3 >
<c:forEach items="${users}" var="user">
<tr>
<td>
<input type="checkbox" id="saif" name="<c:out value="${user.hrid}" />"
value="<c:out value="${user.hrid}" />" />
</td>
</tr>
</c:forEach>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
Javascript:
<script type="text/javascript">
function checkForm(){
var checkt = document.getElementsById('saif');
var chekSelect = false;
for (var i = 0; i < checkt.length; i++) {
var myElement = checkt[i];
if (myElement.type === "checkbox" && myElement.checked) {
if (myElement.checked) {
chekSelect = true;
break;
}
}
}
if(!chekSelect) {
alert('Please Check Atleast one record to print cheque!!!');
return false;
} else {
return true;
}
}
</script>`
Few things you can modify here like:
Add return to onsubmit like onsubmit="return checkForm()"
Use class instead of id like for this demo we have used class="item"
And finally use document.querySelector to get only checked checkbox.
DEMO:
function checkForm() {
if (document.querySelector('.item:checked')) {
alert('Checkbox is checked');
return true;
} else {
alert('Please Check Atleast one record to print cheque!!!');
return false;
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=1>
<tr>
<td>
<input type="checkbox" class="item" value="1" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="2" />
</td>
</tr>
<tr>
<td>
<input type="checkbox" class="item" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs" />
</form>
function checkForm(e){
event.preventDefault()
var a = document.querySelectorAll('#saif');
if(a[0].checked || a[1].checked || a[2].checked == true){
alert('Checkbox checked')
}else{
alert('Please Check Atleast one record to print cheque!!!')
}
}
<form action="deleteselectedhr" name="deleteFiles" method="post" onsubmit="return checkForm()">
<table id="mytable" border=3 >
<tr>
<td>
<input type="checkbox" id="saif" value="1" /><br/>
<input type="checkbox" id="saif" value="2" /><br/>
<input type="checkbox" id="saif" value="3" />
</td>
</tr>
</table>
<input TYPE="SUBMIT" value="Delete Selected HRs"/>
</form>
I hope you are using a framework of any particular language.
In MVC structure, you can validate the presence of the checkbox.
For example, I am using Ruby on Rails and I have my checkbox field
<%= f.label :active %>
<%= f.check_box :active %>
I then validate the checkbox as
validates :active, presence: true
I can also print a flash message via my controller to show the error. Eg:-
flash.now[:danger] = 'Invalid email/password combination'
In the form below, how to ignore the disabled checkbox. The expected behavior in the form is that if the user does not check the Model check box and click on the submit button, form should be submitted. If the Model checkbox is checked, user must enter data. This behavior works as long as there is no other checkbox on the page. If there is another checkbox, and the submit button is clicked without checking the Model checkbox, alert is thrown. How can I ignore the other checkboxes in the form to achieve the desired behavior? Thanks!
$(document).ready(function () {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $("input[type=checkbox]:checked").length;
var isTextEntered = $("input.childModel").val().length;
if ( isTextEntered || !isCheckboxChecked ) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p><h2>MODEL:</h2></p>
<input type="checkbox"> Model #
<input type="text" size="12" class="childModel"><BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn"/>
The checkbox needs to have a unique selector.
$(document).ready(function () {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $("input[name='model_number']:checked").length;
var isTextEntered = $("input.childModel").val().length;
if ( isTextEntered || !isCheckboxChecked ) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p><h2>MODEL:</h2></p>
<input type="checkbox" name="model_number"> Model #
<input type="text" size="12" class="childModel"><BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn"/>
To ignore the checkbox you don't want to validate you need a way to ignore it in your validation, and you can do that by using the input field. Change the selector for your checkbox from $("input[type=checkbox]:checked") to $(".childModel").prev("input[type=checkbox]:checked")
Example:
$(document).ready(function() {
$('#checkModelBtn').click(function() {
var isCheckboxChecked = $(".childModel").prev("input[type=checkbox]:checked").length;
var isTextEntered = $("input.childModel").val().length;
if (isTextEntered || !isCheckboxChecked) {
//alert("validation passed!");
} else {
alert("Please enter the Model Number");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table>
<tr>
<td>
<p>
<h2>MODEL:</h2>
</p>
<input type="checkbox"> Model #
<input type="text" size="12" class="childModel">
<BR>
</td>
<td>
THIS CHECKBOX BREAKS THE FUNCTIONALITY
<p>
<input type="checkbox" checked disabled> Some text here</td>
</tr>
</table>
<hr>
<input type="submit" name="submit" value="submit" id="checkModelBtn" />
I have a table with 2 checkboxes:
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
and I want to be able to identify which box is checked (by id), and be able to store a string as a variable, depending on the box. Here is my javascript:
var getCheck = function() {
if (document.getElementById('A').checked) {
return "A";
}
else if (document.getElementById('B').checked){
return "B";
}
else if ((document.getElementById('A').checked) && (document.getElementById('B').checked)) {
return "Both"
}
console.log(getCheck); // for debugging
};
So if I check 'A', I want getCheck to = 'A' as a string. Curious as to how to fix my Javascript to get it to work.
Here's an example of how you would do it with jQuery, it's just easier to do with it and since there's a jQuery tag...
Basically, you add a handler for elements that are checkboxes. Then you select only checked checkboxes with :checked and then you just access each element with the jQuery each function.
$(function(){
$('input[type=checkbox]').on('change', function(){
var checked = [];
$('input[type=checkbox]:checked').each(function(index, checkbox){
checked.push($(checkbox).attr('id'));
});
$('#result').text(JSON.stringify(checked, '/t'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
<pre id="result"></pre>
You need to check both first, since otherwise the function will return "A" and never reach the code that would return both. It is also possible to eliminate all the if-else complexity when returning from each if.
A helper function and some variables can reduce repetition and code length.
var isChecked = function(id){
var e = document.getElementById(id);
return (e && e.checked);
}
var getCheck = function() {
var A = isChecked("A");
var B = isChecked("B");
if (A && B) return "Both";
if (A) return "A";
if (B) return "B";
return "None";
}
For testing, you could add
window.onclick = function(){ console.log(getCheck()); }
demo via jsfiddle
fiddle example
The answer others provided is quite good for. And I want to make some addition:
If you want to get the value whenever user check the box, you can add a eventListen to the parent table as a delegation for the checkbox. Just as I show in the fiddle example
<table id="mytable">
<tr>
<td>
<label for="A">
<input type="checkbox" name="A" id="A" value="true" />
A
</label>
<label for="B">
<input type="checkbox" name="B" id="B" value="true" />
B
</label>
</td>
</tr>
</table>
i've checkbox and text input
What I need is to enable text input when i check the checkbox and to disable text input when i uncheck the checkbox
I'm using the following code but it do the reverse enable when unchecked / disable when checked so how to adjust it fit with my needs.
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
<script>
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').enabled = this.checked;
};
</script>
any help ~ thanks
You just need to add a ! in front of this.checked.
Here's an example that shows the change:
document.getElementById('yourBox').onchange = function() {
document.getElementById('yourText').disabled = !this.checked;
};
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" />
A jQuery solution could be this one:
<script>
$('#yourBox').change(function() {
$('yourText').attr('disabled',!this.checked)
});
</script>
It is the same as Minko's answer but I find it more elegant.
Try it. If you use a label then add onmousedown to it
<form >
<input type="text" id="yourText" disabled />
<input type="checkbox" id="yourBox" onmousedown="this.form.yourText.disabled=this.checked"/>
</form>
A better solution could be:
var checkbox = document.querySelector("#yourBox");
var input = document.querySelector("#yourText");
var toogleInput = function(e){
input.disabled = !e.target.checked;
};
toogleInput({target: checkbox});
checkbox.addEventListener("change", toogleInput);
<input type="checkbox" id="yourBox">
<input type="text" id="yourText">
function createInput( chck ) {
if( jQuery(chck).is(':checked') ) {
jQuery('<input>', {
type:"text",
"name":"meta_enter[]",
"class":"meta_enter"
}).appendTo('p.checkable_options');
}
else {
jQuery("input.meta_enter").attr('disabled','disabled');
}
}
createInput( chck );
<input type="radio" name="checkable" class="checkable" value="3" />
<input type="radio" name="checkable" class="checkable" value="4" onclick="createInput(this)" />