Checkbox need to be checked based on string values - javascript

I am fetching data from LocalStorage as follows
angular.module('madMeApp').controller('campaignInDetails', function($scope) {
var campaignToShow = JSON.parse(localStorage.getItem("CampaignDetails"));
$scope.selectedDays = campaignToShow.selected_days;
});
I am getting selected_days value in a comma separated string e.g. Tuesday,Wednesday
Based on that value of selected_days
I want to be checked the below Checkbox,
<input type="checkbox" value="Monday" name="selected_days" />
<input type="checkbox" value="Tuesday" name="selected_days" />
<input type="checkbox" value="Wednesday" name="selected_days" />
<input type="checkbox" value="Thursday" name="selected_days" />
<input type="checkbox" value="Friday" name="selected_days" />
<input type="checkbox" value="Saturday" name="selected_days" />
<input type="checkbox" value="Sunday" name="selected_days" />
Kindly help me that how to check the checkbox using AngularJs as per the value.
In this condition I want to be checked Tuesday,Wednesday checkbox.
Thanks.

create a function for ng-checked which would return true or false based on you local storage string.
example :
<input type="checkbox" value="Monday" name="selected_days" ng-checked="dayChecker("Monday")" />
In controller
var str = "Tuesday,Wednesday";
$scope.dayChecker = function(day){
if(str.indexOf(day) > 0){
return true;
} else{
return false;
}
}
Hope it would help

Related

the function return the resultat null or undefined

