checkbox name i need in text field - javascript

<input type="checkbox" name="checkbox" id="checkbox1" value="10" /> Value 1
<input type="checkbox" name="checkbox" id="checkbox2" value="20" /> value 2
<input type="checkbox" name="checkbox" id="checkbox3" value="30" /> value 3
<input type="checkbox" name="checkbox" id="checkbox4" value="40" /> value 4
<input type="checkbox" name="checkbox" id="checkbox5" value="50" /> value 5
Ect, etc. I want the add value of selected checkboxes in a text field and all selected checkbox value in a diffrent diffrent checkboxes.
Using this code for the adding of checkboxes but dont know how to get the name of the check box as well as dynamic. For example value 1 , value 2, value 3 in a textbox in front of checkbox in a hidden form.
Code of adding is given below.
$(document).ready(function () {
$("#textfield2").val( $("#textfield").val());
$('.priceAdded input[type="checkbox"]').on("change", function () {
var priceAdded = $("#textfield").val();
$('.priceAdded input[type="checkbox"]').each(function () {
if ($(this).is(":checked")) {
priceAdded = parseFloat(priceAdded) + parseFloat($(this).val());
}
$("#textfield2").val(priceAdded);
});
});
return false;
});

If you're wanting to get the id of the checkboxes and a total of the selected values
http://jsfiddle.net/hb0hhbk4/1/
HTML
<input type="checkbox" name="checkbox" id="checkbox1" value="10" class='sum' />Value 1
<input type="checkbox" name="checkbox" id="checkbox2" value="20" class='sum' />value 2
<input type="checkbox" name="checkbox" id="checkbox3" value="30" class='sum' />value 3
<input type="checkbox" name="checkbox" id="checkbox4" value="40" class='sum' />value 4
<input type="checkbox" name="checkbox" id="checkbox5" value="50" class='sum' />value 5
<input id='textfield1' type='text' />
<input id='textfield2' type='text' />
JS
$("input[type='checkbox'].sum").on('click', function () {
var total = 0;
var ids = [];
$("input[type='checkbox'].sum:checked").each(function () {
var value = parseInt($(this).val());
total += value;
ids.push($(this).attr('id'));
});
ids = ids.join(" ", ids);
$('#textfield1').val(ids);
$('#textfield2').val(total);
});

If you're looking for the LABEL near the checkbox, you need to do something like this
<span><input type="checkbox" name="checkbox" id="checkbox1" value="10" /> Value 1</span>
<span><input type="checkbox" name="checkbox" id="checkbox2" value="20" /> value 2</span>
<span><input type="checkbox" name="checkbox" id="checkbox3" value="30" /> value 3</span>
<span><input type="checkbox" name="checkbox" id="checkbox4" value="40" /> value 4</span>
<span><input type="checkbox" name="checkbox" id="checkbox5" value="50" /> value 5</span>
And inside the each function you can access the label with
$( this ).closest( "span" ).text();

