jquery checkbox get value text input - javascript

I have list input checkbox
<input type="checkbox" name="id_image" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" />
<input type="text" name="id_image" value="" class="id_image_check" />
How to check multiple input checkbox i have show value to input type="text"as
<form>
<input type="text" name="id_image" value="homies_01, homies_02, homies_03" class="id_image_check" />
</form>

There is a perfecly solution with Vanilla Javascript
function attachListeners() {
var checkboxes = document.getElementsByClassName('id_image')
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].addEventListener('click', getAndPutValues, false);
}
}
function getAndPutValues() {
var result = [];
document.querySelectorAll(".id_image:checked").forEach(function(item) { result.push(item.value);});
document.querySelector('.id_image_check').value = result.join(', ');
}
attachListeners();

With jquery
$(".id_image").on("click",function(){
$(".id_image_check").val(
$(".id_image :checked").map((i,el) => el.value).join(", ")
)
});

First of all you should use array notation for checkbox names
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" />
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" />
It will help you to post multiple values simultaneously
After that for checking values in jQuery you can use
<script type="text/javascript">
$('[name="id_image[]"]').click(function(){
var value = '';
$('[name="id_image[]"]:checked').each(function(){
value += $(this).val();
});
$('#id_image_check').val(value);
});
</script>

Try this :
<input type="checkbox" name="id_image" value="homies_01" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_02" class="id_image" onchange="toggleCheckbox(this)" />
<input type="checkbox" name="id_image" value="homies_03" class="id_image" onchange="toggleCheckbox(this)" />
<input type="text" name="id_image" id="id_image" value="" class="id_image_check" />
<script type="text/javascript">
var arrImages = [];
function toggleCheckbox(element) {
console.log('element', element.value);
arrImages.push(element.value);
document.getElementById("id_image").value = arrImages;
}
</script>