I have a problem I created a function to take the value of the input: check
and to take its value to return this result to write in the h3
html
<input type="radio" name="check" value="2" /> Option 1
<input type="radio" name="check" value="1" /> Option 2`
<h3 id="r" onchange="test1()"></h3>
function test1 (){
var select= document.querySelector('input[name="check"]:checked').value;
return select
}
var selectbox = test1()
document.getElementById('r').innerHTML = selectbox
Add the event listeners to the radio button. Set the element's text when you read the input's value.
function test1() {
var value = document.querySelector('input[name="check"]:checked').value;
document.getElementById('r').textContent = value
}
<input type="radio" name="check" value="2" onchange="test1()" /> Option 1
<input type="radio" name="check" value="1" onchange="test1()" /> Option 2`
<h3 id="r"></h3>
And based on your comment, make a function
function getTheValue () {
return document.querySelector('input[name="check"]:checked').value;
}
function test1() {
document.getElementById('r').textContent = getTheValue();
}
<input type="radio" name="check" value="2" onchange="test1()" /> Option 1
<input type="radio" name="check" value="1" onchange="test1()" /> Option 2`
<h3 id="r"></h3>

Generated form not liking javascript change field value function

I was previously helped to get a javscript function using jquery working - see :
JS Fiddle working example
$("[name='COLUMN35']").on('change', function() {
var val = $(this).val();
var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
$("input[value='" + reverseVal + "']:not([name='COLUMN35'])").prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span>Option 1</span><br />
<form>
<label><input type="radio" name="option1" id="option1Yes" value="Yes">Yes</label>
<label><input type="radio" name="option1" id="option1No" value="No">No</label>
<br /><br />
<span>Option 2</span><br />
<label><input type="radio" name="option2" id="option2Yes" value="Yes">Yes
</label>
<label><input type="radio" name="option2" id="option2No" value="No">No</label>
<hr />
<span>Unsubscribe from all</span><br />
<label><input type="radio" name="COLUMN35" id="unsubYes" value="Yes">Yes</label>
<label><input type="radio" name="COLUMN35" id="unsubNo" value="No">No</label>
<br /><br />
<input type="submit" value="submit">
</form>
Upon implmenting that same code into the generated form page i am not sure why it does not work - see:
Webform with code not working
Unfortunately I am not able to edit the any of the form elements as they are generated automatically but hoping someone might have a different idea to implement - usually the messier the better E.G target the relevant ids to change and maybe not using jquery
try putting your code in $(document).ready(function(){})
eg
$(document).ready(function(){
$("[name='COLUMN35']").on('change', function(){
var val = $(this).val();
var reverseVal = (val == 'Yes' ? 'No' : 'Yes')
$("input[value='"+reverseVal+"']:not([name='COLUMN35'])").prop('checked', true);
});
});

check all checkboxes javascript

I'm trying to have all checkboxes checked (true) when the user clicks on "All" button. I tried this, firstly just to see if "Anglais" could be checked clicking on "All" :
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous
My Javascript :
function checkedAll () {
var checked = false;
var all = document.getElementById('all');
if (checked == false) {
checked = true
}
else {
checked = false
}
var ang = document.getElementById('anglais').checked
if (ang == true) {
ang.checked = true;
}
But the button(s) are not checked when I click on All. I think I don't understand exactly how to use the .checked method..
Maybe, some of my code has not logic, because it was from this example :
https://www.hscripts.com/scripts/JavaScript/select-all-checkbox.php
Couple modifications:
Pass in the all checkbox to the checkedAll method (this allows you to reference it without having to re-find it).
Used document.getElementsByTagName to find the other checkboxes, but you could just as easily use document.getElementById for each one (anglais, allemand, etc.)
Set every other checkbox's checked status to the all.checked value. No need for a true/false comparison.
function checkedAll(allCheckbox){
var allCheckboxes = document.getElementsByTagName('input');
for (var i = 0; i < allCheckboxes.length; i++){
var curCheckbox = allCheckboxes[i];
if (curCheckbox.id != 'all'){
curCheckbox.checked = allCheckbox.checked;
}
}
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll(this)" name="all" id="all" value="Tous" /> Tous
The more explicit way would be:
function checkedAll(){
var isAllChecked = document.getElementById('all').checked;
// Set the other checkboxes .checked property based on the
// .checked status of the `all` checkbox
document.getElementById('anglais').checked = isAllChecked;
document.getElementById('allemand').checked = isAllChecked;
document.getElementById('espagnol').checked = isAllChecked;
document.getElementById('francais').checked = isAllChecked;
}
<input type="checkbox" name="anglais" id="anglais" value="Anglais" /> Anglais
<input type="checkbox" name="allemand" id="allemand" value="Allemand" /> Allemand
<input type="checkbox" name="espagnol" id="espagnol" value="Espagnol" /> Espagnol
<input type="checkbox" name="francais" id="francais" value="Francais" /> Francais
<input type="checkbox" onclick="checkedAll()" name="all" id="all" value="Tous" /> Tous

Pass all checkboxes values as an array in Javascript

I have the below checkboxes and I need to get them as an array values.
<input type="checkbox" id="contact_id" value="4" />
<input type="checkbox" id="contact_id" value="3" />
<input type="checkbox" id="contact_id" value="1" />
<input type="checkbox" id="contact_id" value="5" />
I need to pass them to one ajax request as array as below:
xmlHttp.open("POST","?action=contact&contact_id=" +contacts,true);
I am using this function to get the values but not able to pass them to the function as array, the passed like this 4,3,1,5. I need them to be passed like this
contact_id[]=4&contact_id[]=3&contact_id[]=1&contact_id[]=5
I have done this as follows
function getContacts(){
var contacts = document.myform.contact_id, ids = [];
for (var i = 0; i < contacts.length; i += 1){
if (contacts[i].checked)
ids.push(contacts[i].value);
}
return ids;
}
http://jsfiddle.net/xQezt/
Does this fiddle do what you want? The serialization is naive, but you could find a proper way to do that exact thing elsewhere or by using a framework like Zepto, jQuery or YUI.
First I made a way to "submit" the data. The output goes to the console, so open your firebug. Could go anywhere, though.
//submit event registration
submitButton.onclick = function () {
var contactArray = inputsToArray(contacts.children);
var data = serializeArray(contactArray, 'contact_id[]');
console.log(data);
}
Then I made your method "getContacts" more generic:
function inputsToArray (inputs) {
var arr = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked)
arr.push(inputs[i].value);
}
return arr;
}
Here is the naive serialization function. I do not expect this to work well in all cases, so you should do some research in where to get a good serialization algo from:
function serializeArray (array, name) {
var serialized = '';
for(var i = 0, j = array.length; i < j; i++) {
if(i>0) serialized += '&';
serialized += name + '=' + array[i];
}
return serialized;
}
I also slightly modified your HTML:
<div id="contacts">
<input type="checkbox" value="4" />
<input type="checkbox" value="3" />
<input type="checkbox" value="1" />
<input type="checkbox" value="5" />
</div>
<button id="submit">Submit</button>
Which let me query the DOM like this:
var d=document;
var submitButton = d.getElementById('submit');
var contacts = d.getElementById('contacts');
Your input's id are duplicate. so I recommend you to use name instead of id
For Example, Your HTML will look like this :
<form id='contactform'>
<input type="checkbox" name="contact[]" value="4" />
<input type="checkbox" name="contact[]" value="3" />
<input type="checkbox" name="contact[]" value="1" />
<input type="checkbox" name="contact[]" value="5" />
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Then if you want to get the value to querystring then use the JQuery Serialize
$('#contactform').serialize();
// this will take some thing like this, Example check the second and the fourth
// contact%5B%5D=3&contact%5B%5D=5
jsFiddle : http://jsfiddle.net/Eqb7f/
$(document).ready(function() {
$("#submit").click(function(){
var favorite = [];
$.each($("input[class='check']:checked"), function(){
favorite.push($(this).val());
});
document.getElementById('fav').value = favorite.join(", ");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cd-form-list">
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="A">
<label for="cd-checkbox-1">A for Apple</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-2" class="check" value="B">
<label for="cd-checkbox-2">B for Ball</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-3" class="check" value="C">
<label for="cd-checkbox-3">C for Cat</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-4" class="check" value="D">
<label for="cd-checkbox-4">D for Dog</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-5" class="check" value="E">
<label for="cd-checkbox-5">E for Ear</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-6" class="check" value="F">
<label for="cd-checkbox-6">F for Fish</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-7" class="check" value="G">
<label for="cd-checkbox-7">G for God</label>
</div>
<div>
<input type="checkbox" id="cd-checkbox-8" class="check" value="H">
<label for="cd-checkbox-8">H for Hen</label>
</div>
</div>
<div>
<input type="submit" value="Submit" id="submit">
</div>
<input name="services" id="fav">

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

Categories

Resources