By clicking on box1 change value from box2 - javascript

I need your help, I'm looking for a solution of:
There is a form with several checkboxes, but only 4 of them are important. Here the html code from this 4:
<input name="opt[pool]" id="opt_pool" type="checkbox" class="searchval" value="1" onclick="submit_search()">Pool
<input name="opt[ppool]" id="opt_ppool" type="checkbox" class="searchval" value="1" onclick="submit_search()">PPool
<input name="opt[internet]" id="opt_internet" type="checkbox" class="searchval" value="1" onclick="submit_search()">Internet
<input name="opt[internetw]" id="opt_internetw" type="checkbox" class="searchval" value="1" onclick="submit_search()">InternetW
Here is the jQuery code:
function build_search(skip){
var sparam = '';
var fields = {};
$('.searchval').each(function(index){
if($(this).attr('name')==skip) {}
else if($(this).attr('type')=='checkbox'||$(this).attr('type')=='radio'){
if($(this).prop("checked")){
sparam+=$(this).attr('name')+"="+$(this).attr('value')+"&";
fields[$(this).attr('name')] = $(this).attr('value');
}
}
else if($(this).val()!=undefined&&$(this).val()!=''){
sparam+=$(this).attr('name')+"="+$(this).val()+"&";
fields[$(this).attr('name')] = $(this).val();
}
});
}
Now I would like to intervene - when clicked on pool, this checked with val=1 and ppool unchecked with val=0. And reverse when click on ppool htis checked with val=1 and pool unchecked with val=0.
This works with my code:
var boxesP = $('#opt_pool,#opt_ppool').click(function(){
boxesP.not(this).prop('checked', false);
$("#opt_pool").val( $("#opt_pool")[0].checked ? "0" : "1" );
$("#opt_ppool").val( $("#opt_ppool")[0].checked ? "0" : "1" );
});
But the problem is when i click to other checkboxes, the checked pool with val=1, remains checked but the val=0.
Where is my mistake? Thanks.

I noticed you have an existing onClick function. Would something like this work for you?
<input name="opt[pool]" id="opt_pool" type="checkbox" class="searchval" value="0" onclick="submit_search(this)">Pool
<input name="opt[ppool]" id="opt_ppool" type="checkbox" class="searchval" value="0" onclick="submit_search(this)">PPool
submit_search = function(e){
if($(e).attr('checked') == 'checked'){
$('.searchval').attr('checked',null);
$('.searchval').val(0);
$(e).attr('checked','checked');
$(e).val(1);
}else{
$(e).val(0);
}
}

Related

Uncheck a checkbox and another checkbox will untick

I have two checkboxes in a form. onclick if a checkbox called email is unchecked how can I get the other checkbox to also uncheck (if it is checked) ?
document.getElementById('email').onclick = function() {
if (!this.checked) {
!document.getElementById("other").checked;
} else {
// if not checked ...
}
};
Am I completey barking up the wrong tree? Any help appriciated
To synchronize the checking of the both at the same time you need just to use this.checked of the first clicked one on the checked attribute of the second one like :
document.getElementById("other").checked = this.checked;
NOTE : That will work on one way, what means the check will be synchronized just when you click on the first checkbox that you've attached the click event to.
document.getElementById('email').onclick = function() {
document.getElementById("other").checked = this.checked;
};
<input id="email" type="checkbox" /> CHECKBOX 1
<br>
<input id="other" type="checkbox" /> CHECKBOX 2
You can make it like :
<form id="test" action="#" method="post">
<div>
<input type="checkbox" name="check" id="check"/>
</div>
<div>
<input type="checkbox" name="check2" id="check2"/>
</div>
</form>
document.getElementById('check').onclick = function() {
if (!this.checked) {
document.getElementById("check2").checked = false;
} else {
// other logic ...
}};
Test it online on jsfiddle : https://jsfiddle.net/3dtq0w8x/
In your test code you are not setting the checked property of "other" to any value.
You are just reading its value, then inverting it (with !).
You could try:
document.getElementById("other").checked = false;
You can add event listener to email checkbox (which is a good practice) and then check if it is check or not and deal with the other checkbox according to that
For example
var ckb = document.getElementById('email')
ckb.addEventListener("click", function(e){
if(!e.target.checked)
document.getElementById('ot').checked = false;
})
<input type="checkbox" name="na" value="email" id="email">Email<br>
<input type="checkbox" name="na" value="other" id="ot">Other
This should help
function check() {
if(document.getElementById("email").checked){
document.getElementById("other").checked = true;
}else{
document.getElementById("other").checked = false;
}
}
HTML
<input type='checkbox' id='email' name='checkbox' onclick="check()" >email
<input type='checkbox' id='other' name='checkbox'>other