Just use square brackets [] at end of name if you want to submit it using form or use the following method in jQuery to get values of multiple selected checkboxes.
$('#show').click(function(){
values = "";
$('input.id_image:checked').each(function(){
values += $(this).val() + " ";
});
if(values){
$('#values').html(values);
}else{
$('#values').html("None");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="id_image[]" value="homies_01" class="id_image" /> Homies 1
<input type="checkbox" name="id_image[]" value="homies_02" class="id_image" /> Homies 2
<input type="checkbox" name="id_image[]" value="homies_03" class="id_image" /> Homies 3
<br>
<button id="show">Show</button>
<br>
<div id="values"></div>

Related

jQuery/Javascript complex iterate over elements

We have a form and need to iterate over some elements to get the final sum to put in a "total" element.
E.g., here is a working starter script. It doesn't NOT iterate over the other ones. It does NOT consider the elements "item*", below, yet but should. Keep reading.
<script>
$( document ).ready(function() {
$('#taxsptotal').keyup(calcgrand);
$('#shiptotal').keyup(calcgrand);
$('#disctotal').keyup(calcgrand);
function calcgrand() {
var grandtot = parseFloat($('#subtotal').val(), 10)
+ parseFloat($("#taxsptotal").val(), 10)
+ parseFloat($("#shiptotal").val(), 10)
- parseFloat($("#disctotal").val(), 10)
$('#ordertotal').val(grandtot);
}
});
</script>
We are adding more to this. Think of having many items in a cart and each one has the same elements for the following where "i" is a number designating an individual item.
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
(1) User can change any itemprice[i] and/or itemquantity[i], so each needs a keyup. I can do that in php as it iterates over the items.
(2) These elements will have a $('.itemtotal[i]').keyup(calcgrand); (Or function other than calcgrand, if needed) statement, too. That keyup can be added by the php code as it evaluates the items in the cart.
(3) When an element is changed, then the script should automatically (a) calculate the $('[name="itemtotal[i]"]').val() and (b) replace the value for $('[name="itemtotal[i]"]').val().
(4) Then, the script above will use the $('[name="itemtotal[i]"]').val() to (a) replace the #subtotal value and (b) use that value in the equation.
Can someone help me with this? I am stuck on how to iterate over the [i] elements.
p.s. Any corrections/enhancements to the above code is appreciated, too.
Add a custom class to the desired inputs to sum:
HTML:
<input type="text" class="customclass" name=itemtotal[1] value="8.97" />
<input type="text" class="customclass" name=itemquantity[1] value="3" />
<input type="text" class="customclass" name=itemprice[1] value="2.99" />
JS:
var sum = 0;
$.each('.customclass',function(i, item){
sum = sum + Number($(this).val());
})
alert(sum);
if you for example group your inputs by giving them a class, or have each group in a div like so:
<!-- ordertotal = sum of #subtotal, #taxptotal, #shiptotal and #disctotal -->
<input type="text" id="ordertotal" name="ordertotal" value="106.49">
<input type="text" id="taxsptotal" name="taxsptotal" value="6.72">
<input type="text" id="shiptotal" name="shiptotal" value="15.83">
<input type="text" id="disctotal" name="disctotal" value="0.00">
<!-- sum of the cart "itemtotal[i]" -->
<input type="text" id="subtotal" name="subtotal" value="83.94">
<!-- cart items
User can change any itemprice[i] and/or itemquantity[i]
itemtotal[i] = sum(itemquantity[i] * itemprice[i])
-->
<div class="group">
<input type="text" name="itemtotal[1]" value="8.97" />
<input type="text" name="itemquantity[1]" value="3" />
<input type="text" name="itemprice[1]" value="2.99" />
</div>
<div class="group">
<input type="text" name="itemtotal[2]" value="4.59" />
<input type="text" name="itemquantity[2]" value="1" />
<input type="text" name="itemprice[2]" value="4.59" />
</div>
<div class="group">
<input type="text" name="itemtotal[3]" value="0.99" />
<input type="text" name="itemquantity[3]" value="10" />
<input type="text" name="itemprice[3]" value="9.90" />
</div>
Then you could do the following in javascript:
function calcSubTotal() {
$('[name^="itemtotal"]').each(function(i){
var sum = 0;
$('[name^="itemtotal"]').each(function(i){
sum += $(this).val();
});
$('#subtotal').val(sum);
});
}
$('.group').each(function(i) {
var total = $(this).find('[name^="itemtotal"]');
var qnt = $(this).find('[name^="itemquantity"]');
var price = $(this).find('[name^="itemprice"]');
total.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
qnt.keyup(function(e){
price.val(total.val() * qnt.val());
calcSubTotal();
});
});
$("[name^='itemprice'], [name^='itemquantity']").keyup(function(){
var input_name = $(this).attr('name');
var temp_name_split = input_name.split(/[\[\]]+/);
var temp_total = parseInt($('[name="itemquantity['+temp_name_split[1] +']"]').val()) * parseFloat($('[name="itemprice['+temp_name_split[1] +']"]').val());
$('[name="itemtotal['+temp_name_split[1]+']"]').val(temp_total.toFixed(2));
var total = 0;
$("[name^='itemtotal']").each(function() {
total += parseFloat($(this).val());
});
$('#subtotal').val(total.toFixed(2));
});

Different groups of checkbox not working in jquery

I prefer to get checked checkboxes from a specific checkbox group, depending on which button I have clicked, I used $('input[name="' + groupName + '"]:checked'). This will ensure that the checked checkboxes from only the coffee or animals checkbox group are selected. But it's not working as I expected.
<body>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee<br>
<input type="submit" id="__mainAnimals" />
<br><br><br><br><br><br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe<br>
<input type="checkbox" value="Tea" name="drinks" />Tea<br>
<input type="checkbox" value="Milk" name="drinks" />Milk<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha<br>
<input type="submit" id="__mainDrinks" />
</div>
<div id="__DIVresult"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#__mainAnimals').click(function () {
getSelectedCheckBoxes('animals');
});
$('#__mainDrinks').click(function () {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function (groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function () {
resultString += $(this).val() + "<br/>";
});
$('__DIVresult').html(resultString);
}
else {
$('__DIVresult').html("No checkbox checked");
}
};
});
</script>
</body>
1st id selector is # so $('__DIVresult') should be $('#__DIVresult')
2nd An ID should start with a letter for compatibility
Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
3rd some small update, added two result div, one for animal one for drink:
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
Then target them dynamically with $('#DIVresult'+groupName).html(resultString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="checkbox" value="Lion" name="animals" checked />Lion
<br>
<input type="checkbox" value="Tiger" name="animals" />Tiger
<br>
<input type="checkbox" value="Elephant" name="animals" />Elephant
<br>
<input type="checkbox" value="Girafee" name="animals" />Girafee
<br>
<input type="submit" id="mainAnimals" />
<br>
<br>
<br>
<br>
<br>
<br>
<input type="checkbox" value="Coffe" name="drinks" checked />Coffe
<br>
<input type="checkbox" value="Tea" name="drinks" />Tea
<br>
<input type="checkbox" value="Milk" name="drinks" />Milk
<br>
<input type="checkbox" value="Mocha" name="drinks" />Mocha
<br>
<input type="submit" id="mainDrinks" />
</div>
<hr>
animals Result:
<div id="DIVresultanimals"></div>
<hr>
drinks Result:
<div id="DIVresultdrinks"></div>
<script type="text/javascript">
$(document).ready(function() {
$('#mainAnimals').click(function() {
getSelectedCheckBoxes('animals');
});
$('#mainDrinks').click(function() {
getSelectedCheckBoxes('drinks');
});
var getSelectedCheckBoxes = function(groupName) {
var result = $('input[name="' + groupName + '"]:checked');
if (result.length > 0) {
var resultString = result.length + " checkboxe(s) checked<br/>";
result.each(function() {
resultString += $(this).val() + "<br/>";
});
$('#DIVresult'+groupName).html(resultString);
} else {
$('#DIVresult'+groupName).html("No checkbox checked");
}
};
});
</script>
In your drink and animal section you are not separating the two so when you use your click function it doesn't discriminate between the tow sections. Once you add each one to a class then the button will only call the checked items that are actually checked.
<html>
<form>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Lion" />Lion</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Tiger" />Tiger</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Elephant" />Elephant</br>
<input name="selector[]" id="ani" class="ads_Checkbox" type="checkbox" value="Girafee" />Girafee</br>
<input type="button" id="save_value" name="save_value" value="Save" /></br>
<textarea id="t"></textarea>
</form>
<script>
function updateTextArea() {
var allVals = [];
$('.ads_Checkbox:checked').each(function() {
allVals.push($(this).val());
});
$('#t').val(allVals);
}
$('#save_value').click(function(){
$('.ads_Checkbox:checked').each(function(){
updateTextArea();
});
});
Inside this code I have named each animal and placed them in a class so I could recall them from an array. I hoped this helped.

How to get a value and label in a textbox

function radioVal(){
//var radVal = document.mainForm.rads.value;
var radVal = document.getElementsByName("rads").value;
result.innerHTML = 'You selected: '+radVal;
}
<div class="pres">
<input type="radio" id="radio01" name="rads" value="10" checked />
<label for="radio01" class="dis"><span>1 time service</span></label>
</div>
<div class="pres">
<input type="radio" id="radio02" name="rads" value="20" />
<label for="radio02" class="dis"><span>Every week</span></label>
</div>
<div class="pres">
<input type="radio" id="radio03" name="rads" value="15" />
<label for="radio03" class="dis"><span>Every 2 weeks </span></label>
</div>
<div class="pres">
<input type="radio" id="radio04" name="rads" value="10" />
<label for="radio04" class="dis"><span>Every 4 weeks</span></label>
</div>
<input type="text" value="" id="result" name="perce" />
<input type="text" value="" id="txtservV" name="servicename" />
<input type="text" value="" id="final_pay" name="final_pay" />
Hello i am using this function to get the value of a selected radio button in a textfield name perce and its value in a field name servicename any one help me in it to sourt it out. I am using this function in doucument.ready function.
Use Document.getElementsByName function which returns array of elements (or better collection, array-like object), so that you can access value of input by index (0 in your case):
var perceVal = document.getElementsByName("perce")[0].value
In case of radio buttons you have to iterate through elements and find which one is checked:
var rads = document.getElementsByName("rads");
var radsValue;
for (var i = 0; i < rads.length; i++) {
if (rads[i].checked) {
radsValue = rads[i].value // here is checked radio
break;
}
}

How to get key (index) value of a textbox in array textboxes

I want a jQuery function or javascript that alert the index and the value of array textboxes : e.g.
<input type="text" name="textbox[]" value="1" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="foo" onblur="javascriptfunction(this.value,this.index)" />
<input type="text" name="textbox[]" value="banana" onblur="javascriptfunction(this.value,this.index)" />
Whenever mouse moves for example from the first input I have this alerted (1,0) and second is (foo,1) and so on. I couldn't find the function that does that. Please help.
You can use jQuery index() and val() like
$('input').blur(function(){
alert($(this).val() + ',' + ($(this).index()-1));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
Update
To target certain elements or have this in a named function, first, put identifiers on your elements such as a class my-class. Then, make a named function and pass it to the jQuery blur function
$('.my-class').blur( alertIndexAndVal );
function alertIndexAndVal(){
alert($(this).val() + ',' + ($(this).index()-1));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input class="my-class" type="text" name="textbox[]" value="1" />
<input class="my-class" type="text" name="textbox[]" value="foo" />
<input class="my-class" type="text" name="textbox[]" value="banana" />
var textboxes = $('input[name="textbox[]"]');
textboxes.on('blur', function() {
var index = textboxes.index( this );
alert( this.value + ', ' + index );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" name="textbox[]" value="1" />
<input type="text" name="textbox[]" value="foo" />
<input type="text" name="textbox[]" value="banana" />
I figured I'd post a javascript solution which to be honest attempts to do something like the index function of jquery although i think jquery function might be better.
var getIndexValue = function (e) {
var children = e.parentElement.children;
for (var i = 0; i < children.length; i++) {
if (children[i] == e) {
alert("Index: " + (i+1) + ", Value: " + e.value);
}
}
}
<div>
<input type="text" name="textbox[]" value="one" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="two" onblur="getIndexValue(this)">
<input type="text" name="textbox[]" value="three" onblur="getIndexValue(this)">
</div>
Index: (i+1)
Value: (e.value);

Check random checkboxes using JQuery

I know how to check and uncheck particular checkbox with ID and CLASS.
But I want to randomly select 10 checkbox using Jquery.
I will have 100,40 or XX number of checkbox everytime. (HTML Checkbox)
It might be 100 checkbox or 50 checkbox or something else. It will be different everytime.
I want to check 10 checkboxes randomly when a button is pressed.
User can manually select those 10 checkboxes. Or they can just press the random button.
I am using Jquery.
$(':checkbox:checked').length;
But i want to find the length of all the checkboxes and i want to check 10 random checkbox.
Are you looking for something like this?
http://jsfiddle.net/qXwD9/
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script>
//Creating random numbers from an array
function getRandomArrayElements(arr, count) {
var randoms = [], clone = arr.slice(0);
for (var i = 0, index; i < count; ++i) {
index = Math.floor(Math.random() * clone.length);
randoms.push(clone[index]);
clone[index] = clone.pop();
}
return randoms;
}
//Dummy array
function createArray(c) {
var ar = [];
for (var i = 0; i < c; i++) {
ar.push(i);
}
return ar;
}
//check random checkboxes
function checkRandom(r, nodeList) {
for (var i = 0; i < r.length; i++) {
nodeList.get(r[i]).checked = true;
}
}
//console.log(getRandomArrayElements(a, 10));
$(function() {
var chkCount = 100;
//this can be changed
var numberOfChecked = 10;
//this can be changed
var docFrag = document.createElement("div");
for (var i = 0; i <= chkCount; i++) {
var chk = $("<input type='checkbox' />");
$(docFrag).append(chk);
}
$("#chkContainer").append(docFrag);
$("#btn").click(function(e) {
var chks = $('input[type=checkbox]');
chks.attr("checked", false);
var a = createArray(chkCount);
var r = getRandomArrayElements(a, numberOfChecked);
//console.log(r);
checkRandom(r, chks);
});
});
</script>
</head>
<body>
<div id="chkContainer"></div>
<div>
<input type="button" id="btn" value="click" />
</div>
</body>
How about this:
Working example: http://jsfiddle.net/MxGPR/23/
HTML:
<button>Press me</button>
<br/><br/>
<div class="checkboxes">
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
JAVASCRIPT (JQuery required):
$("button").click(function() {
// How many to be checked?
var must_check = 10;
// Count checkboxes
var checkboxes = $(".checkboxes input").size();
// Check random checkboxes until "must_check" limit reached
while ($(".checkboxes input:checked").size() < must_check) {
// Pick random checkbox
var random_checkbox = Math.floor(Math.random() * checkboxes) + 1;
// Check it
$(".checkboxes input:nth-child(" + random_checkbox + ")").prop("checked", true);
}
});

Categories