Jquery , Html Append value to textfield when Checkbox is checked - javascript

I have a list of four check boxes which are as shown below :
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" placeholder=" Suppliers : "/>
The first four are check boxes while the last one is a textbox. How can I append data to the text-field Suppliers ? (When it is checked , it should be appended to the text field Supplier, if it is unchecked, then the value should be removed from the text field supplier) .
I tried implementing it the following way :
var CD_Supplr = $('#CD_Supplr').val();
var id_peer_educator = $('#id_peer_educator').val();
var id_chw = $('#id_chw').val();
var id_health_provider = $('#id_health_provider').val();
var id_purchase = $('#id_purchase').val();
$('#id_peer_educator').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_peer_educator;
});
$('#id_chw').click(function () {
$('#CD_Supplr').val(CD_Supplr + "," + id_chw;
});
But it's not working,what's the best way to implement it?

You can use an array to add value when checkbox is checked and remove it when unchecked and use join() function to join the array values by dispay in input.
Hope this helps.
var selected_checkbox=[];
$('.checkboxstyle').change(function()
{
if($(this).is(':checked'))
{
//If checked add it to the array
selected_checkbox.push($(this).val());
}
else
{
//If unchecked remove it from array
for (var i=selected_checkbox.length-1; i>=0; i--)
{
if (selected_checkbox[i] === $(this).val())
selected_checkbox.splice(i, 1);
}
}
$('#CD_Supplr').val(selected_checkbox.join(','));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="checkboxstyle" id="id_peer_educator" value="Peer Educator"/>Peer Educator<br>
<input type="checkbox" class="checkboxstyle" id="id_chw" value="CHW"/>CHW<br>
<input type="checkbox" class="checkboxstyle" id="id_health_provider" value="Health Prvider"/>Health Provider<br>
<input type="checkbox" class="checkboxstyle" id="id_purchase" value="Purchase"/>Purchase<br>
<input type="text" id="CD_Supplr" class="CD_Supplr" name="CD_Supplr" size='50' placeholder=" Suppliers : "/>

Demo
$('.checkboxstyle').on("change",function ()
{
var str ="";
$('.checkboxstyle:checked').each(function()
{
str+= $(this).val()+" ";
});
$('#CD_Supplr').val(str);
});

Add listeners to the change event on the checkboxex, then using match() find out if the value of a checkbox is NOT already there in the CD_Suplr textbox. Then, use the result of this condition to add/remove the checkbox values:
var $target = $('#CD_Supplr');
$('[type="checkbox"]').change(function(){
if($target.val() == ''){
$target.val('Supplier: '); //default text
}
if(!$target.val().match($(this).val())){
var text = $target.val();
$target.val(text + ' ' + $(this).val() + ', ');
} else {
var text = $target.val();
$target.val(text.replace($(this).val()+', ', ''));
}
//make sure the last comma is removed
$target.val($target.val().replace(/\,$/, ''));
});
JSFiddle Demo.

Related

Return CheckBox True False Status With jQuery Map

I am creating dynamic CheckBoxes using jQuery and by default, those are set to false status. Something as follows:
<input type="checkbox" class="cbCheck" value="false" />
So you can see no value or id is assigned there. Is it possible to just retrieve the true/false based on CheckBox checked/unchecked status something as follows using jQuery mapping?
string = $('input[type=checkbox]:checked').map(function (i, elements) {
return elements; //Here the elements like true or false, instead of elements.value
});
alert(string.join(','));
Expected Output: true, false, false, true (Based on user selection)
You can use the checked property.
const string = Array.from($('input[type=checkbox]')).map(function(element) {
return element.checked; //Here the elements like true or false, instead of elements.value
});
console.log(string.join(","));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" checked/>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked/>
var checkboxes = [];
function createDynamicCheckBoxes() {
if (checkboxes.length != 0)
return;
var numberOfBoxes = parseInt(Math.random() * 10) + 1;
for (var i = 0; i < numberOfBoxes; i++) {
var checkbox = document.createElement('input');
checkbox.setAttribute("type", "checkbox");
checkbox.setAttribute("value", "false");
var number = document.createElement('label');
number.innerText = "(" + (checkboxes.length+1) + ") ";
document.getElementById("container").appendChild(number);
document.getElementById("container").appendChild(checkbox);
document.getElementById("container").appendChild(document.createElement('br'));
checkboxes.push(checkbox);
}
}
function logValues(){
for(var i=0; i<checkboxes.length;i++){
console.log("Checkbox (" + (i+1) + ") is set to " + checkboxes[i].checked);
}
}
<button onclick="createDynamicCheckBoxes()">Generate Checkboxes</button>
<button onclick="logValues()">Log Values of Checkboxes</button>
<div id="container">
</div>
This is a pure JavaScript based snippet. You can do something like this!
The .checked property return check/uncheck status of checkbox. So you need to use it.
var string = $('[type=checkbox]').map(function (i, elements) {
return elements.checked;
}).toArray().join(",");
Also you can simplify the code
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
var string = $(':checkbox').map((i,ele) => ele.checked).toArray().join(",");
console.log(string);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="cbCheck" />
<input type="checkbox" class="cbCheck" checked />
<input type="checkbox" class="cbCheck" />

convert Checkbox into radio button using javascript?

I am trying to convert checkbox into radio button which is working partially , but not deselecting previous selected radio button.I am looking solution to show one button at a time as a selected.
var layers = {
'Esri_WorldImagery': Esri_WorldImagery.addTo(this.baseMap),
'World_Topo_Map': World_Topo_Map//.addTo(this.baseMap)
};
var layerHtml = '<ul class="fa-ul">';
for (var key in layers) {
if (layers.hasOwnProperty(key)) {
var state = this.baseMap.hasLayer(layers[key]) ? 'checked="checked"' : '';
//layerHtml += '<li><label><input type="checkbox" ' + state + ' value="' + key + '" >' + key + '</label>';
layerHtml += '<li><label><input type="radio" ' + state + ' value="' + key + '" >' + key + '</label>';
}
}
layerHtml += '</ul>';
var widget = $('<div id="layer-control" class="sidebar-widget">' + layerHtml + '</div>');
widget.on('click', 'input[type="radio"]', function (e) {
var was_Active = $(this).prop('checked');
var value = $(this).val();
if (was_Active) {
layers[value].addTo(self.baseMap);
}
else {
self.baseMap.removeLayer(layers[value]);
}
});
First, regarding the current code with radio elements, as #Aswin Ramesh has told you, yo should add the name attribute. From MDN:
A radio group is defined by giving each of radio buttons in the group the same name. Once a radio group is established, selecting any radio button in that group automatically deselects any currently-selected radio button in the same group.
Besides the shape (circle vs square) that's the only difference between the radio and checkbox elements. So consider that checkboxes that behave like radio buttons might be confusing for the user.
That said, if you really want to replicate that functionality on checkboxes, use JavaScript to deselect all the elements but the one which raised the click event.
$('#checkboxes').on('click', ':checkbox', function(e) {
$('#checkboxes :checkbox').each(function() {
if (this != e.target)
$(this).prop('checked', false);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="radios">
<input type="radio" name="rOptions" value="radio1" checked>
<input type="radio" name="rOptions" value="radio2">
<input type="radio" name="rOptions" value="radio3">
</div>
<div id="checkboxes">
<input type="checkbox" value="checkbox1" checked>
<input type="checkbox" value="checkbox2">
<input type="checkbox" value="checkbox3">
</div>
Note: you forgot to close the <li> tags.

Verify checked checkbox javascript

I'm trying to update in "real time" if I check and uncheck in a list of checkboxs.
With this code:
window.onload = function () {
var input = document.getElementById('listTaxi');
function check() {
var a = input.checked ? "checked" : "not checked";
console.log(a);
}
input.onchange = check;
check();
}
I can do this for one checkbox, but how can I make for multiple checkboxs? A list(div) of checkboxs?
Thanks!!
Assign a class on all checkboxes you want to check if checked or not.
Checkboxes
<input type="checkbox" class="checkboxes" id="checkbox1"/>
<input type="checkbox" class="checkboxes" id="checkbox2"/>
<input type="checkbox" class="checkboxes" id="checkbox3"/>
<input type="checkbox" class="checkboxes" id="checkbox4"/>
Pure Javascript
// getting all checkboxes
var checkboxes = document.getElementsByClassName('checkboxes');
// go through all checkboxes
for(var i = 0; i <= checkboxes.length - 1; i++){
checkboxes[i].onchange = function(e){
alert('Element with id ' + e.target.getAttribute('id') + ' is checked ' +e.target.checked);
}
}
Codepen http://codepen.io/todorutandrei/pen/rLBQOX
Or you can use JQUERY - is it more simple
$('.checkboxes').change(function(){
var item = $(this);
alert('Element with id ' + item.attr('id') + ' is ' + item.is(':checked'));
})
Codepen http://codepen.io/todorutandrei/pen/MegzwR
make them all the same class or give the all the same custom attribute
$(".classname")
$("input[name='customName'])
Jquery will then select all with those
$("#id").change(function() {//if using class name or custom attr loop through the return elements and use a function below to handle the cases
if($(this).is(":checked")) {
//code if checked
}
else{
//code if not checked
}
});

I'm trying to assign a variable to check-boxes and adding that variable to an output variable when it's checked

I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.

How to automatically uncheck checkbox if textbox is filled

I've made the checkbox to be default check. How can I uncheck the checkbox automatically if certain textfield is filled. I've thinking of using javascript.
I tried using this
<input type="text" name="commentID" id="commentID" onkeyup="userTyped('skipID', this)"/>
<input type="checkbox" name="skipID" value="N" id="skipID" checked="checked" />
and the javascript
function userTyped(commen, e){
if(e.value.length > 0){
document.getElementById(commen).checked=false;
}else{
document.getElementById(commen).checked=true;
}}​
It works but how if i have 3 textfield, and I want the checkbox to be filled only after all textfield is filled.
Just do this:
<input type="checkbox" id="someid" checked="checked"/>
<textarea onchange="if (this.value != '') document.getElementById('someid').checked = false;"></textarea>
if(document.getElementById('yourtextBox').value!=' ')
{
document.getElementById('checbox').checked=false;
}
Try the following code. In this code, each time when you type a character in the textfield, the function will be called and the length of the textfield value is not zero, the checbox will be unchecked and it will be checked while you clear your textfield
//Function get called when you type each letter
function OnChangeTextField(){
//getting the length of your textbox
var myLength = $("#myTextbox").val().length;
if(myLength > 0){
$("#myCheckbox").attr("checked", false);
}else{
$("#myCheckbox").attr("checked", true);
}
}
<input type = "text" id = "myTextbox" onkeyup= "OnChangeTextField();"/>
<input type="checkbox" id = "myCheckbox" value = "true" checked = "checked"/>
$("#comment").on("keyup blur", function () {
$("#box").prop("checked", this.value == "");
});
EDIT: You can also use jQuery
$("#comment").on("keyup blur", function() {
$("#box").prop("checked", this.value == "");
});
Try jQuery, This works for me...

Categories

Resources