Javascript, form, checkbox results into an array - javascript

I am trying to get the results from a form - in particular a multicheckbox.
So I want to get the results as a simple array
[2,4,6,5,7]
I've tried these -
$('.ids:checked').serialize()
$('.ids:checked').serializeArray()

Use jQuery map() method to generate the collection and get it as an array using get() method.
$('.ids:checked').map(function(){
// return the value, which would be the collection element
return this.value;
// get it as an array
}).get()
$("button").click(function() {
console.log($('input:checked').map(function() {
return this.value;
}).get());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="bla1" value="something1">
<input type="checkbox" name="bla2" value="something2">
<input type="checkbox" name="bla3" value="something3">
<input type="checkbox" name="bla4" value="something4">
<input type="checkbox" name="bla5" value="something5">
<input type="checkbox" name="bla6" value="something6">
</form>
<button>
Click
</button>
Or use jQuery.map() method to iterate and generate array where first argument in callback refers to the element.
$.map($('.ids:checked'),function(ele){
// return the value, which would be the array element
return ele.value;
});
$("button").click(function() {
console.log($.map($('input:checked'), function(ele) {
return ele.value;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="checkbox" name="bla1" value="something1">
<input type="checkbox" name="bla2" value="something2">
<input type="checkbox" name="bla3" value="something3">
<input type="checkbox" name="bla4" value="something4">
<input type="checkbox" name="bla5" value="something5">
<input type="checkbox" name="bla6" value="something6">
</form>
<button>
Click
</button>

var myArray = Array.prototype.map.call($('.ids:checked'), function(item){return item.value;});
use the core js array map method and binds it to your jquery object

Related

JS/jQuery for assigning values

I am trying to achieve this:
Currently value has been set on 2 radio buttons.
Once one of the button is selected, the value(attribute) of that button should be assigned to the value of the div with an id.
I am not sure where I am going wrong. Below is the code snippet.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
if (init_font_one == 'checked') {
init_id_value.val(init_font_one.val());
}
if (init_font_two == 'checked') {
init_id_value.val(init_font_two.val());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" value="abc"> Testing
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
You have to use on('change' to update the value of div when radio button is click. And use attr of jQuery to update the value of particular element.
Try this.
var init_font_one = $('input[id="init-one-name"]'),
init_font_two = $('input[id="init-two-name"]'),
init_id_value = $("#test");
init_font_one.change(function() {
init_id_value.attr("value",init_font_one.val());
console.log(init_id_value.attr("value"));
});
init_font_two.on('change',function() {
init_id_value.attr("value",init_font_two.val());
console.log(init_id_value.attr("value"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
There is few problems with your code:
<div> can't have value property.
Your code executes on page load and not when some event was triggered.
init_font_one == 'checked' compares jQuery object with string.
input[id="init-one-name"] can be replaced with #init-one-name
Your labels are not linked with inputs.
$('.radios').change(function() {
$("#test").val($('.radios:checked').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<!-- uncomment below -->
<!--<input type="hidden" id="test" value="abc"/>-->
<input type="text" id="test" value="abc" /> Testing
</div>
<input class="radios" id="init-one-name" type="radio" name="init-one-name" value="abcd"><label for="init-one-name">Test1</label>
<input class="radios" id="init-two-name" type="radio" name="init-one-name" value="xyz"><label for="init-two-name">Test2</label>
You should use jQuery change event to detect the change in the radio buttons and assign the value of checked radio button to the div with id="test"
var init_id_value = $("#test");
$('input[id="init-one-name"]').on('change', function() {
init_id_value.text($(this).val());
});
$('input[id="init-two-name"]').on('change', function() {
init_id_value.text($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
try this
$(document).ready(function(){
$("input[type='button']").click(function(){
var radioValue =
$("input[name='init-one-name']:checked").val();
if(radioValue){
alert("Your are a - " + radioValue);
}
});
});
I do not understand what you are trying to do, but try this:
$( "input[name='init-one-name']" ).change(function(){
$('#test').val('New Value: ' + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="test">Testing
</textarea><BR>
<input type="radio" name="init-one-name" value="abcd"><label>Op 1</label>
<input type="radio" name="init-one-name" value="xyz"><label>OP 2</label>
There is no value on a div, but you can change the text content or you can assing a "virtual value" to the div using .data()
Check the snippet
$(function(){ // On jquery initialize
var idtest = $('#test'); // the target Div
$('input[type="radio"]').on('change',function(){ // change event for the two radio buttons
/*** Method 1 : Using data attribute to assing a value ***/
idtest.data('value',$(this).val()); // Value of the selected radio
/*** Method 2 : Add the value of the selected radio to the text inside the div ***/
idtest.text( $(this).val() ) // Value of the selected radio
//retrieve the setted data value
console.log( idtest.data('value') );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"><label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"><label>Test2</label>
Refer to the fixed code below.
Added a listener to detect action performed over the radio buttons and changed method to check if radio is checked or not.
let ele = document.getElementById('init-one-div');
ele.addEventListener('click', function(e) {
if ("INPUT" === e.target.nodeName)
checkAndAssign();
});
function checkAndAssign() {
var init_font_one = $('#init-one-name'),
init_font_two = $('#init-two-name'),
init_id_value = $("#test");
if (init_font_one.is(':checked')) {
init_id_value.val(init_font_one.val());
}
if (init_font_two.is(':checked')) {
init_id_value.val(init_font_two.val());
}
//REMOVE below line if you want to remove the line printing the result
init_id_value.html(' Testing [ ' + init_id_value.val() + ' ] ');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test" value="abc">
Testing
</div>
<div id="init-one-div">
<input id="init-one-name" type="radio" name="init-one-name" value="abcd"> <label>Test1</label>
<input id="init-two-name" type="radio" name="init-one-name" value="xyz"> <label>Test2</label>
</div>

jQuery - Sending "Select All" Check boxes with Multiple Forms

I have checked online for a solution to pass my values for the checkbox "select all". I have multiple forms in a page. So I will need to separate passing the values based on specific forms.
jQuery:
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
});
})
HTML for form:**
<div class="col">
<fieldset>
<form action="{$link->getLink('controller')|escape:'htmlall':'utf-8'}" method="post">
<p>
{foreach from=$payment item=row}
<input type="checkbox" name="payment[]" maxlength="50" value={$row.id_order}>
<label> ID: <b>{$row.id_order}</b></label><br/>
{/foreach}
<br/>
<input id="submit" name="submitpayment" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
Error (Value is empty):
input type="checkbox" class="select-all" name="payment[]" value=""
SQL query to pass records:
public function displayOrdersbyID()
{
$query1 = new DbQuery();
$query1->select('o.id_order')
->from('orders','o')
->leftJoin('carrier','c','o.id_carrier=c.id_carrier')
->leftJoin('order_state_lang','s','o.current_state=s.id_order_state')
->where('c.name = ' . "'XXX'")
->where('s.name = ' . "'Payment accepted'");
$payment = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query1);
$this->context->smarty->assign( 'payment', $payment);
Controller:
if (Tools::isSubmit('submitpayment')) {
$ids= Tools::getValue('payment');
$query18 = new DbQuery();
$query18->select('id_order_state')
->from('order_state_lang')
->where('name = ' . "'Processing in progress'");
$updateinprogress = Db::getInstance()->getValue($query18);
foreach ($ids as $updateids) {
$objOrder = new Order($updateids);
$history = new OrderHistory();
$history->id_order = (int)$objOrder->id;
$history->id_employee = $cookie->id_employee;
$history->changeIdOrderState($updateinprogress, (int)($objOrder->id));
$history->add(true);
$history->save();
}
}
SELECT ALL checkbox:
<input type="checkbox" class="select-all" name="payment[]" value=
{$row.id_order}>
<label> SELECT ALL</label>
I was using the above code to create a SELECT ALL checkbox for the form, placing it outside the loop. I understand it is wrong and value is not passing, where should I place the checkbox at?
Any guidance is appreciated.
Thank you.
I think the problem in select-all value because there no initialization for $row.id_order in
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
But if you assign the value of $row.id_order then might be not used in the following child like the {foreach from=$payment item=row} must use another variable identifier then row.
you working with a wrong practice you can't assign $row.order_id outside the loop.If there you want to use these element value in PHP then no need to do anything the $_POST['payment'] for the second form and $_POST['inprogress'] will return the value you want.
if no checkbox is selected then the result is returned blank.
and remember this will return an array type object.
The line
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
lies outside the loop. Thus the value of {$row.id_order} will not be defined in your template. Check the DOM tree for compiled value.
And what is your final goal with the SELECT ALL button ? Is there any relation between the two forms?
Edit:
See the value of output variable. You can collect this value and pass it along with form submission.
<div class="col">
<fieldset>
<form>
<p>
<input type="checkbox" class="select-all" name="payment[]" value="22">
<label> SELECT ALL</label>
<br/><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="a">
<label> ID: <b>A</b></label><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="b">
<label> ID: <b>B</b></label><br/>
<input id="submit" name="submitinprogress" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
let inputs = $(this).siblings("input[type=checkbox]");
let output = [];
for(let i = 0; i < inputs.length; i++){
output.push(inputs[i].value);
};
console.log(output); // ["a", "b"]
});
});

How to insert value of checked checkbox in array using jQuery

I want select all input values that is checked and has name DisbursementUnitCodes
$('input:checked[name=DisbursementUnitCodes]').val()
This code give the first element value but i want give all input value to list or array.
Use .each() to iterating selected elements and get value of its.
var arr = [];
$("input:checked[name=DisbursementUnitCodes]").each(function(){
arr.push($(this).val());
});
console.log(arr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="DisbursementUnitCodes" value ="A" checked />
<input type="checkbox" name="DisbursementUnitCodes" value ="B" />
<input type="checkbox" name="DisbursementUnitCodes" value ="C" checked />
<input type="checkbox" name="other" value ="D" checked />
<input type="checkbox" name="other" value ="E" />
.val() gives you value of first element in selection. If you want all values in array, you should use .map() like this:
var values = $('input:checked[name=DisbursementUnitCodes]').map(function() {
return $(this).val();
}).get();

How to display value of checkbox?

I want to display all the cheked values of a chekbox, this is my attempt:
<p>jQuery is :</p>
<input type="checkbox" id="s" name="super"> Super !<br>
<input type="checkbox" id="g" name="genial"> Génial<br>
<input type="checkbox" id="j" name="joli"> Joli<br>
<input type="button" value="display" id="disp">
<script>
$('#disp').click(function(data){
$("input[type=checkbox]").is(":checked");
alert($("this").val());
});
</script>
Certainly you could try a little bit harder to solve this on your own, no?
Regardless, your checkboxes don't have value attributes defined: name & value are different attributes.
$('this') would try to make a collection of <this> elements, and $(this) would refer to the button in that event handler.
You're looking for something along these lines:
http://jsbin.com/luyaweqaqe/1/edit?html,js,output
HTML
<input type="checkbox" value="super"> Super !<br>
<input type="checkbox" value="genial"> Génial<br>
<input type="checkbox" value="joli"> Joli<br>
<button id="bt">Check</button>
JS
$('#bt').on('click', function () {
var arr = [];
$('input[type="checkbox"]:checked').each(function () {
arr.push($(this).val());
});
alert(arr);
});
Here's some reading material:
jQuery API
HTML Attributes
It cannot get the value with .val because there is no value. Try something like this:
<p>jQuery is :</p>
<input class="box" type="checkbox" value="Super">Super</br>
<input class="box" type="checkbox" value="Génial">Génial</br>
<input class="box" type="checkbox" value="Joli">Joli</br>
<input type="button" value="display" id="disp">
$('#disp').click(function () {
$(".box:checked").each(function () {
alert($(this).val());
});
});
JS fiddle: https://jsfiddle.net/ms14eLz0/1/
Hi you can try something like this. You do not need data in your function as your not passing anything in it. What this should do is find all the boxes which are checked and then loop through them and add them to the array. Then alert it at the end.
$('#disp').click(function () {
var array = [];
$(".box:checked").each(function () {
array.push($(this).val());
});
alert(array + ' checked');
});

jQuery: Add values of checkboxes to input text field

I'm trying to add the values of any checked checkbox to an input text field.
Here's my fiddle: http://jsfiddle.net/Lf6ky/
$(document).ready(function() {
$(":checkbox").on('click', function() {
if ($(':checkbox:checked')) {
var fields = $(":checkbox").val();
jQuery.each(fields, function(i, field) {
$('#field_results').val($('#field_results').val() + field.value + " ");
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
In this example, I have 3 checkboxes, with the values 1,2,3. If I click on all these checkboxes, then the input field should look like this: 1 2 3
If I uncheck any of these checkboxes, then that corresponding value should disappear in the input field.
How do I do this?
I've stored the collection of check-boxes in a variable $checks, then attach the handler to this collection. Inside the event handler, I take the collection once again and filter (return) only the check-boxes that are checked.
map() returns a jQuery object containing the values of the checked check-boxes, get() converts it to a standard array. Join those values with a space and put 'em in the input.
$(document).ready(function(){
$checks = $(":checkbox");
$checks.on('change', function() {
var string = $checks.filter(":checked").map(function(i,v){
return this.value;
}).get().join(" ");
$('#field_results').val(string);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="field_results"/><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
On click of a checkbox, loop through the checked inputs, append to a string then assign that to your text box:
$(document).ready(function() {
$("input:checkbox").click(function() {
var output = "";
$("input:checked").each(function() {
output += $(this).val() + " ";
});
$("#field_results").val(output.trim());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" /><br>
<input type="checkbox" value="1">1<br>
<input type="checkbox" value="2">2<br>
<input type="checkbox" value="3">3
First issue is
if($(':checkbox:checked')) {
will always be true since it returns a jQuery object and an object is a truthy value. If you were to use the if, you want to check the length. aka if($(':checkbox:checked').length) {
Secondly
var fields = $(":checkbox").val();
returns only the first element's value and it returns any checkbox, not just the checked ones. You want to loop through $(':checkbox:checked')
One way to attack it is to use an each and an array.
$(":checkbox").on('change', function() {
var total = [];
$(':checkbox:checked').each( function(){ //find the checked checkboxes and loop through them
total.push(this.value); //add the values to the array
});
$('#field_results').val(total.join(" ")); //join the array
});
Problem
if($(':checkbox:checked')) will always be true
var fields = $(":checkbox").val(); Will give first checkbox value
You can try this.
$(document).ready(function() {
$(":checkbox").on('click', function() {
var fields = '';
$(":checkbox").each(function() {
if (this.checked) {
fields += $(this).val() + ' ';
}
});
$('#field_results').val($.trim(fields))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" id="field_results" />
<br>
<input type="checkbox" value="1">1
<br>
<input type="checkbox" value="2">2
<br>
<input type="checkbox" value="3">3

Categories

Resources