how to change class property inside a checkbox - javascript

if user inputs a value in the input field the class value on the checkbox will change automatically
input field:
<input style="width:25px; margin-left:5px;" type="text" name="qtyA" id="qtyA" />
checkbox:
<input id="INsrv1" name="INopt" type="checkbox" value="1" />1<br>
<input id="INsrv2" name="INopt" type="checkbox" value="2" />2<br>
<input id="INsrv3" name="INopt" type="checkbox" value="3" />3<br>
<input id="INsrv4" name="INopt" type="checkbox" value="4" />4<br>
javascript:
<script>
$(document).ready(function() {
$('#qtyA').on('change', function() {
var max = $(this).val();
});
$("[name$='INopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
});
</script>
for ex:
the user inputs 3 in input field "qtyA"
value : 3
the maxCheckbox[] value on the script will change along with it
from maxCheckbox[1] to maxCheckbox[3]
the actual code:
<script>
$(document).ready(function() {
$('#qtyA').on('change', function() {
var max = $(this).val();
alert(max);
});
$("#srv").on('change', function() {
var max = $('#qtyA').val();
alert(max);
var selVal = $(this).val();
if (selVal == 'Inbound') { // Inbound
$('.Inbound').show();
$('.Outbound').hide();
$("[name$='OUTopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$("[name$='INopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
$('#valOUT').val('');
$('div#Outbound').find('span').prop('class','');
}
else if (selVal == 'Outbound') { // Outbound
$('.Inbound').hide();
$('.Outbound').show();
$("[name$='INopt']").prop('class','')
$("#INsrvOtr").prop('class','')
$("[name$='OUTopt']").prop('class','validate[minCheckbox[1],maxCheckbox[max]] checkbox text')
$('#valIN').val('');
$('div#Inbound').find('span').prop('class','');
}
else {
$('.Inbound').hide();
$('.Outbound').hide();
$('#valOUT').val('');
$('#valIN').val('');
$("[name$='INopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$('div#Inbound').find('span').prop('class','');
$("[name$='OUTopt']").prop('class','')
$("#OUTsrvOtr").prop('class','')
$('div#Outbound').find('span').prop('class','');
}
});
});
</script>

$(document).ready(function() {
$("input").onchange(function() {
$(this).attr('class','validate[minCheckbox[1],maxCheckbox[1]] checkbox text')
}
});

Related

Check all/sum values - how to put span inside input

I wrote some code which sums up all the values of checkboxes with a "toggle all" option. At the beginning I needed to only have information about the value, but now I need to have sum inside an input element, but it does not work.
NOTICE: I know ID can be used only once! I put both input and span to show that it works with span and not with input.
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var inputs = select('.sum'),
totalElement = document.getElementById('payment-total')
function sumUpdate() {
totalElement.innerHTML = inputs.reduce(function(result, input) {
return result + (input.checked ? parseFloat(input.value) : 0);
}, 0).toFixed(2);
}
// Update the sums in function on input change.
inputs.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/></div> <br/> Price: <span id="payment-total">0</span>
</div>
I done some modification to your sumUpdate function making it working now, you need to give the input control and the span different id:
// Shorter querySelectorAll that returns a real array.
function select(selector, parent) {
return Array.from((parent || document).querySelectorAll(selector));
}
var values = document.querySelectorAll('.sum');
function sumUpdate() {
var total = 0;
var selectedItems = Array.prototype.filter.call(values,function(input) {
return input.checked ? input : null;
});
$(selectedItems).each(function (index, element) {
total = total + parseFloat($(element).val());
});
total = parseFloat(total).toFixed(2);
$('#payment-total').val(total);
$('#payment-total-span').text(total);
}
// Update the sums in function on input change.
values.forEach(function(input) {
input.addEventListener("change", sumUpdate);
});
select(".checkAll").forEach(function(checkAll) {
var targetFieldSet = document.getElementById(checkAll.getAttribute("data-target-set"));
var targetInputs = select(".sum", targetFieldSet);
// Update checkAll in function of the inputs on input change.
targetInputs.forEach(function(input) {
input.addEventListener("change", function() {
checkAll.checked = input.checked && targetInputs.every(function(sibling) {
return sibling.checked;
});
});
});
// Update the inputs on checkall change, then udpate the sums.
checkAll.addEventListener("change", function() {
targetInputs.forEach(function(input) {
input.checked = checkAll.checked;
});
sumUpdate();
});
});
function checkInput(text) {
if (text) {
$("#clearBtn1").addClass("show");
} else {
$("#clearBtn1").removeClass("show");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p><label><input type="checkbox" class="checkAll" data-target-set="setA"/> Check all Set A</label></p>
<fieldset id="setA">
<legend>Set A Books</legend>
<input value="300" type="checkbox" class="sum" data-toggle="checkbox"> English
<input value="500" type="checkbox" class="sum" data-toggle="checkbox"> Science
<input value="755" type="checkbox" class="sum" data-toggle="checkbox"> Christian Living
</fieldset>
<p></p>
<div class="card-charge-info">
Price: <input type="text" id="payment-total" value="" disabled/> <br/> Price: <span id="payment-total-span">0</span>
</div>

jquery add / remove item from array

I have a checkboxs 3-4 of them, when the user checks the checkbox I want to add the value of the checkbox to the array, if they uncheck the box I want to remove the item from the array, this is what I got so far:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
if ($(this).attr("id") == 'price') {
if (this.checked) {
priceArray.push($(this).val());
}
else {
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
}
}
});
});
Adding the value to the array works perfectly, however removing items results in this error:
Cannot read property 'toLowerCase' of undefined
on this line:
return value != $(this).val();
Run the code snippet and check
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var priceArray=[];
$(document).ready(function(){
$('input[type=checkbox]').each(function () {
$(this).change(function () {
if (this.checked) {
priceArray.push($(this).val());
$("#displayarray").html("array=[" + priceArray+"]");
}
else {
var index = priceArray.indexOf($(this).val());
if (index > -1) {
priceArray.splice(index, 1);
}
$("#displayarray").html("array=[" + priceArray+"]");
}
});
});
});
</script>
<input type="checkbox" value="box1"/>box1
<input type="checkbox" value="box2"/>box2
<input type="checkbox" value="box3"/>box3
<input type="checkbox" value="box4"/>box4
<br/>
<div id="displayarray"></div>
Replace
priceArray = jQuery.grep(priceArray, function (value) {
return value != $(this).val();
});
By
val = $(this).val();
priceArray = jQuery.grep(priceArray, function (value) {
return value != val;
});
Don't forget the scope where your are in the callback function.
You can try using filter instead of $.grep:
var values = [];
$("input").on("change", function()
{
var $this = $(this);
if ($this.is(":checked"))
{
values.push($this.val());
}
else
{
values = values.filter(x => x != $this.val());
}
console.log(values);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
<input type="checkbox" value="3" />
<input type="checkbox" value="4" />
<input type="checkbox" value="5" />
<input type="checkbox" value="6" />
<input type="checkbox" value="7" />
filter() is a native function, I prefer using built-in function rather than 3rd party's, IMO. Also, avoid binding events within loops like this:
$('ul.dropdown-menu input[type=checkbox]').each(function () {
$(this).change(function () {
Use this method:
$('ul.dropdown-menu').on('change', 'input[type=checkbox]', function() { ...
This will work even if checkbox is dynamically added.
You could do this very cleanly with a functional style
<div class="checkboxes">
<input type="checkbox" value="1" />
<input type="checkbox" value="2" />
</div>
And
(function() {
$(".checkboxes input[type=checkbox]").on("click", function() {
var x = $(".checkboxes input[type=checkbox]:checked").map(function(a,b) {
return parseFloat(b.value);
}).toArray();
console.log(x)
});
})();
I had a similar situation and I was able to overcome it in the following way :
My jQuery :
$(document).ready(function(){
$("#dataFilterForm").on("input", function() {
var values = '';
var boxes = $('input[name=vehicle]:checked');
boxes.each(function(b){
values = values + boxes[b].id + ', ';
});
$('#filterResult').text(values.substring(0, values.length-2));
});
});
My HTML :
<form id="dataFilterForm">
<input type="checkbox" id="Filter1" name="vehicle" value="Bike">
<label for="Filter1">Filter1</label><br>
<input type="checkbox" id="Filter2" name="vehicle" value="Car">
<label for="Filter2">Filter2</label><br>
<input type="checkbox" id="Filter3" name="vehicle" value="Boat">
<label for="Filter3">Filter3</label><br>
</form>
<p>Result : </p>
<p id="filterResult"></p>

Check at most four check box and store checked value to textbox

I am displaying some check boxes. The user can check a maximum of 4 boxes. I store the checked value in 4 textboxes.
My problem: How can I correctly store the "new" checked value when the user randomly unchecks one box and checks another?
I store values as follows: First checked into item_1, second checked into item_2, third checked into item_3 ... If the user unchecks the first checked box, for example, how can I store the value of the next box he or she checks into item_1? Please help.
Simplified code
<input type="checkbox" name="prodname_1" id="prodname_1"value="1"/>
<input type="checkbox" name="prodname_2" id="prodname_2"value="2"/>
<input type="checkbox" name="prodname_3" id="prodname_3"value="3"/>
.
.
<input type="checkbox" name="prodname_10" id="prodname_10"value="10"/>
<input type="text" name="item_0" id="item_0"value=""/>
<input type="text" name="item_1" id="item_1"value=""/>
<input type="text" name="item_2" id="item_2"value=""/>
<input type="text" name="item_3" id="item_3"value=""/>
$(document).ready(function (e)
{
counter=0;
$('input[id^="prodname_"]').change(function()
{
id = $(this).attr('id');
var arr = id.split('_');
valueChecked=$('#'+id).val();
if(this.checked)
{
if(counter==4)
{
alert('Allready checked 4 items');
this.checked=false;
return false;
}
$("#item_"+counter).val(valueChecked);
++counter;
}
});
});
Instead of retaining a counter, just count the number of checked boxes when the change occurs.
Revised to use the logic you intended (took a little while to figure that out) :)
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/9/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var checkboxes = $('input[id ^= "prodname_"]').change(function () {
var id = $(this).attr('id');
var arr = id.split('_');
valueChecked = $(this).val();
// Count of checked checkboxes
var counter = checkboxes.filter(':checked').length;
if ($(this).is(':checked')) {
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
} else {
// Add to the first available slot
$items.filter(function(){return $(this).val() == ""}).first().val(valueChecked);
}
} else {
// Remove the matching value
$items.filter(function(){return $(this).val() == valueChecked;}).first().val('');
}
});
});
note: The "jQuery way" for changing checkboxes is to use prop('checked', booleanvalue) (also changed above)
V2 - If you don't want gaps:
This version is actually simpler as it just clears the items and fills them, in order, with any checked checkbox values.
JSFiddle: http://jsfiddle.net/TrueBlueAussie/tmLnbvv0/13/
$(document).ready(function (e) {
var $items = $('input[id^="item_"]');
var $checkboxes = $('input[id ^= "prodname_"]').change(function () {
// Count of checked checkboxes
var counter = $checkboxes.filter(':checked').length;
// count the checked checkboxes
if (counter > 4) {
alert('Already checked 4 items');
$(this).prop('checked', false);
}
// Clear all the items
$items.val('');
// Fill the items with the selected values
var item = 0;
$checkboxes.filter(':checked').each(function () {
$('#item_' + (item++)).val($(this).val());
});
});
});
Look at
$(document).ready(function(e) {
var counter = 0,
$items = $('input[name^="item_"]');
$('input[id^="prodname_"]').change(function() {
var id = this;
if (this.checked) {
if (counter == 4) {
this.checked = false;
return;
}
$("#item_" + counter).val(this.value).attr('data-value', this.value);
++counter;
} else {
var $item = $items.filter('[data-value="' + this.value + '"]');
var index = $items.index($item);
$items.slice(index, counter).each(function(i) {
var $n = $items.eq(index + i + 1);
$(this).val($n.val() || '').attr('data-value', $n.attr('data-value'));
});
counter--;
$("#item_" + counter).val('').removeAttr('data-value');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="prodname_1" id="prodname_1" value="1" />
<input type="checkbox" name="prodname_2" id="prodname_2" value="2" />
<input type="checkbox" name="prodname_3" id="prodname_3" value="3" />
<input type="checkbox" name="prodname_4" id="prodname_4" value="4" />
<input type="checkbox" name="prodname_5" id="prodname_5" value="5" />
<input type="checkbox" name="prodname_6" id="prodname_6" value="6" />
<input type="checkbox" name="prodname_7" id="prodname_7" value="7" />
<input type="checkbox" name="prodname_8" id="prodname_8" value="8" />
<input type="checkbox" name="prodname_9" id="prodname_9" value="9" />
<input type="checkbox" name="prodname_10" id="prodname_10" value="10" />
<input type="text" name="item_0" id="item_0" value="" />
<input type="text" name="item_1" id="item_1" value="" />
<input type="text" name="item_2" id="item_2" value="" />
<input type="text" name="item_3" id="item_3" value="" />

check all checkbox with hide

How do I add a checkbox that can check all the checkboxes if it's checked?
How can I add show/hide functionality to the "check all" checkbox.
The submit button also need to be showed if the check all checkbox is checked.
$(document).ready(function() {
var $submit = $("#submit_prog").hide(),
$cbs = $('input[name="prog"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
<input type="checkbox" name="?" value="?"> // check all checkbox
<input type="checkbox" name="prog" value="1">
<input type="checkbox" name="prog" value="2">
<input type="submit" id="submit_prog" value='Submit' />
assumption id of select all chckbox is selall.
create a class for all the check box you want to select using select all
$('#selall').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$('.yourchckbox').each(function() {
this.checked = true;
});
$('#submit_prog').show();
}
else {
$('.yourchckbox').each(function()
{ this.checked = false; });
$('#submit_prog').hide()
}
});
$('.yourchckbox').click(function(event) {
if(!(this.checked)) {
$('#selall').prop('checked', false);
}
});
Give the select all check box an id, say selectall then
$('#selectall').click(function(){
if (this.checked){
$('input[name="prog"]').prop('checked', true);
$submit.toggle( true );
}
});
if you want the checkboxes to be unselected if the select all in unselected
$('#selectall').click(function(){
$('input[name="prog"]').prop('checked', this.checked);
$submit.toggle( this.checked);
});
$cbs = $('input[name="prog"]').click(function() {
$submit.toggle( $cbs.filter(':checked').length == 0 );
if (!this.checked) $('#selectall').prop('checked', false);
});
Try
$('input:checkbox[name!="prog"]').click(function(){
$('input:checkbox[name="prog"]').prop('checked', $(this).is(':checked'))
})
Or if you can change checkbox id to selall
$('#selall').click(function(){
$('input:checkbox').prop('checked', $(this).is(':checked'))
})
Its quite simple.
lets name this checkbox <input type="checkbox" name="check_all" value="1">
And now add event:
$('input[name="check_all"]').click( function() {
if( $(this).is(':checked') ) {
$('input[name="prog"]').attr('checked', 'checked');
} else {
$('input[name="prog"]').removeAttr('checked');
}
$('input[name="prog"]:eq(0)').change(); //firing event which we will catch
});
Then we should check if all input[name="prog"] are checked:
$('input[name="prog"]').change( function() {
if( $('input[name="prog"]:not(:checked)').length ) {
$('#submit_prog').hide();
} else {
$('#submit_prog').show();
}
});
select all checkboxes on #all check and check #all when all checkboxes are checked
<SCRIPT language="javascript">
$(function(){
$("#all").click(function () {
$('.one').attr('checked', this.checked);
if (this.checked) {$('#submit_prog').hide();}
(this.checked)?$('#submit_prog').show():$('#submit_prog').hide();
});
$(".one").click(function(){
if($(".one").length == $(".one:checked").length) {
$("#all").attr("checked", "checked");
$('#submit_prog').show();
} else {
$("#all").removeAttr("checked");
$('#submit_prog').hide();
}
});
});
</SCRIPT>
Change id and class of checkboxes
<input type="checkbox" id="all" > // check all checkbox
<input type="checkbox" name="prog" class="one" value="1">
<input type="checkbox" name="prog" class="one" value="2">

Javascript help. Adding/removing form element to DOM

if radio button 2 is checked add input box into datesettings. How do i add an input box? If radio button 1 is checked do nothing but if button 2 was checked previously remove children. Can you help me
Thanks
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
//Remove o2 children
}
else if(o2.checked) {
//How do I add an input box?
}
}
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions();">
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions();">
<span id="datesettings">//Add input box here if dateoption2 is checked</span>
The simplest route would be:
<input type="radio" id="dateoption1" name="dateoption" value="1" ="ToggleDateOptions(true);" />
<input type="radio" id="dateoption2" name="dateoption" value="2" ="ToggleDateOptions(false);" />
<span id="datesettings">
<input type="text" id="dateSetting" />
</span>
<script>
function ToggleDateOptions(oneChecked) {
if(oneChecked)
{
$("#dateSetting").hide();
}
else
{
$("#dateSetting").show();
}
}
</script>
Or if you didn't want to use JQuery (Which is used above) you could do:
if(oneChecked)
{
document.getElementById("dateSetting").style.display = 'none';
}
else
{
document.getElementById("dateSetting").style.display = 'inline';
}
You can just use innerHTML to add the input field.
Something like this should work for you
<script type="text/javascript">
function CheckDateOptions() {
var o1 = document.getElementById("dateoption1");
var o2 = document.getElementById("dateoption2");
var eSettings = document.getElementById("datesettings");
if(o1.checked) {
eSettings.innerHTML = "";
} else if(o2.checked) {
eSettings.innerHTML = '<input type="text" name="field" />';
}
}
</script>
<input type="radio" id="dateoption1" name="dateoption" value="1" onclick="CheckDateOptions()"/>
<input type="radio" id="dateoption2" name="dateoption" value="2" onclick="CheckDateOptions()"/>
<span id="datesettings"></span>
Demo

Categories

Resources