How to select a MultipleChoice option based on text variable - javascript

I have a MultipleChoiceField and a variable my_choice = 'mystring'
I want check the option relative to my_choice
Here my html:
ul id="id_layer_select"><li><label for="id_layer_select_0"><input checked="checked" id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
here my javascript:
var my_choice = 'mystring'
var opt = $("#id_layer_select option");
opt.filter("[value=my_choice]").attr("selected", true);
I can use jquery. Thank you
PS: Off course mystring is an option Mychoice1 or Mychoice2 or etc.
I don't want use the id_layer_select_x and I prefer to not add and attribute.
The problem is that the checkbox stay unchecked and
console.log(opt)=Object { length: 0, prevObject: Object[1] }

You can filter all spans by the text they contain. You can then get the previous element and have it checked.
$(document).ready(function() {
var txt = "Mychoice3";
var labelMatchingTxt = $('#id_layer_select span').filter(function(i, el) {
return txt === el.childNodes[0].nodeValue; // avoiding DOM reselection.
}).prev().prop('checked', true);
});
<head><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></head>
<body>
<ul id="id_layer_select"><li><label for="id_layer_select_0"><input id="id_layer_select_0" name="layer_select" type="checkbox" value="1" /> <span style='font-weight:normal'>Mychoice1</span></label></li>
<li><label for="id_layer_select_1"><input id="id_layer_select_1" name="layer_select" type="checkbox" value="2" /> <span style='font-weight:normal'>Mychoice2</span></label></li>
<li><label for="id_layer_select_2"><input id="id_layer_select_2" name="layer_select" type="checkbox" value="3" /> <span style='font-weight:normal'>Mychoice3</span></label></li> [...]</ul>
</body>

Related

How to get Selected Checkbox value by ID

