Get dynamically value from checkbox jQuery - javascript

I need help with get value from checkbox with jQuery.
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
var $this = $( this ),
value = $this.val();
value_array.push( value );
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>
If category 1 checked, getting value (correct).
If category 2 checked, getting value (correct).
If category 1 un-checked, getting value again (false, i don't want
it).
If category 2 un-checked, getting value again (false, i don't want
it).
I want like this:
If category 1 un-checked, remove the value from output array.
If category 2 un-checked, remove the value from output array.

Check if checkbox is checked, add value into array if it is, remove if it's not.
$(document).ready(function() {
var value_array = [];
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
if ($this.prop('checked')) value_array.push(value);
else value_array.splice(value_array.indexOf(value), 1);
console.log($.unique(value_array));
$('#out').html($.unique(value_array).join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>

You don't have to declare an array to begin with (which will pollute your namespace anyway). You can simply select for all the checkboxes, use .filter() to keep those that are checked, and the use .map() to return their values, all done within the callback of the onchange event listener:
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
Note: Remember to chain .get() at the end of .map(), because it will return a jQuery object/collection and you have to convert it into an array.
See proof-of-concept example below:
$(document).ready(function() {
$(document).on('change', '.radio-group input', function(e) {
var $this = $(this),
value = $this.val();
// Get values of checked checkboxes
var value_array = $('.radio-group input').filter(':checked').map(function() {
return this.value;
}).get();
console.log(value_array);
$('#out').html(value_array.join())
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio-group">
<label>
<input type="checkbox" name="cat_1" value="90" />
Category 1
</label>
<label>
<input type="checkbox" name="cat_2" value="43" />
Category 2
</label>
</div>
<div id="out">
</div>

You can just fetch an array of all checked values at once:
$( document ).ready( function() {
var value_array = [];
$( document ).on( 'change', '.radio-group input', function(e) {
value_array = $('.radio-group input:checked').map(function() {
return $(this).val();
}).get();
console.log( $.unique( value_array ) );
$( '#out' ).html( $.unique( value_array ).join() )
});
});
JSFiddle

First, you should understand that the "this" value refers to the object that owns the code. In your case, the "this" in
$( document ).on( 'change', '.radio-group input', function(e)
refers to the "document" itself and not the ".radio-group input". Instead you should do the following so that the "this" refers to your checkbox.
var arr = [];
$(".radio-group input").change(function(){
var val = $(this).val();
//push the value into the array if the checkbox is checked
if($(this).prop("checked")==true)
{
arr.push(val);
}
//otherwise, remove the value from the array
else{
//fetch the index of the value in the array
var index = arr.indexOf(val);
//remove that value from the index
arr.splice(index,1);
}
});

Related

how to select singel and multiple checkbox with radiobutton

i'm stuck with this problem. i have 2 radiobutton and few checkbox. what i want to do is if radiobutton1 chacked, it only allow check 1 checkbox, then if radiobutton2 chacked, it will allow all checkbox to be checked.
i've been tried some script, but not any of them work.
this is my code for sample.
HTML
<input type="radio" id="radio1" name="radiobtn1" />
<input type="radio" id="radio1" name="radiobtn2" />
<input type="checkbox" name="cb" value="1" onclick="test(this)" />
<input type="checkbox" name="cb" value="2" onclick="test(this)"/>
<input type="checkbox" name="cb" value="3" onclick="test(this)"/>
<input type="checkbox" name="cb" value="4" onclick="test(this)"/>
<input type="checkbox" name="cb" value="5" onclick="test(this)"/>
script for select only 1 checkbox
function test(id){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
my script
$(function test(id){
$("#radio1, #radio2").change(function(){
if($("#radio1").is(":checked")){
var cb = document.getElementsByName("cb");
Array.prototype.forEach.call(cb,function(el){
el.checked = false;
});
id.checked = true;
}
else if($("#radio2").is(":checked")){
}
});
});
thank you for your help.
it's like your question has been solved.
next time try to find it first.
but you can try this script.
var $form = $('#form1');
var $checkboxes = $('input[type=checkbox]');
var $selectionType = $('input[type=radio]');
var $output = $('#output');
// Used to determine if the Multi radio is selected
var isMulti = false;
// Listen to change event on the radio buttons and set isMulti
$selectionType.on('change', function( e ) {
// Check the value of what radio button was clicked
isMulti = $( e.target ).val() === 'Multi';
// Clear all selected checkboxes if user clicked "single"
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
$( item ).prop( 'checked', false );
});
}
});
// Listen to clicks on checkboxes
$checkboxes.on('change', function( e ) {
// Store what was just clicked
var $this = $( e.target );
// If Multi is not selected, then remove the check from all checkboxes except
// the one that the user actually clicked on
if( !isMulti ) {
$checkboxes.each( function( idx, item ) {
var $item = $( item );
if( $item.attr('id') === $this.attr('id') ) {
return true;
}
$item.prop('checked', false );
});
}
});
http://jsfiddle.net/grammar/pdx8gccu/2/

Remove clicked id from the input value

I am trying to delete clicked id to remove input value. For example i have this input <input type='hidden' id='uploadvalues' value="8,9"/> you can see the values 8,9 and the button is <div class="delete" id="9"></div> .
When i click the id="9" then the input value 9 should be remove . After clicked id="9" ==> <input type='hidden' id='uploadvalues' value="8"/>
How can i do that anyone can teach me?
Demo from CodeCanyon
<div class="container">
<div class="area">
<div class="image"><img src="https://s-media-cache-ak0.pinimg.com/736x/05/2f/1b/052f1b3a2361eb4f3c1385c1fd4f75ed.jpg"></div>
<div class="delete" id="8"></div>
</div>
<div class="area">
<div class="image"><img src="http://www.wallpapermade.com/images/wallpapers/originals/tip-and-oh-laugh-together-home-2015-movie-wallpaper-4612.jpg"></div>
<div class="delete" id="9"></div>
</div>
<input type='hidden' id='uploadvalues' value="8,9"/>
</div>
JS
$(document).ready(function(){
$("body").on("click", ".delete", function(){
// Remove clicked id from the input value
});
});
One way on the approach you want is
$("body").on("click", ".delete", function(){
var id = this.id, //extract the id from the clicked element
values = $('#uploadvalues').val().split(','), // get the existing values in the #uploadvalues element
remaining = values.filter(function(val){ // filter out the ones equal to the id of the clicked element
return val !== id;
});
$('#uploadvalues').val(remaining.join()); // update the changed values
});
make it
$(document).ready(function(){
$("body").on("click", ".delete", function(){
var val = $(this).attr("id");
var values = $( "#uploadvalues" ).val().split(",");
var valIndex = values.indexOf(val);
if (valIndex > -1)
{
values.splice(valIndex,1);
}
$( "#uploadvalues" ).val( values.join(",") )
});
});
Try to make use of regular expression at this context,
$(document).ready(function() {
$("body").on("click", ".delete", function(){
var id = this.id;
$("#uploadvalues").val(function(val){
return val.replace(new RegExp(id + "\,|\,"+ id +"$"),"")
});
});
});
when you click the delete button, in the callback function grab the id:
var valueToRemove = this.id;
// now you need to look to see if that value is inside the hidden input
var valueToRemove = this.id;
console.log(valueToRemove);
var values = $("#uploadvalues").val();
if(values.indexOf(valueToRemove) >= 0){
$("#uploadvalues").val(values.replace(valueToRemove,""));
}
also its best practice to cache the dom so you dont have to constantly query it.
Is this what you wanted? and this method does not get rid of the comma within the values.

Combine multiple input prices to one TOTAL

So the script starts with an initial value $8.90 and the idea is to add a extra fee depending on the options that are selected, the HTML is divided by 3 sections 1.check-boxes, 2.Select and 3.input(text).
Each section works independently and I'm trying to find a way to combine all 3 sections so the TOTAL can show the final result depending on the options that were selected.
LIVE EXAMPLE
JQUERY:
$(document).ready( function() {
<!-- COUNTRY OPTIONS SCRIPT -->
$('#country').on('keyup change', function(e){
//Changed the following line to get the original value
var subt_value = $('#subt0').attr('data-original');
//Changed this to say, NOT AR and has a choice per the comments.
if($(this).val() != 'AR' && $(this).val().length > 0) {
var add_sub = parseFloat(subt_value)+parseFloat('10.00');
$('#subt0').text(parseFloat(add_sub).toFixed(2));
} else {
//Otherwise put it back to the original value
$('#subt0').text(subt_value);
}
});
<!-- END COUNTRY OPTIONS SCRIPT -->
<!-- CHECKBOX OPTIONS SCRIPT -->
var start_price = parseFloat($('#subt0').attr('data-original'));
$("#ser1, #ser2").click(function(){
var amountToAdd = 0.0;
$("#ser1, #ser2").each(function() {
if($(this).is(":checked")){
amountToAdd += parseFloat($(this).attr('data-price'));
}
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END CHECKBOX OPTIONS SCRIPT -->
<!-- INPUT OPTIONS SCRIPT -->
$(".opts").click(function() {
var amountToAdd = 0.0;
$(this).each(function() {
$("#map_sector").val($(this).attr('data-price'));
amountToAdd += parseFloat($(this).attr('data-price'));
});
$('#subt0').text(parseFloat(amountToAdd+start_price).toFixed(2));
});
<!-- END INPUT OPTIONS SCRIPT -->
});
HTML:
<input name="service1" type="checkbox" id="ser1" data-price="1" value="1" title="Service 1" />
<input name="service2" type="checkbox" id="ser2" data-price="5" value="1" title="Service 2" />
<select id="country">
<option value="AR">Argentina</option>
<option value="US">USA</option>
<option value="BR">Brasil</option>
<option value="CU">Cuba</option>
</select>
<input name="map_sector" type="text" id="map_sector" value="5" readonly>
<label class="opts" data-price="1">Option #1</label>
<label class="opts" data-price="5">Option #2</label>
<label class="opts" data-price="8">Option #3</label>
<div>TOTAL: <label id="subt0" data-original="8.90">8.90</label></div>
LOOKING FOR THIS RESULT:
If 2 check-boxes selected: $14.90 + Option (USA) selected: $10.00 + Option#2 selected: $5.00: TOTAL: $29.90
I would use AJAX to 'submit' the form to a PHP script that would calc the price and return it as a result. You use AJAX to prevent the default submit and then POST to the form to the PHP page. Use isset() to check the different options and based on either the isset() or the value of the POST variable modify a variable, and then echo that variable at the end of the PHP.
EDIT: IGNORE THE FIRST PART.
This should work for the select and the checkboxes, im not sure how you are handling the labels.
<script>
//ASSIGN CLASSES TO EACH TYPE OF INPUT I.E. <input name="service1" type="checkbox" class="serviceCheckbox" id="ser1" data-price="1" value="1" title="Service 1" />
//ALSO ASSIGN data-price TO SELECT ELEMENTS ( even if it is 0 )
window.originalCost = 8.90; //window is how you explicitly assign global variables.
window.cost = originalCost;
$( document ).on( 'click', '.serviceCheckbox', function()
{
var thisCost = $( this ).attr( 'data-price' );
if ( $( this ).prop( 'selected' ) == true )
{
addCost( thisCost );
}
else
{
subractCost( thisCost );
}
});
$( document ).ready( function()
{
var previousCost;
var currentCost;
$( document ).on( 'focus', '#country', function()
{
previousCost = $( this ).attr( 'data-price' );
});
$( document ).on( 'change', '#country', function()
{
currentCost = $( this ).attr( 'data-price' );
var priceChange = currentCost*1 - previousCost*1;
if ( priceChange > 0 )
{
addCost( priceChange );
}
else
{
subtractCost( priceChange );
}
});
});
function addCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 + cost*1;
window.cost = finalCost;
}
function subractCost( cost )
{
var currentCost = window.cost;
var finalCost;
cost = parseFloat( cost );
finalCost = window.cost*1 - cost*1;
window.cost = finalCost;
}
</script>
and then you would have to translate the window.cost variable into the text for the label. Let me know if this works ( might need minor tweaking ) but I believe the logic is sound.
I will divide the logic into two parts to make things manageable and easy to understand.
Elements that are involved in price update would all have data-price so we can pick it up
Elements on click would just place a class on all selected elements and if needed remove class from other elements where switch is needed.
A single function to calculate price.
Please see this
http://jsfiddle.net/farrukhsubhani/Q2XVw/2/
function CalculateTotalPrice() {
var totalPrice = 0.0;
$(".priceitem").each(function(){
totalPrice += parseFloat($(this).attr("data-price"));
});
$("#subt0").html("$" + totalPrice);
}
I have changed your html and js to make things work.

Get values of dynamic fields with random ids

I have a form where you can add input fields dynamically with jQuery.
<form class="test">
1. <input type="text" class="title" id="title-1" placeholder="title">
1. <input type="text" class="subtitle" id="subtitle-1" placeholder="title">
<br />
2. <input type="text" class="title" id="title-2" placeholder="subtitle">
2. <input type="text" class="subtitle" id="subtitle-2" placeholder="subtitle">
</form>
<span class="addField">Add new fields</span>
var count=0; var arr=[]
while(count< noOfFields){
var id = '#title' + count;
var arr[count]=$(id).val();
count++;
}
I want to get the values of each pair of text fields (title/subtitle) and save them to a Mysql database. My question for this moment is: how to get the contents of the fields (with dynamic id) with jQuery?
I would use about each feature, which I have been looking all input and then comparing what they id
$(".test").find("input").each(function(){
var id = $(this).attr("id");
});
you can get values by using each value with selecting classes. code could be something like.
var arr1 = {};
$( ".title" ).each(function( index ) {
var arr1[index] = $( this ).val() ;
});
var arr2 = {};
$( ".subtitle" ).each(function( index ) {
var arr2[index] = $( this ).val() ;
});
you will get all data within arr1 and arr2 inputs.

Detect the largest number in inputs

I want Detect the largest number in inputs and done alert for it, How is it in following code by jQuery?
Example: http://jsfiddle.net/3cTqD/
<input type="text">
<input type="text">
<input type="text">
<input type="text">
<button>Click Me</button>
$('button').live('click', function(){
$('input').each(function(){
var val = $('this').val();
alert(val); // i want done alert largest number from input
})
})
$( 'button' ).live( 'click', function(){
alert(
Math.max.apply( Math, $( 'input' ).map( function(){
return 0|this.value;
}).get())
);
} );
$('button').live('click', function(){
var i = 0;
$('input').each(function(){
var val = $(this).val();
if(val > i) i = val;
});
alert(i);
});

Categories