Adding and removing from count when checkbox is checked/unchecked with javascript/jquery?

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" />

update text of textbox on check of checkbox

<input type="checkbox" id="one" onclick="updatebox()"/>1
<input type="checkbox" id="two" onclick="updatebox()"/>2
<input type="checkbox" id="three" onclick="updatebox()"/>3
<input type="text" id="tbtb"/>
I have 3 checkboxes and a textbox. I want that when all checkboxes are checked the textbox value would be like "123" and if one of them is not checked the value should go like "12" or "13" or "23". I dont need comma for this, I just need these to use as conditional values.
To be specific here I want that they would still be in order though they are not checked consecutively in order. I need the java script function for this
and also when they will be unchecked the textbox should not contain the value they have. like when all are checked then u uncheck #1 the value should be "23". "1" should be removed on the text. coz right now the code i have that:
var one = document.getelementbyID('one');
var textbox = document.getelementbyID('tbtb').value;
if (one.checked)
{
textbox = textbox + "1";
}
so what's happening here is everytime a checkbox is checked and unchecked simultaneously the value of textbox keep adding another "1" it goes like "2311111". PLEASE HELP :)
This will work:
var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');
var textbox = document.getElementById('tbtb');
function updatebox(){
var str = "";
if(one.checked)
str+="1";
if(two.checked)
str+="2";
if(three.checked)
str+="3";
textbox.value = str;
}
<input type="checkbox" class="chk" id="one" onclick="updatebox()"/>1
<input type="checkbox" class="chk" id="two" onclick="updatebox()"/>2
<input type="checkbox" class="chk" id="three" onclick="updatebox()"/>3
<input type="text" id="tbtb"/>
Please try this:
function updatebox()
{
var textbox = $('#tbtb').val();;
if($('#one').prop('checked')) {
$("#tbtb").val(textbox + "1");
}
if($('#two').prop('checked')) {
$("#tbtb").val(textbox + "1");
}
if($('#three').prop('checked')) {
$("#tbtb").val(textbox + "1");
}
}
and HTML part is:
<input type="checkbox" id="one" onclick="updatebox()"/>1
<input type="checkbox" id="two" onclick="updatebox()"/>2
<input type="checkbox" id="three" onclick="updatebox()"/>3
<input type="text" id="tbtb"/>
Try this one.
JS:
function updatebox() {
var arrCheckbox = document.querySelectorAll('input[name=common-check]:checked');
var textBox = document.getElementById("tbtb");
var strCheck = "";
for(var i=0;i < arrCheckbox.length;i++){
strCheck+=arrCheckbox[i].getAttribute('check');
}
textBox.value = strCheck
}
HTML :
<input type="checkbox" name="common-check" id="one" onclick="updatebox()" check="1"/>1
<input type="checkbox" name="common-check" id="two" onclick="updatebox()" check="2"/>2
<input type="checkbox" name="common-check" id="three" onclick="updatebox()" check="3"/>3
<input type="text" id="tbtb"/>
Here is the Plunker
try this
javascript
function updatebox()
{
var one = document.getElementById('one');
var two = document.getElementById('two');
var three = document.getElementById('three');
var textbox = document.getElementById('tbtb');
var str = "";
if(one.checked)
str+=one.value;
if(two.checked)
str+=two.value;
if(three.checked)
str+=three.value;
textbox.value = str;
}
HTML
<input type="checkbox" value="1" id="one" onclick="updatebox()"/>1
<input type="checkbox" value="2" id="two" onclick="updatebox()"/>2
<input type="checkbox" value="3" id="three" onclick="updatebox()"/>3
<input type="text" id="tbtb"/>

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

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