Currently my code works well with the input name, I can get the input value by input name
But I want my script to retrieve the input value with id input and not with name input?
here my code :
$(document).ready(function () {
$('input[type="checkbox"]').click(function () {
getSelectedCheckBoxwithValueText("test")
});
var getSelectedCheckBoxwithValueText = function (name1) {
var data = $('input[name="' + name1 + '"]:checked');
if (data.length > 0) {
var resultdata='' ;
data.each(function () {
var selectedValue = $(this).val();
resultdata += $('label[for="cb-' + selectedValue + '"]').text() + "<br/>";
});
$("#divchecked").html(resultdata);
}
else {
$("#divchecked").html("No Check box selected");
}
};
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="cb-cricket">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="cb-swimming">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="cb-blog">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="cb-coding">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>
</body>
jsfiddle: https://jsfiddle.net/showcode/L64nauo0/5/
You can use
var data = $('input[id=^"c"]:checked');
Only if the IDs not pseudos (so you really this IDs use), and do not use IDs thagt starts with c
This is a little hacker solution, but works!
There is no need to use id or name to select the checkboxes and/or their related labels. You can simplify your code like so
Select all the checkboxes from the DOM and listen to change event on them.
When the value of a checkbox changes, you get all selected checkboxes
using .filter().
And then get the text of the related labels using .map() and .get().
$(document).ready(function () {
let $checkboxes = $('input[type="checkbox"]');
$checkboxes.change(function () {
let labels = $checkboxes.filter(':checked').map(function(){
return $(this).next('label').text().trim();
}).get();
$("#divchecked").html(labels.join('<br />') || "No Check box selected");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
checked:
<input type="checkbox" id="c1" name="test" value="cricket" />
<label for="c1">Cricket</label>
<input type="checkbox" id="c2" name="test" value="swimming" />
<label for="c2">Swimming</label>
<input type="checkbox" id="c3" name="test" value="blog" />
<label for="c3">Blog</label>
<input type="checkbox" id="c4" name="test" value="coding" />
<label for="c4">Coding</label>
<br/>
<br/>
Selected checkbox:<br />
<div id="divchecked"></div>

jQuery, collecting checkboxes and put selected ones to array, is that possible?

I want to collect checked checkboxes (values) with a classname and put them into an array. Just like that one:
var a = new Array();
$('.categoriesCb').each(function(i, item) {
if ($(item).prop('checked'))
{
a.push($(item).val());
}
alert(JSON.stringify(a));
});
my problem is its a bit big. Cant it be done with one-line?11
You can use .map() function along with .get(). You can also eliminate paramete item and use context this:
var a = $('.categoriesCb:checked').map(function(){
return $(this).val();
}).get();
Use jQuery.map()
$('.categoriesCb:checked').map(function() {
return this.value;
}).get();
another way is to use jQuery.makeArray() with .map():
var arr = jQuery.makeArray($(':checked').map(function(){ return this.value; }));
$('pre').html(JSON.stringify(arr));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />
<br>
<pre></pre>
Just a pure JS single liner. Note that node list to array conversion with the spread operator works fine in Firefox but with Chrome it's only possible with v51 on. Otherwise you will have to go with the good old Array.prototype.map.call(document.querySelectorAll("input[type=checkbox][checked]"), e => e.value) method.
var arr = [...document.querySelectorAll("input[type=checkbox][checked]")].map(e => e.value);
console.log(JSON.stringify(arr));
<input type="checkbox" checked name="options" value="1" />
<input type="checkbox" name="options" value="2" />
<input type="checkbox" name="options" value="3" />
<input type="checkbox" checked name="options" value="4" />
<input type="checkbox" checked name="options" value="5" />

De-selecting a select all checkbox

I have a checkbox that will select all, at the moment if I press it, it will select all the the options(which is good!), then if I deselect one of them it doesn't deselect the Select All option. Any help in how to do this would be gratefully appreciated.
<span class="glyphicon glyphicon-check"></span>
<label for="sel1">Select days:</label><br />
<li>
<input type="checkbox" name="all" id="all" />
<label for='all'>Select All</label>
<ul>
<ul>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_1" value="1" />
<label for="box_1">Monday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_2" value="2" />
<label for="box_2">Tuesday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_3" value="3" />
<label for="box_3">Wednesday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_4" value="4" />
<label for="box_4">Thursday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_5" value="5" />
<label for="box_5">Friday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_6" value="6" />
<label for="box_6">Saturday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_7" value="7" />
<label for="box_7">Sunday</label>
</li>
</ul>
</ul>
</li>
</div>
Script I am currently using to Select All:
$(document).ready(function(){
$('input[name="all"],input[name="title"]').bind('click', function(){
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).prop('checked', status);
});
});
$(document).ready(function){
}
Example:
http://jsfiddle.net/0e018w0y/
You're most of the way there.
I'd attach a "change" event listener to all the checkboxes, confirming that (on change) whether all the checkboxes are selected or not... (FYI you're using checkboxes and not radio buttons. Radio buttons only allow 1 to be selected at a time.)
// On change of any (not "Select All" checkbox)
$('input[name="selected[]"]').change(function () {
var selectAll = true;
// Confirm all checkboxes are checked (or not)
$('input[name="selected[]"]').each(function (i, obj) {
if ($(obj).is(':checked') === false) {
// At least one checkbox isn't selected
selectAll = false;
return false;
}
});
// Update "Select All" checkbox appropriately
$('input[name="all"]').prop('checked', selectAll);
});
In the example I've tried to follow your convention for checking if things are selected or not etc - except I've used "change()" rather than "click()" (which captures any change event, not just mouse-clicks).
Line by line:
$('input[name="selected[]"]').change(function () {
...
}
This captures the change event on all select boxes. You could use classes or a name convention to identify the checkboxes to attach it to.
var selectAll = true;
The scope of this variable reaches the nameless function provided to the .each(...) call which follows. We're using this to track whether every checkbox is checked or not.
$('input[name="selected[]"]').each(function (i, obj) {
if ($(obj).is(':checked') === false) {
// At least one checkbox isn't selected
selectAll = false;
return false;
}
});
This checks every checkbox, see if any are not checked.
Then we update the "Select All" checkbox appropriately.
Looking at it again (2 minutes later), I can see this could be reduced actually:
var allSelected = ($('input[name="selected[]"]:not(:checked)').length === 0);
// Update "Select All" checkbox appropriately
$('input[name="all"]').prop('checked', allSelected);
I've not tested if this is faster ... I've just offloaded the checking of "is checked" to jQuery itself. The "length" property returns how many elements match the criteria - ":not(:checked)" does what you'd expect, matches only the aforementioned inputs which are not checked.
If the count is not equal to 0, we deselect the "Select All" checkbox.
Example:
http://jsfiddle.net/zyxgm2kz/
Try this:
You need to bind a change listener for all the days checkbox and if all the checkboxes are checked then you can play with select all checkbox checked property.
$(document).ready(function () {
var allCB = $('input[name="selected[]"]');
var mainCB = $('input[name="all"]')
mainCB.on('click', function () {
var status = $(this).is(':checked');
allCB.prop('checked', status);
});
allCB.on('change', function () {
var status = $('input[name="selected[]"]:checked').length === allCB.length;
$('input[name="all"]').prop('checked', status);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<li>
<input type="checkbox" name="all" id="all" />
<label for='all'>Select All</label>
<ul>
<ul>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_1" value="1" />
<label for="box_1">Monday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_2" value="2" />
<label for="box_2">Tuesday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_3" value="3" />
<label for="box_3">Wednesday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_4" value="4" />
<label for="box_4">Thursday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_5" value="5" />
<label for="box_5">Friday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_6" value="6" />
<label for="box_6">Saturday</label>
</li>
<li class="moveli">
<input type="checkbox" name="selected[]" id="box_7" value="7" />
<label for="box_7">Sunday</label>
</li>
</ul>
</ul>
</li>
you can try this one:
$(document).ready(function() {
$('input[name="all"],input[name="title').click(function(event) { //on click
if(this.checked) {
$('input[type="checkbox').each(function() {
this.checked = true;
});
}else{
$('.input[type="checkbox').each(function() {
this.checked = false;
});
}
});
});
DEMO FIDDLE
$('input[name="all"],input[name="title"]').bind('click', function () {
var status = $(this).is(':checked');
$('input[type="checkbox"]', $(this).parent('li')).prop('checked', status);
});
var checkbox = $(':checkbox').not('#all');
$(checkbox).change(function () {
checkbox.each(function () {
if ($(this).is(':checked')) {
} else {
$(':checkbox#all').prop('checked', false)
}
})
})
Get the checkbox except the all then check if one is uncheck remove the check from all
DEMO

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

JQuery select label of selected checkboxes

When I click a button I want to get the value from each of the checked check boxes. I really just want to populate an array with all the check boxes that are checked.
I started a simplified example here: http://jsfiddle.net/kralco626/JvAdg/1/
The actual code is more like this:
var dataList = new Array(10);
dataList[0] = "Delete";
dataList[1] = LD_LicenseNumber.val();
dataList[2] = $("#LDOperatingCompanies input:checked").val();
And aspx code:
<div id="LDOperatingCompanies">
<input type="checkbox" value="o1" id="o1" name="LDOperatingCompanies" /><label for="o1">o1</label>
<input value="o2" type="checkbox" id="o2" name="LDOperatingCompanies" /><label for="o2">o2</label>
<input value="o3" value="o1" type="checkbox" id="o3" name="LDOperatingCompanies" /><label for="o3">o3</label>
</div>
Thanks!
here is an update to your fiddle that puts all checked boxes into an array Example
HTML
<div id="LDOperatingCompanies">
<input type="checkbox" id="o1" name="LDOperatingCompanies" /><label for="o1">o1</label>
<input type="checkbox" id="o2" name="LDOperatingCompanies" /><label for="o2">o2</label>
<input type="checkbox" id="o3" name="LDOperatingCompanies" /><label for="o3">o3</label>
</div>
<input type="button" id="btn" value="alert checked boxes" />
JavaScript
var checks = [];
$('#btn').click(function(e) {
$(':checked').each(function(index, item) {
checks.push( item );
});
if(checks.length == 0) alert('nothing checked');
else alert(checks);
});

Categories

Resources