How to check checkboxs based on text string HTML/JS - javascript

Is it possible to check checkbox based on string text using js or jQuery:
$(':checkbox').filter(function() {
return $(this).parent().next('label').text() === 'Text 1';
}).prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>
(JSFiddle)

A JS example. It grabs the labels, finds the label with the text you pass in as an argument to the function, and if that label is found checks it's corresponding checkbox.
function checkBoxFromLabelText(str) {
// Select all the labels and coerce the array-like node-list
// into an array
const labels = [...document.querySelectorAll('label')];
// `find` the label with the text content you supplied
// as a string argument to the function
const label = labels.find(label => label.textContent.trim() === str);
// If it exists find the label's checkbox and check it
if (label) label.querySelector('[type="checkbox"]').checked = true;
}
checkBoxFromLabelText('Text 1');
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

Your code is almost there, you just need to remove next('label') as parent() already gives you a reference to the label.
Also note that you can make the code a little more succinct with an arrow function:
$(':checkbox').filter((i, el) => $(el).parent().text().trim() === 'Text 1').prop('checked', true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="selectit"><input value="171" type="checkbox" name="post_category[]" id="in-category-171">Text 1</label>
<label class="selectit"><input value="172" type="checkbox" name="post_category[]" id="in-category-172">Text 2</label>
<label class="selectit"><input value="173" type="checkbox" name="post_category[]" id="in-category-173">Text 3</label>

Related

select only one checkbox in a group not working 100%

I'm trying to make it where the user can only select 1 checkbox at a time on a page.
Here's my code so far:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active', 'inactive',
'showall')
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
What keeps happening is it will work sometimes and sometimes they can select more than 1 checkbox. What do I need to tweak to get it working all the time.
HTML DOM getElementsByName() Method Gets all elements with the specified name
So In your code It's getting only the first name active ;
as a result the length of the list of checkboxs is 1 this is why your code doesn't work correctly.
If you want to make sure that what i am saying is true change your code to this and your logic will work just fine:
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('active');
checkboxes.forEach((item) => {
if (item !== checkbox)
item.checked = false;
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="active" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
As the others recommended use the radio buttons it's much easier I just wanted to clear this for you.
EDIT :
If you still want to use checkbox use querySelectorAll instead of your getElementsByName
var checkboxes = document.querySelectorAll('[name="active"], [name="inactive"], [name="showall"]');
You can use radio buttons to do this, it needs no JavaScript and is supported by pretty much everything, Internet Explorer included. They can be used like so:
<div>
<strong>Active</strong>
<input type="radio" name="select" id="active" checked> <!-- Checked means that it is initially selected -->
</div>
<div>
<strong>Inactive</strong>
<input type="radio" name="select" id="inactive">
</div>
<div>
<strong>Show All</strong>
<input type="radio" name="select" id="showall">
</div>
Notice how because they are all technically the same input, they all have to have the same name, but you can instead use IDs to tell between them if you really need to.
Using radio buttons would be the preferred choice. But if you do want to use checkboxes, you can use the following approach.
<strong>Active</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="chkbox" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="chkbox" value="Yes" onclick="onlyOne(this)">
<script>
function onlyOne(checkbox) {
var checkboxes = document.getElementsByName('chkbox')
checkboxes.forEach((item) => {
item.checked = false
})
checkbox.checked = true
}
</script>
Note that the name attribute for all the input fields are the same.
getElementsByName() only takes one argument. The other arguments you're giving are being ignores, so you're only processing the active checkbox.
Give all your checkboxes the same class, and use getElementsByClassName() instead.
function onlyOne(checkbox) {
var checkboxes = Array.from(document.getElementsByClassName('radio'))
checkboxes.forEach((item) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes" class="radio" onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" class="radio" onclick="onlyOne(this)">
You are using getElementsByName incorrectly as you can only pass one name to it and it is not an Array so you can't forEach it.
You can use querySelectorAll to query by multiple names and use forEach from the Array prototype.
function onlyOne(checkbox) {
var checkboxes = document.querySelectorAll('[name=active],[name=inactive],[name=showall]')
Array.prototype.forEach.call(checkboxes, (item,i) => {
if (item !== checkbox) item.checked = false
})
}
<strong>Active</strong>
<input type="checkbox" name="active" value="Yes" onclick="onlyOne(this)">
<strong>Inactive</strong>
<input type="checkbox" name="inactive" value="Yes"
onclick="onlyOne(this)">
<strong>Show All</strong>
<input type="checkbox" name="showall" value="Yes" onclick="onlyOne(this)">
While using a radio button control might be the way to go, that just really a comment and not an answer.

retrieved data from db to textarea and radio type

how to retrieved data from db to radio type
<div class="form-check">
<input class="form-check-input" name="jenis" id="radio3"
onclick="enableTxtBox1()" type="radio" value="Cuti Tahunan" />
<label class="form-check-label">CUTI TAHUNAN</label>
</div>
<div class="form-check">
<input class="form-check-input" name="jenis" id="radio4"
onclick="enableTxtBox1()" type="radio" value="Cuti Sakit"/>
<label class="form-check-label">CUTI SAKIT</label>
</div>
<script>
$('#ModalCenter').on('show.bs.modal', function(e) {
var jenis = $(e.relatedTarget).data('jenis');
$(e.currentTarget).find('input[name="jenis"]').val(jenis);
});
</script>
In your case, you should find the element by id instead of name, i.e.:
$(e.currentTarget).find('input[id="radio3"]').val(jenis);
$(e.currentTarget).find('input[id="radio4"]').val(jenis);
Setting value using $(..).val() to textarea is fine, bu not for Checkbox or Radio. You need to use attr method of the input selector
Do this to update check / uncheck it
$(...).attr('checked', true);
/// to uncheck,
$(...).attr('checked', false);
To make it more dynamic, you can check input type using the below code
var isCheckboxOrRadio = $(...).is(':radio, :checkbox');
console.log(isCheckboxOrRadio); // result will be true or false
You can add the checkedattribute if the value retrieved from the database is the value of the radio.
<div class="form-check">
<input class="form-check-input" name="jenis" id="radio3"
onclick="enableTxtBox1()" type="radio" value="Cuti Tahunan"
<?php echo $data_retrieved['jenis'] == 'Cuti Tahunan' ? 'checked': '' ; />
<label class="form-check-label">CUTI TAHUNAN</label>
</div>
<div class="form-check">
<input class="form-check-input" name="jenis" id="radio4"
onclick="enableTxtBox1()" type="radio" value="Cuti Sakit"
<?php echo $data_retrieved['jenis'] == 'Cuti Sakit' ? 'checked': '' ; />
<label class="form-check-label">CUTI SAKIT</label>
</div>

dynamic variable name from form input name

How would i create a dynamic variable name based on all the forms input checkbox list names? This is what i have so far
var nameArray = [];
$.each($("#store-filter input").serializeArray(), function(i, field) {
nameArray[field.name] = field.value;
});
alert(nameArray[0]);
for (i = 0; nameArray.length > i; i++)
{
//alert(nameArray[i]);
var nameArray[i] = nameArray[i].value;
var nameArray[i]+'_checked_values' = $(\'input[name="nameArray[i]+[]"]:checked\').map(function() {
return this.value;
}).get();
}
alert(make); //variable name from name="make[]"
sample HTML
<form id="store-filter" action:"javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
so later on in my code i can create a url string ?make=1,2,3&store=40,5,6&time=1,2,3,4 etc
the $_GET parameters are taken from the input check boxes name's dynamically
I'd suggest the following approach, obviously I'm binding to the click of a button, you should add that to the event/interaction of your choice:
function makeQueryString() {
function keyValues(idPref) {
// using the pass-in 'id' as a key:
var key = idPref,
// searching within the element identified with that 'id' for
// other elements whose 'id' *starts* with that string:
values = $('#' + idPref + ' input[id^="' + idPref + '"]').map(function() {
// iterating over those found elements and, if the value is *not* the
// defaultValue (value on page-load), *or* the checked state is not the
// default state (checked/unchecked as on page-load):
if (this.value !== this.defaultValue || this.checked !== this.defaultChecked) {
// we return the value:
return this.value;
}
// get() converts to a JavaScript Array, join() concatenates Array elements
// to form a string:
}).get().join(',');
// if there is a key, and there are associated values, we return a 'key=value,value2'
// string, otherwise we return an empty string:
return key && values.length ? key + '=' + values : '';
}
// we return the value obtained after iterating over the form's span elements
// that have an [id] attribute:
return $('form span[id]').map(function(){
// obtaining the 'key=value1,value2' strings from the called-function:
return keyValues(this.id);
// converting those returned elements into an Array, and joining with & characters:
}).get().join('&');
}
$('#test').click(function(e) {
e.preventDefault();
console.log(makeQueryString());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="test">test</button>
<form id="store-filter" action: "javascript:void(0);">
<span id="store">
<input id="store_0" value="2" name="store[]" type="checkbox"> <label for="store_0">Store 1</label>
<input id="store_1" value="3" name="store[]" type="checkbox"> <label for="store_1">Store 2</label>
<input id="store_2" value="3" name="store[]" type="checkbox"> <label for="store_2">Store 3</label>
</span>
<span id="make">
<input id="make_0" value="2" name="make[]" type="checkbox"> <label for="make_0">make
1</label>
<input id="make_1" value="3" name="make[]" type="checkbox"> <label for="make_1">make
2</label>
<input id="make_2" value="4" name="make[]" type="checkbox"> <label for="make_2">make
3</label>
</span>
<span id="time">
<input id="time_0" value="2" name="time[]" type="checkbox"> <label for="time_0">time 1</label>
<input id="time_1" value="3" name="time[]" type="checkbox"> <label for="time_1">time 2</label>
<input id="time_2" value="4" name="time[]" type="checkbox"> <label for="time_2">time 3</label>
</span>
</form>
References:
CSS:
Attribute-presence and value ([attribute],[attribute="value"]) selectors.
JavaScript:
Array.prototype.join().
defaultChecked and defaultValue (HTMLInputElement).
jQuery:
get().
map().
You are in Javascript, you do not need to declare the size of your arrays, there is no propblems by adding/removing anything from an Object/Array.
You should create a variable make then get the values in. Finally, you will be able to get it back.
var make;
$.each($("#store-filter input").serializeArray(), function(i, field) {
make[i] = field.name;
});
Later in your code, you will use the array make.
make[0];
EDIT:
Here is an example i did for you: http://jsfiddle.net/kjkzm8qm/
NOTE: Your $.each($("#store-filter input").serializeArray() ... is useless, you should select all your inputs by adding a class AND, you should END your input tags by adding a / at the end.
HTML
<input name="test" class="inputs" />
JAVASCRIPT
$.each($(".inputs"), function(){ });
Update for david's answer.
If you want to remove & then add this code below
For this check the key value is not null
let keyValue = keyValues(this.id);
if (keyValue != ''){
return keyValue;
}

Javascript: get radiobutton label with a specific "for" in label

I have a form element like this:
<div id="myformelement">
<input type="radio" id="option1">
<label for="option2">Option 1</label>
<input type="radio" id="option2">
<label for="option2">Option 2</label>
<input type="radio" id="option3">
<label for="option3">Option 3</label>
<input type="radio" id="option4">
<label for="option4">Option 4</label>
</div>
I want to hide the input fields "option2" and "option3" and their labels.
I can hide the input bullets by addressing the id. Unfortunately the corresponding labels to the input fields only have a "for" tag with the id in it.
How can I do this with javascript (no jquery).
I found this question (Find html label associated with a given input), but this seems only to work with one label within an ID, I can not use this.
Thanks in advance!
Kind regards,
Malte
In pure JavaScript you can use querySelector:
document.querySelector("label[for='option2']").style.display = "none";
You can do it with nextSibling:
var rdo = document.getElementById("option2");
var lbl;
rdo.style.display = "none";
for (lbl = rdo.nextSibling; lbl && lbl.nodeName.toUpperCase() !== "LABEL"; lbl = lbl.nextSibling) {
}
if (lbl) {
lbl.style.display = "none";
}
But I have a better option for you: It seems to be a well-kept secret that label elements can contain the input they relate to, and when they do no for is required at all. So if you change your HTML to:
<div id="myformelement">
<label><input type="radio" id="option1"> Option 1</label>
<label><input type="radio" id="option2"> Option 2</label>
<label><input type="radio" id="option3"> Option 3</label>
<label><input type="radio" id="option4"> Option 4</label>
</div>
...it gets a lot easier:
document.getElementById("option2").parentNode.style.display = "none";
You just find the input, traverse up to its parent which is the label, and hide that (which will hide the input as well).

I have multiple checkboxes, and want to make a rule for 2 of them so that if I select 1 the other cannot be selected

​<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
Those are the checkboxes , I have tried to search all over the internet and didn't find anything.
I want to allow the user to check id 3 and 4 BUT if he checks 1 , then 2 is not available to check, or if he checks 2 then 1 is not available to check.
And to the unavailable to add a class .. named ..
grade-out{ color: #DDD;}
Hope u understand the problem. Thanks in Advance !!
I would add data-groupid attribute to your checkboxes to identify which group they belong to. And then add a click handler to checkboxes belonging to group, which would disable all other checkboxes in the same group when checked and enable them when unchecked..
Assumming your markup is consistent and labels are always predecessors of respective checkboxes, you can easily target them using the prev() method.
$('input:checkbox[data-group]').click(function() {
var groupid = $(this).data('group');
var checked = $(this).is(':checked');
if(checked) {
$('input:checkbox[data-group=' + groupid + ']').not($(this))
.attr('disabled', 'disabled')
.prev().addClass('grade-out');
} else {
$('input:checkbox[data-group=' + groupid + ']')
.removeAttr('disabled')
.prev().removeClass('grade-out');
}
});
DEMO
I would assign an attribute data-disable to disable certain elements and check onchange.
This is how I would do it:
<form>
<label for="1">Text 1</label>
<input type="checkbox" name="1" value="something1" id="1" data-disable="2,3"><br>
<label for="2">Text 2</label>
<input type="checkbox" name="2" value="something2" id="2" data-disable="1"><br>
<label for="3">Text 3</label>
<input type="checkbox" name="3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input type="checkbox" name="4" value="something4" id="4">
</form>​​​
and script:
$('input:checkbox​​​​​​​​​​​​​​​​​​')​.on('change', function(){
var toUncheck = $(this).attr('data-disable');
var self = $(this);
$.each(toUncheck.split(','), function(el, val){
if(self.attr('checked') == 'checked'){
$('#'+val).attr('disabled', 'disabled');
} else {
$('#'+val).removeAttr('disabled');
}
});
});​
JSFiddle Demo
You could use radio form inputs. Anyway, if it's a must to use checkboxes then you could use some javascript (with jQuery, for example)
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('checked',false);
});
It this what you're looking for?
Re-worked example: demo fiddle
$('#1,#2').click(function(){
var $this = $(this);
var theOtherId = $this.attr('id') == 1 ? 2 : 1;
var theOtherOne = $('#'+theOtherId);
if( $this.is(':checked') ) theOtherOne.attr('disabled',true);
else theOtherOne.attr('disabled',false);
});
Although there are more complex and flexible solutions above if you wish a solid but clear usage sample look at this. Using id's make things easier.
http://jsfiddle.net/erdincgc/uMhbs/1/
HTML (added class and id) ;
<form>
<label for="1">Text 1</label>
<input class="checks" type="checkbox" id="option1" name="option1" value="something1" id="1"><br>
<label for="2">Text 2</label>
<input class="checks" type="checkbox" id="option2" name="option2" value="something2" id="2"><br>
<label for="3">Text 3</label>
<input class="checks" type="checkbox" id="option3" name="option3" value="something3" id="3"><br>
<label for="4">Text 4</label>
<input class="checks" type="checkbox" id="option4" name="option4" value="something4" id="4">
</form>
And JS
$('.checks').click(function(){
op1 = $('#option1') ;
op2 = $('#option2') ;
this_id = $(this).attr("id") ;
this_state = $(this).attr("checked");
if(this_id =="option1"){
if( this_state == "checked" ){
op2.attr("disabled",true);
}
else {
op2.attr("disabled",false);
}
op2.prev().toggleClass('disabled');
}
if(this_id=="option2"){
if( this_state=="checked" )
op1.attr("disabled",true);
else {
op1.attr("disabled",false);
}
op1.prev().toggleClass('disabled');
}
});
Use $("#element_id").hide(); for disabling the check box
Use $("#element_id").attr("checked", true); to check if the check box is selected
Use $("#element_id").addclass(); to add class to an element so in short search for jQuery selectors and you will find the solutions
Vist for more information http://api.jquery.com/category/selectors/ I hope I help take care

Categories