Using that layout, you probably won't be able to, because there's no way of isolating "value 1", for example, from the rest of the code (it isn't the content of an element, or an attribute of anything.
You could put the "Value 1/2/3/4" text in something like a span and then you can use the adjacent selector in Jquery. for example::
<input type="checkbox" name="checkbox" id="checkbox1" value="10" /> <span>Value 1</span>
Then use
$(this).next().text();
To get the contents of the span directly after the checkbox that's just been clicked.

Related

Push and pop data from array based on checkbox check and uncheck value using jQuery

var listvalues = []
$('.check').on('change', function() {
var val = this.checked ? this.value : '';
listvalues.push(val)
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
I have a code which should push and pop checkbox value based on checkbox check and uncheck, for example if I check and checkbox it should show the value in a div and if I unselect the checkbox the value should disappear from div, and it should not allow anyone to append duplicate data.
But what I did appends even if it is duplicate it appends the data. Can anyone help me on this?
and i wanted to create separate div for each checkbox
Instead of push & pop value from array, you can get all checked values with listvalues = $('.check:checked').toArray().map(x => x.value); and display it.
$('.check:checked') will only return .check which are checked. Then .toArray() will convert jquery object into array & get use .map(x => x.value) to fetch only value from checked elements.
var listvalues = []
$('.check').on('change', function() {
listvalues = $('.check:checked').toArray().map(x => x.value).join(', ');
$('#show').html(listvalues);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>
To remove you can use filter to exclude the unchecked item. I'm not sure what you want to achieve with different divs, please explain.
var listvalues = []
$('.check').on('change', function() {
if(this.checked){
listvalues.push(this.value);
}
else {
listvalues = listvalues.filter(item => item != this.value);
}
$('#show').html(listvalues.sort());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" type="text/javascript"></script>
<input type="checkbox" class="check" value="1" />1
<input type="checkbox" class="check" value="2" />2
<input type="checkbox" class="check" value="3" />3
<input type="checkbox" class="check" value="4" />4
<div id="show"> </div>

How does one, from a checkbox group and preferably with jQuery, collect array data and does assign this data to a hidden target element's value?

I have a group of equally named checkboxes ...
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
and a hidden form element ...
<input type="hidden" class="target" name="target[]" value="" />
Using jQuery, I want to copy all checked checkbox values in form of a value-list in its stringified array literal notation to the hidden target element's value.
I have tried the following ...
$(".checkbox").each(function(idx, val) {
$('input[name="target['+idx+']"]').val(this.value);
});
... without success. How can I generate and assign the correct result?
map() the :checked checkboxes to create array of their values, then stringify that array
const checkedVals = $(".checkbox:checked").map((i,el) => el.value).get()
$('input[name="target[]"]').val(JSON.stringify(checkedVals))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input class="target" name="target[]" value="">
basic jQuery approach which does the following ...
Query all equally named ... [name="checkbox[]"] ... and also :checked checkboxes,
and convert the resulting jQuery collection into a native array ... toArray().
Make use of an array's native map method in order to return an array of (checked) checkbox values,
which immediately after gets converted via JSON.stringify into its string representation (of an array literal notation),
and assigned to the hidden target element's (via jQuery $('input[name="target[]"]')[0]) value.
$('input[name="target[]"]')[0].value = JSON.stringify(
$('[type="checkbox"][name="checkbox[]"]:checked')
.toArray()
.map(elm => elm.value)
);
console.log(
'target[] :: value :',
$('input[name="target[]"]')[0].value
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input type="hidden" class="target" name="target[]" value="">
a jQuery free variant of the above approach with checkbox change event handling ...
function updateCheckboxTargetValue() {
document
.querySelector('input[name="target[]"]')
.value = JSON.stringify([
...document
.querySelectorAll(
'[type="checkbox"][name="checkbox[]"]:checked'
)
].map(elm => elm.value)
);
console.log(
'target[] :: value :',
document.querySelector('input[name="target[]"]').value
);
}
function handleCheckboxChange(evt) {
if (evt.target.matches('[type="checkbox"][name="checkbox[]"]')) {
updateCheckboxTargetValue();
}
}
updateCheckboxTargetValue();
document.addEventListener('change', handleCheckboxChange);
<input type="checkbox" class="checkbox" name="checkbox[]" value="1" checked />
<input type="checkbox" class="checkbox" name="checkbox[]" value="2" />
<input type="checkbox" class="checkbox" name="checkbox[]" value="3" checked />
<input type="hidden" class="target" name="target[]" value="">

Check and summed if two or more checkbox is checked

I have an 4 input checkbox tag, and 1 div tag to display a price if one checkbox is checked
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>
What i want to do if only 1 random checkbox is checked it will display number 1,800 on div#price, but if 2 checkbox is checked it will summed become 3,600 and so on until 4 checkbox. But i really confused how to do that using jQuery. Any idea?
Use :checkbox selector to assign change event on all thre type = checkbox elements, one can add [value="None"] while selecing checkbox elements to be more specific.
Use :checkbox:checked selector to select the checked checkboxes.
var val = 1800;
$(':checkbox[value="None"]').on('change', function() {
var len = $(':checkbox:checked').length;
$('#price').text(len * val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="None" id="check1" />
<input type="checkbox" value="None" id="check2" />
<input type="checkbox" value="None" id="check3" />
<input type="checkbox" value="None" id="check4" />
<div id="price"></div>
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="checkbox" value="100" id="check1" />
<input type="checkbox" value="21" id="check2" />
<input type="checkbox" value="22" id="check3" />
<input type="checkbox" value="4" id="check4" />
<div id="price"></div>
JAVASCRIPT
var price=0;
$(':checkbox').on('change', function() {
var len = parseInt(this.value);
if($(this).is(':checked')){
price+=len;
}else{
price-=len;
}
console.log(price)
$('#price').text(price);
});
JSBIN
JSBIN-URL

Only one checkbox checked at a time in javascript

I have 3 checkbox, for which I want only 1 checkbox to be checked at a time. below is my fiddle for the html
JS fiddle
I want this to be worked in IE8 also kindly suggest how to do
How about this - fiddle:
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
<input type="checkbox" class="chk" />
$('input.chk').on('change', function() {
$('input.chk').not(this).prop('checked', false);
});
Edit:
for second part of your question to un-check other checkboxes when selecting parent checkbox see this fiddle - (as per chat) :
if (!cb.checked) {
$('#trchkOptions input[type=checkbox]').attr('checked', false);
}
function selectOnlyThis(id) {
for (var i = 1;i <= 4; i++)
{
document.getElementById(i).checked = false;
}
document.getElementById(id).checked = true;
}
<input type="checkbox" id="1" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 1
<input type="checkbox" id="2" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 2
<input type="checkbox" id="3" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 3
<input type="checkbox" id="4" value="Value1" onclick="selectOnlyThis(this.id)" /> Option 4
It should help you

How to remove unchecked item from textbox?

My JavaScript:
<script type="text/javascript">
function getVal(chk, adto)
{
var ad="";
if (chk.checked)
{
ad=document.getElementById(adto).value + chk.value;
document.getElementById(adto).value = ad;
}
else
{
}
}
</script>
The first block is working as I wanted but when user unchecked the check box it should remove the value from the text box.
Below is the HTML code:
<body>
<input type="checkbox" name="chk[]" value="0" id="chk0" onclick="getVal(this, 'inp0')">value 0<br>
<input type="checkbox" name="chk[]" value="1" id="chk1" onclick="getVal(this, 'inp0')">value 1<br>
<input type="checkbox" name="chk[]" value="2" id="chk2" onclick="getVal(this, 'inp0')">value 2<br>
<input type="checkbox" name="chk[]" value="3" id="chk3" onclick="getVal(this, 'inp0')">value 3<br>
<input type="checkbox" name="chk[]" value="4" id="chk4" onclick="getVal(this, 'inp0')">value 4<br>
<input type="checkbox" name="chk[]" value="5" id="chk5" onclick="getVal(this, 'inp0')">value 5<br>
<br>
<input type="text" name="inp" id="inp0" readonly><br>
Please help how to remove the unchecked options from the text box.
DEMO
Assuming all checkboxes with the same name adds to the same field.
If not we will need more code.
I also assumed the boxes are wrapped in a form tag
function getVal(chk, adto) {
var ad=[];
var checks = chk.form[chk.name];
for (i=0;i<checks.length;i++) {
if (checks[i].checked) {
ad.push(checks[i].value);
}
}
document.getElementById(adto).value = (ad.length>0)?ad.join(" "):"";
}

Categories

Resources