problem with checkbox statuses - javascript

I have a problem, and I can't seem to work out how to solve it. I have two checkboxes, both of them have a value of 5. I just need to add the value of 5 to a variable when a checkbox is checked, and deduct 5, when it is unchecked. I've been using jQuery, but so far I've only managed to add 5 and it adds 10, when both of them are checked. It doesn't deduct anything as of now. Since I have a some radio buttons which I properly check, the code I have is this.
$(":checked").each(function(){
if ($(this).attr("type") == "checkbox"){
pricediff += 5;
}
}
as the function each is used, it adds 10 when both of them are checked. This, of course, is not wanted. And it still has to deduct 5 when the checkbox is unchecked. I have no idea how to do that - I'm a bit of a noob to jQuery and JavaScript. Can anyone assist me? Thanks
P.S. this is not the exact code but just the jist of it.

#rahul has a good answer, but this implies all checkboxes must have a value of 5.
Try this demo: http://jsfiddle.net/2WJZ4/
HTML:
<input type="checkbox" class="test" value="5" />
<input type="checkbox" class="test" value="7" />
<input type="checkbox" class="test" value="2" />
<input type="checkbox" class="test" value="1" /><br />
<span id="result">0</span>
Script:
$(function(){
$("input.test").change(function(){
var $this = $(this);
var value = $this.val();
var checked = $this.is(":checked");
if (checked) value = -value;
var $r = $('#result');
$r.text( (+$r.text()) - value)
});
});
PS. #rahul Awesome fiddle page!!!

Sample HTML
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" />
<input type="checkbox" class="test" /><br />
<span id="result">0</span>
Script
$(function(){
$("input:checkbox.test").click(function(){
var checked = $("input:checkbox.test:checked").length;
var checkedValue = checked * 5;
$("#result").text(checkedValue)
});
});
See a working demo

try something like this
var placediff;
function calc()
{
var n = $("input:checked").length;
pricediff = n*5;
}
$(":checkbox").click(calc);

Related

Take value for each check box if checked Javascript

I still learning javascript, i think this is ez question, but i can't fix it with my experience (already try search some source), this my code
This is example:
PHP
<?php
<input type="checkbox" checked="checked" value="1" class="box_1">1</label> // checked
<input type="checkbox" value="2" class="box_1">2</label> //unchecked
<input type="checkbox" checked="checked" value="3" class="box_1">3</label> // checked
<input type="checkbox" value="4" class="box_1">4</label> //unchecked
<input type="checkbox" checked="checked" value="5" class="box_1">5</label> // checked
<input type="button" value="Submit" id="button-price" class="button" />
?>
I try check the check box with javasript by class, (i can't use by name&id because i use looping)
I try build condition like this Javascript :
$('#button-price').bind('click', function() {
var box = '';
$(".box_1").each(function(){ // for each checkbox in class box_1(1-5)
if(this).attr("checked","true"){ // if this checked box is true
var value = (this.value).toLowerCase(); // take the value
box = box + value; // store to box
}
});
});
when click button then take value and store to box,
I know there error in here if(this).attr("checked","true"){
what it should be writing the condition?
Try using prop instead of attr
if($(this).prop('checked')) {
}
Hope this helps.
You can use the jQuery .prop() method to check the checkbox state:
if ($(this).prop("checked")) { // if this checked box is true
box += $(this).val().toLowerCase(); // store to box
}
Suggestion: (this.value).toLowerCase() will work but try not mixing up jQuery code with pure javascript. Instead of it you can use the solution above.

Check/Uncheck using jQuery not working

I am trying to make the check boxes behave like radio buttons in my ASP .NET MVC Web Application. I have got about 20-30 check boxes grouped in two. For Example:
<input type="checkbox" id="#riggingType.RiggingTypeId 1" name="RiggingTypePlus"
value="#riggingType.RiggingTypeId"
checked="#riggingTypeIds.Contains(riggingType.RiggingTypeId)" />
<input type="checkbox" id="#riggingType.RiggingTypeId 2" name="RiggingTypeMinus"
value="#riggingType.RiggingTypeId"
checked="#riggingTypeIds.Contains(riggingType.RiggingTypeId)" />
Goal:
I want to make the check boxes to behave in such a way that if a Plus Check box is checked then the Minus is unchecked automatically and vice versa. I have written following code to try and achieve this functionality:
$(":checkbox").change(function () {
var inputs = $(this).parents("form").eq(0).find(":checkbox");
var idx = inputs.index(this);
if (this.name.substring(this.name.length - 4, this.name.length) === "Plus") {
// just trying to check if I am getting the right it
// and I am getting the right id
// alert(inputs[idx + 1].id);
// But this does not work
$("#" + inputs[idx + 1].id).prop('checked', false);
}
});
Am I doing something wrong here:
$("#" + inputs[idx + 1].id).prop('checked', false);
Any help will be appreciated.
I know that I can use the radio buttons and group them by same name but I am rendering the elements in a loop so they all have the same name but different values and I don't want to name them differently because I am using this data on the server side... Is there a better way to do this?
Answer:
Got this working using the following:
$(document).ready(function(){
$(":checkbox").on('click', function () {
var $this = $(this);
var inputs = $this.closest("form").find(":checkbox");
if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus" && $this.attr('checked')) {
$this.next().prop('checked', false);
}
else
{
$this.prev().prop('checked', false);
}
});
});
Fiddle Link
fiddle: https://jsfiddle.net/24gmnjwm/1/
$(document).ready(function(){
$(":checkbox").on('click', function () {
var $this = $(this);
var inputs = $this.closest("form").find(":checkbox");
if ($this.attr('name').substring(this.name.length - 4, this.name.length) === "Plus") {
$this.next().prop('checked', false);
}
});
});
If we can assume that the "plus" checkbox always appears immediately before its related "minus" checkbox then this will do the trick:
$(":checkbox").change(function () {
if ($(this).prop("name").match(/Plus$/)) {
$(this).next().prop("checked", !$(this).prop("checked"));
} else {
$(this).prev().prop("checked", !$(this).prop("checked"));
}
});
sample form:
<form>
<input type="checkbox" name="RiggingTypePlus" value="2" checked />
<input type="checkbox" name="RiggingTypeMinus" value="2" />
<input type="checkbox" name="RiggingTypePlus" value="3" />
<input type="checkbox" name="RiggingTypeMinus" value="3" />
<input type="checkbox" name="RiggingTypePlus" value="4" />
<input type="checkbox" name="RiggingTypeMinus" value="4" />
<input type="checkbox" name="RiggingTypePlus" value="5" />
<input type="checkbox" name="RiggingTypeMinus" value="5" />
</form>
fiddle

changing the checked attribute of checkbox using jquery

I have to control the checked status a list of checkboxes from another checkbox.
HTML:
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" name="recipe.read" type="checkbox" value="1" rel="read">
<input id="group.read" name="group.read" type="checkbox" value="1" rel="read">
<input id="ingredients.read" name="ingredients.read" type="checkbox" value="1" rel="read">
</div>
JS:
$('#readall').click(function()
{
var checkStatus = $(this).is(':checked');
var checkboxList = $('#permGrid input[rel="read"]');
$(checkboxList).attr('rel', 'read').each(function(index)
{
if(checkStatus == true)
{
$(this).attr('checked', 'checked');
console.log($(this).attr('checked'));
}
else
{
$(this).removeAttr('checked').reload();
console.log($(this).attr('checked'));
}
});
});
The above code seems fine but the check/uncheck works only for the first time. But when I click the main checkbox second time, it doesn't change the status of other checkboxes into 'checked'. Is there anything I need to do?
I found something similar here. I compared the code and mine and this code is somewhat similar but mine doesn't work.
Try using prop, and shorten the code alot like this
$('#readall').click(function () {
var checkboxList = $('#permGrid input[rel="read"]')
checkboxList.prop('checked', this.checked);
});
DEMO
You can't use a method .reload like this
$(this).removeAttr('checked').reload();
// returns Uncaught TypeError: Object #<Object> has no method 'reload'
Remove it, and it will work.
JSFiddle
Use a class for all the checkboxes which you need to change on click of some checkbox. Like:
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
I have added a class="toChange" to all the checkboxes except the first one.
<input id="readall" name="readall" type="checkbox" value="1">
<div id="permGrid">
<input id="recipe.read" class="toChange" name="recipe.read" type="checkbox" value="1" rel="read" />
<input id="group.read" class="toChange" name="group.read" type="checkbox" value="1" rel="read" />
<input id="ingredients.read" class="toChange" name="ingredients.read" type="checkbox" value="1" rel="read" />
</div>
Then use the following script:
$('#readall').click(function(){
var checkStatus = $(this).is(':checked');
if(checkStatus){
$(".toChange").attr('checked', 'checked');
}
else{
$(".toChange").removeAttr('checked')
}
});
Demo

Javascript innerHtml and value for textbox and label issue

I have below javascript code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
var tone = txtone.value;
var lone = lblone.innerHTML;
Now the problem is there are cases when I dont have txtone or lblone in my page so in that case last two lines of my code gives error.
solution for this is to check if they exists might be like this code.
var txtone = document.getElementByID("txtone");
var lblone = document.getElementByID("lblone");
if(txtone)
var tone = txtone.value;
if(lblone)
var lone = lblone.innerHTML;
but In my case I have around 100 to 200 textbox and labels with are rendered based on some condition. So in that case I dont think the give solution will be the best one.
Is there any easy way out to my problem something like prototyping value or innerHtml.
(It is an aspx web site page)
Update answer
Check DEMO http://jsfiddle.net/tD6eC/1/
You can use without class or ID like that.
HTML
<label id="">label 1</label><input id="" value="1" /><br />
<label id="">label 2</label><input id="" value="2" /><br />
<label id="">label 3</label><input id="" value="3" /><br />
<label id="">label 4</label><input id="" value="4" /><br />
<label id="">label 5</label><input id="" value="5" /><br />
<div id="content"></div>
JQUERY
$(document).ready(function(){
var val, label;
$('label').each(function(){
val = $(this).html();
label = $(this).next('input').val();
if(val != 'undefined' && label != 'undefined'){
$('#content').append(val+' : '+label+'<br />');
}
});
});

make checkbox behave like radio buttons with javascript

I need to manipulate the behavior of the check boxes with javascript. They should basically behave like radio buttons (only one selectable at a time, plus unselect any previous selections).
The problem is that I can't use plain radio buttons in first place, because the name attribute for each radio button would be different.
I know its not the ultimate and shiniest solutions to make an apple look like a pear, and w3c wouldn't give me their thumbs for it, but it would be a better solution right now than to change the core php logic of the entire cms structure ;-)
Any help is much appreciated!
HTML :
<label><input type="checkbox" name="cb1" class="chb" /> CheckBox1</label>
<label><input type="checkbox" name="cb2" class="chb" /> CheckBox2</label>
<label><input type="checkbox" name="cb3" class="chb" /> CheckBox3</label>
<label><input type="checkbox" name="cb4" class="chb" /> CheckBox4</label>
jQuery :
$(".chb").change(function() {
$(".chb").prop('checked', false);
$(this).prop('checked', true);
});
if you want user can unchecked selected item :
$(".chb").change(function() {
$(".chb").not(this).prop('checked', false);
});
Demo :
http://jsfiddle.net/44Zfv/724/
There are many ways to do this. This is a clickhandler (plain js) for a div containing a number of checkboxes:
function cbclick(e){
e = e || event;
var cb = e.srcElement || e.target;
if (cb.type !== 'checkbox') {return true;}
var cbxs = document.getElementById('radiocb')
.getElementsByTagName('input'),
i = cbxs.length;
while(i--) {
if (cbxs[i].type
&& cbxs[i].type == 'checkbox'
&& cbxs[i].id !== cb.id) {
cbxs[i].checked = false;
}
}
}
Here's a working example.
This is a better option as it allows unchecking also:
$(".cb").change(function () {
$(".cb").not(this).prop('checked', false);
});
I kept it simple...
<html>
<body>
<script>
function chbx(obj)
{
var that = obj;
if(document.getElementById(that.id).checked == true) {
document.getElementById('id1').checked = false;
document.getElementById('id2').checked = false;
document.getElementById('id3').checked = false;
document.getElementById(that.id).checked = true;
}
}
</script>
<form action="your action" method="post">
<Input id='id1' type='Checkbox' Name ='name1' value ="S" onclick="chbx(this)"><br />
<Input id='id2' type='Checkbox' Name ='name2' value ="S" onclick="chbx(this)"><br />
<Input id='id3' type='Checkbox' Name ='name3' value ="S" onclick="chbx(this)"><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
#DJafari's answer doesn't let unchecking the checkbox. So I've updated it like this:
$(".chb").change(function(e) {
//Getting status before unchecking all
var status = $(this).prop("checked");
$(".chb").prop('checked', false);
$(this).prop('checked', true);
//false means checkbox was checked and became unchecked on change event, so let it stay unchecked
if (status === false) {
$(this).prop('checked', false);
}
});
https://jsfiddle.net/mapetek/nLtb0q1e/4/
Just in case it helps someone else
I was having the same situation where my client needed to have a checkbox behaving like a radio button. But to me it was meaningless to use a checkbox and make it act like radio button and it was very complex for me as I was using so many checkboxes in a GridView Control.
My Solution: So, I styled a radio button look like a checkbox and took the help of grouping of radio buttons.
You could give the group of checkboxes you need to behave like this a common class, then use the class to attach the following event handler:
function clickReset ()
{
var isChecked = false,
clicked = $(this),
set = $('.' + clicked.attr ('class') + ':checked').not (clicked);
if (isChecked = clicked.attr ('checked'))
{
set.attr ('checked', false);
}
return true;
}
$(function ()
{
$('.test').click (clickReset);
});
Note: This is pretty me just shooting from the hip, I've not tested this and it might need tweaking to work.
I would advise that you do look into finding a way of doing this with radio buttons if you can, as radios are the proper tool for the job. Users expect checkboxes to behave like checkboxes, not radios, and if they turn javascript off they can force through input into the server side script that you weren't expecting.
EDIT: Fixed function so that uncheck works properly and added a JS Fiddle link.
http://jsfiddle.net/j53gd/1/
<html>
<body>
<form action="#" method="post">
Radio 1: <input type="radio" name="radioMark" value="radio 1" /><br />
Radio 2: <input type="radio" name="radioMark" value="radio 2" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Ultimately you can use brackets with the name attribute to create an array of radio input like so:
<input type="radio" name="radioMark[]" value="radio1" />Radio 1
<input type="radio" name="radioMark[]" value="radio2" />Radio 2
<input type="radio" name="radioMark[]" value="radio3" />Radio 3
<input type="radio" name="radioMark[]" value="radio4" />Radio 4
What matters to transfer in the end are whats in the value attribute. Your names do not have to be different at all for each radio button. Hope that helps.
In Simple JS.
Enjoy !
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function onChoiceChange(obj) {
// Get Objects
var that=obj,
triggerChoice = document.getElementById(that.id),
domChoice1 = document.getElementById("Choice1"),
domChoice2 = document.getElementById("Choice2");
// Apply
if (triggerChoice.checked && triggerChoice.id === "Choice1")
domChoice2.checked=false;
if (triggerChoice.checked && triggerChoice.id === "Choice2")
domChoice1.checked=false;
// Logout
var log = document.getElementById("message");
log.innerHTML += "<br>"+ (domChoice1.checked ? "1" : "0") + ":" + (domChoice2.checked ? "1" : "0");
// Return !
return that.checked;
}
</script>
</head>
<body>
<h1 id="title">Title</h1>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice1" />Choice #1</label>
<label><input type="checkbox" onclick="onChoiceChange(this)" id="Choice2" />Choice #2</label>
<hr>
<div id="message"></div>
</body>
</html>
try this
<form id="form" action="#">
<input name="checkbox1" type="checkbox" />
<input name="checkbox2" type="checkbox" />
<input name="checkbox3" type="checkbox" />
<input name="checkbox4" type="checkbox" />
<input name="checkbox5" type="checkbox" />
<input name="checkbox6" type="checkbox" />
<input name="checkbox7" type="checkbox" />
<input name="checkbox8" type="checkbox" />
<input name="checkbox9" type="checkbox" />
<input name="checkbox10" type="checkbox" />
<input type="submit" name="submit" value="submit"/>
</form>
and this is the javascript
(function () {
function checkLikeRadio(tag) {
var form = document.getElementById(tag);//selecting the form ID
var checkboxList = form.getElementsByTagName("input");//selecting all checkbox of that form who will behave like radio button
for (var i = 0; i < checkboxList.length; i++) {//loop thorough every checkbox and set there value false.
if (checkboxList[i].type == "checkbox") {
checkboxList[i].checked = false;
}
checkboxList[i].onclick = function () {
checkLikeRadio(tag);//recursively calling the same function again to uncheck all checkbox
checkBoxName(this);// passing the location of selected checkbox to another function.
};
}
}
function checkBoxName(id) {
return id.checked = true;// selecting the selected checkbox and maiking its value true;
}
window.onload = function () {
checkLikeRadio("form");
};
})();
I like D.A.V.O.O.D's Answer to this question, but it relies on classes on the checkbox, which should not be needed.
As checkboxes tend to be related in that they will have the same (field) name, or a name which make them part of an array, then using that to decide which other checkboxes to untick would be a better solution.
$(document)
.on('change','input[type="checkbox"]',function(e){
var $t = $(this);
var $form = $t.closest('form');
var name = $t.attr('name');
var selector = 'input[type="checkbox"]';
var m = (new RegExp('^(.+)\\[([^\\]]+)\\]$')).exec( name );
if( m ){
selector += '[name^="'+m[1]+'["][name$="]"]';
}else{
selector += '[name="'+name+'"]';
}
$(selector, $form).not($t).prop('checked',false);
});
This code on jsFiddle

Categories

Resources