check if all inputs are checked - javascript

I have 2 buttons and 2 inputs. The "buy"-button should only fire its default function when both inputs are checked. If not it should mark them with a red border. What am I doing wrong here?
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
$(".checkedterms").change(function(){
if (!$('.checkedterms:checked').length == $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
});
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
buy<br><br>
no thanks

There's a couple of issues here:
You've got an equality check at the start of the code which does nothing.
You've nested the change handler on the checkboxes within the click handler of the button; remove it.
Unrelated to the issue, but you are using duplicate id attributes. They need to be unique within the DOM.
Your logic is backwards. You state that you want the red border to only appear when both checkboxes are not checked when the 'Buy' button is clicked.
You can also make the logic more succinct by caching the checkbox selector and using toggleClass(). Something like this:
jQuery(function($) {
$("#upsellyes").click(function(e) {
var $terms = $('.checkedterms');
$("#terms-required").toggleClass('invalid', $terms.length != $terms.filter(':checked').length);
});
});
.invalid {
border: 1px solid red;
}
.checkedterms {
position: absolute;
}
label {
display: inline-block!important;
font-weight: normal!important;
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read Allgemeinen Geschäftsbedingungen.
<span class="required">*</span>
</label><br />
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#" >Widerrufsbelehrung</a>.
<span class="required">*</span>
</label><br />
</div><br />
buy<br><br>
no thanks
Finally note the use of a separate stylesheet. Inline styling is a bad idea and should be avoided where possible.

remove this line
$(".checkedterms").change(function(){ //remove
//keep the code that's currently here
}); //remove
leaving you with
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
if ($('.checkedterms:checked').length != $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
the code wasn't running because you were setting an event listener on the checkboxes inside the event listener on the button. what was happening is that when you clicked the button, javascript would set an event listener on the checkboxes that fires when their state changes

You need an if statement at line 2 and one more '='
if ($('.checkedterms:checked').length === $('.checkedterms').length) {
....
}
and you should put an eventListener each input change

Related

How do I validate a radio button with JavaScript?

How do I validate a radio button? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.
Here is the HTML Page
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
So how do I turn the background red when they leave it unchecked?
You need to think of some event the user will fire which you want to trigger the function that makes the background go red. That could be if the user clicks on the next form control. Then when that event fires you test whether they checked any radio buttons. If they did not (!checked) then you set the style attribute of your p element to background:red:
const nextThing = document.querySelector('#next-thing');
const p = document.querySelector('p');
nextThing.addEventListener('click', function(){
const checked = document.querySelector("input[name='f__project']:checked");
if(!checked){
p.setAttribute('style', 'background:red');
}
});
<p id="caption_project">Project Selection
<br/>
<input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
<label for="in_restaurant">LEGO Project</label>
<br/>
<input type="radio" name="f__project" id="in_humber" value="Humber News"/>
<label for="in_humber">Humber Current Project</label>
<br/>
<input type="radio" name="f__project" id="in_self" value="self-determined"/>
<label for="in_self">Self-determined Project</label>
</p>
<button id='next-thing'>Next form control</button>
Use document.querySelector("input[name='f__project']:checked"). If this returns null, none of the radio buttons were checked, and you can display the red background.
If this is in a <form> you can add the required attribute to the radio buttons. If they try to submit the form without selecting one of them, the browser will display a validation error.
Use document.getElementById('id').checkedthe statement returns True or False.
const checkedRadioButton = document.
querySelector("input[name='f__project']:checked");
if (!checkedRadioButton) {
// No values are selected
} else {
// Some value is selected and the element is stored in checkedRadioButton
}
You can use CSS to manipulate the colour depending on whether the radio input is checked or not.
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
border: 5px solid lightblue;
background-color: lightblue;
cursor: pointer;
display: block;
height: 40px;
width: 200px;
text-align: center;
line-height: 40px;
}
input[type="radio"]:checked + label {
border: 5px solid blue;
background-color: dodgerblue;
}
Or else you can make a Javascript function to check
function checkRadioValidity() {
if(document.getElementById('in_restaurant').checked) {
//change CSS here for the element
}
}
The idea of radio button is that it can not be unchecked.
EDIT:
document.querySelector("input[name='f__project']:checked")
will return element if it is checked

Always getting the same value if the checkbox is unchecked also

Input checkbox will be like this
<input id="idCheckbox" name="check" type="checkbox" value="AllValue" style="width: auto; height: auto; font-weight: bolder;" data-bind="checked: idCheckbox" />
Always getting the same value (AllValue) if the checkbox is unchecked also.
var AllPoliciesChk = document.getElementById("idCheckbox").value;
try it, its working fine for me. I have used jquery here is the working example in jsfiddle https://jsfiddle.net/26Ltymkx/
jquery code
var AllPoliciesChk = document.getElementById("idCheckbox").value;
$(document).on('click', '#idCheckbox', function(){
if ($('#idCheckbox').is(":checked")) {
//...your code
}
}
})

how to change text between input tags and align label checbox and icon on one line

I currently have this:
<script type="text/javascript">
$(document).ready(function(){
/* als je selectbox gebruikt doe dan deze:
$("#deliveryType").change(function(){
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
});
*/
$('#deliveryType').click(function() {
$deliveryType = document.getElementById("deliveryType");
if ($(this).is(':checked') == true) {
$deliveryType.value="spoed";
$('#deliveryType').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src","images/rushdeliveryicon.png");
}else{
$deliveryType.value="week";
$('#deliveryType').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src","images/weekdeliveryicon.png");
}
});
});
</script>
<label id="deliverylabel" for="delivery">Leveringsoort
<!-- <select name="deliveryType" id="deliveryType" >
<option value="week">Weeklevering</option>
<option value="rush">Spoedlevering</option>
</select>
-->
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" /></label>
If i click the checkbox then the text between the input tags need to change:
<input name="deliveryType" id="deliveryType" type="checkbox" value="week">Weeklevering</input>
Next to this i also try to get the text of the label and the checkbox + text + icon aligned on 1 line so that it fits like the rest of the input fields on the form. Please have a look:
http://jsfiddle.net/nqm4bpnu/
problem with CSS is that the checkbox input also takes this style:
div.wrapperDiv
{
width:100%;
float:left;
margin-bottom:20px;
}
but it because it is a checkbox it doesnt need to have such a big width.
any ideas
thank you
First thing is <input> doesn't have a closing tag (</input>) so I have changed it to </input>, added a <span> with different id to display the text and changed click to change (this doesn't matter but I prefer change event for check box)
HTML
<label id="deliverylabel" for="delivery">Leveringsoort</label>
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" />
<span id="displayTypeText">Weeklevering</span> <!-- <-----here -->
<img name="deliveryIcon" src="images/weekdeliveryicon.png" style="width:64px;height:64px;" />
JS
$('#deliveryType').change(function () {
if (this.checked) {
this.value = "spoed";
$('#displayTypeText').text("Spoedlevering");
$("img[name=deliveryIcon]").attr("src", "images/rushdeliveryicon.png");
} else {
this.value = "week";
$('#displayTypeText').text("Weeklevering");
$("img[name=deliveryIcon]").attr("src", "images/weekdeliveryicon.png");
}
});
I am not much of a designer but I think you should add a div with float:left around this . Anyways here is a working fiddle,
fiddle
UPDATED
As I have already mentioned I am not a designer but this should get you going (Add it at the end of the CSS script,
#deliveryType{
width:30%!important;
}
updated fiddle
Try using this --
remove 'Weeklevering' from within your input tag
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >Weeklevering</input>
and make html like this,
<input name="deliveryType" id="deliveryType" type="checkbox" value="week" >
<span id="label">Weeklevering</span>
change blow line in your jquery code -
$('#deliveryType').text("Spoedlevering");
to this,
$('#label').html("Spoedlevering");
Note: Do this to both the instances in your jQuery code.
To make all three items in single line, add following css -
#deliverylabel { display: block; text-align: left; width: 100% !important; }
#deliverylabel > input { display: inline-block; margin-left: 15px; vertical-align: middle; width: auto; }
hope this helps.

Linking checkboxes to text inputs and updating its fields

I am trying to link a checkbox to a text input in order to update the value inside the input field.
My problem is how do I update the value accordingly when the checkbox is ticked. For example, I would like to have a text stating status is "Pending" (with the checkbox unticked) and once the box is ticked, update the value to "Completed" and possibly highlight the text input to a green colour.
Picture:
Code:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
Do I need some sort of jQuery to run some sort of input validation?
Would appreciate some help on this.
Thank you.
Try below jquery code(bind .change() event of checkbox) :-
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed')
}
else
{
$("#pending-completed").attr('placeholder','Pending')
}
});
EDIT(Placeholder with green color) :-
Jquery :
$('#statuses').change(function(){
if($(this).is(':checked'))
{
$("#pending-completed").attr('placeholder','Completed').addClass('green-class')
}
else
{
$("#pending-completed").attr('placeholder','Pending').removeClass('green-class')
}
});
CSS :
.green-class::-webkit-input-placeholder {
color: green;
}
DEMO
Try this : bind change event to checkbox and put placeholder as per checkbox checked status.
$(function(){
$('#statuses').change(function(){
var placeholder = $(this).is(':checked')?"Completed":"Pending";
$("#pending-completed").attr('placeholder',placeholder);
});
});
LIVE DEMO: http://jsfiddle.net/don/qaxow1jz/
jQuery:
$('input[name=status]').change(function() {
var inputText = 'input[name=pending-completed]';
if($(this).is(':checked')) {
$(inputText).attr('placeholder', 'Completed').addClass('highlight');
} else {
$(inputText).attr('placeholder', 'Pending').removeClass('highlight');
}
});
HTML:
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
CSS:
input.highlight[name=pending-completed]::-webkit-input-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]::-moz-placeholder {
color: green;
}
input.highlight[name=pending-completed]:-ms-input-placeholder {
color: green;
}
Have a look at this . Working example : http://jsfiddle.net/gmwzzL10/
HTML
<div class="status-updates">
<label class="radio" for="status-updates">
<input type="checkbox" name="status" id="statuses" class="checkbox_status">
</label>
<input type="text" name="pending-completed" id="pending-completed" class="pending-completed" placeholder="Pending">
</div>
JS
$("document").ready(function(){
$(".checkbox_status").click(function(){
var inputBox = $(this).closest(".status-updates").find(".pending-completed");
if($(this).is(':checked')){
inputBox.attr("placeholder","Completed").addClass("make-green");
}
else{
inputBox.attr("placeholder","Pending").removeClass("make-green");
}
})
})
CSS
.make-green{
border: 1px solid green;
}

radio hide. show div class instead. on click of div select linked radio

trying to get this working. Instead of showing the normal radio, or replacing the radio with an image. i would like to replace it with a div i can dress up as a button and on hover the class changes and on click the class changes. but also on click the hidden radio is selected. but also require the label (label in reference to the text showing e.g as below .co.uk .com .net etc.) to be inside the div/button. or be able to add text to the div button. is this possible?
$(function() {
$("input [name='domain_ext']").each(function() {
if ($(this).prop('checked')) {
$(this).hide();
$(this).after($("< class='radioButtonOff' />"));
} else {
$(this).hide();
$(this).after($("<class='radioButtonOn' />"));
}
});
$("input.radio").click(function() {
if($(this).attr('src') == 'radiobuttonOn') {
$(this).attr('src', 'radiobuttonOff');
$(this).prev().attr('checked', 'false');
} else { // its not checked, so check it
$(this).attr('src', 'radioButtonOn');
$(this).prev().attr('checked', 'true');
}
});
});
HTML
<table class="domain_ext_ribbon">
<tr>
<td><label>
<input type="radio" name="domain_ext" value="all" />
All</label></td>
<td><label>
<input type="radio" name="domain_ext" value=".co.uk" />
.co.uk</label></td>
<td><label>
<input type="radio" name="domain_ext" value=".com" />
.com</label></td>
</tr>
<tr>
<td><label>
<input type="radio" name="domain_ext" value=".net" />
.net</label></td>
<td><label>
<input type="radio" name="domain_ext" value=".org" />
.net</label></td>
<td><label>
<input type="radio" name="domain_ext" value=".biz" />
.net</label></td>
</tr>
</table>
css
.radioButtonOff { width: 60px; height: 20px; background: #000000;}
.radioButtonHover { width: 60px; height: 20px; background: #666666;}
.radioButtonOn { width: 60px; height: 20px; background: #999999;}
It looks like you have a bug in your selector; you're missing the opening brace around your attribute filter. So
$("input name='domain_ext']")
should be
$("input [name='domain_ext']")
Also, unless you're using specifically version 1.6 of jQuery, your code should work, but,
if ($(this).prop('checked'))
is the preferred way to check to see if a radio button is checked, as opposed to
if ($(this).attr('checked'))
See this link for more information.
And of course this
$(this).after($("<class='radioButtonOn' />"));
doesn't really make much sense at all. I think you meant:
$(this).after($("<div class='radioButtonOff' />"));

Categories

Resources