Pass Array HTML Element(s) in JavaScript - javascript

I have array of checkboxes like below,
<input type="checkbox" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="checkbox" value="1" id="a_r_id[2]" name="a_r_id[2]">
<input type="checkbox" value="1" id="a_r_id[3]" name="a_r_id[3]">
<input type="checkbox" value="1" id="a_r_id[4]" name="a_r_id[4]">
in my page... and i want to submit only the checked one via JavaScript (jQuery AJAX)... how can i do that ?
EDITED :
Actually, i want to get all array keys on the checked checkbox so that i can post it via ajax. Something like "1,4" as a string.

var keys = [],
keystring;
$('input[name^="a_r_id"]:checked').each(function () {
keys.push($(this).attr('name').replace(/a_r_id\[(\d+)\]/, '$1'));
});
keystring = keys.join();
Of course, there are better ways of doing this, but this answers your question as you've framed it.

Finally, i found an answer for my question above. I'll write it down right here.
Problem :
how can i get "key" from array HTML element(s) ? (in my case, only checked checkbox i want to get)
my answer code is something like this :
//first, i get every checked checkbox using jQuery selector,
//as mentioned by DerekHenderson.
var list_agent = $('input[name^="a_r_id"]:checked');
var l_c_agent = new Array();
//then, i create a loop to loop each object returned.
for(var i=0;i<list_agent.length;i++){
//after that, i'm using Regular Expression ( match() ) on every returned object id and throw it into some array.
l_c_agent[i] = list_agent[i].id.match(/[0-9]+/);
}
//finally, i join the array using javascript join() method so that i can pass it using jQuery AJAX as a string to my controller and process it.
var clean_agent_list = l_c_agent.join();
var add_url = 'test.php';
$.ajax({
url: add_url,
type: "GET",
data : { 'list_agent' : clean_agent_list },
success: function(data_return) {
//alert(data_return);
}
});
the output will be something like this (if using my example question above and we're check element with id 1,3 and 4 only)
1,3,4
if anybody have a better code, please write it here so that we can discuss which is better to solve my problem.

The method you want seems a bit backwards; the browser will already submit only the checked checkboxes, but here goes:
var re = /\[(\d+)\]$/,
numbers = [];
$('input[name^="a_r_id\\["]:checked').each(function() {
numbers.push(+this.name.match(re)[1]);
});
console.log(numbers.join(','));
It selects all checked boxes whose name starts with "a_r_id[". Then, a regular expression is used to extract the number portion between square brackets and added to the list of values.

I think you want to do something like this
<input type="checkbox" value="1" id="a_r_id_1" name="a_r_id[]">
<input type="checkbox" value="2" id="a_r_id_2" name="a_r_id[]">
<input type="checkbox" value="3" id="a_r_id_3" name="a_r_id[]">
<input type="checkbox" value="4" id="a_r_id_4" name="a_r_id[]">

Radio Buttons seems to be more applicable here rather than checkboxes try this:
<input type="radio" name="radiogroup" value="1" id="a_r_id[1]" name="a_r_id[1]">
<input type="radio" name="radiogroup" value="2" id="a_r_id[2]" name="a_r_id[2]">
<input type="radio" name="radiogroup" value="3" id="a_r_id[3]" name="a_r_id[3]">
You can get the selected value using
$("input:radio[name=radiogroup]").click(function() {
var value = $(this).val();
//
do something with var
//
});

Related

How do I retrieve values from checkboxes in JavaScript, using onchange to trigger a function?

I'm a High School student who takes a programming course (JavaScript) at school. We just had a test (which I miserably failed), but we are allowed to try again.
I have a couple of checkboxes. They all have an onchange which triggers a function later. I want to retrieve their values when I click on the checkboxes.
I've browsed around here a bit and seen something called jQuery. I have no idea what that is, so I would highly appreciate to get my help in pure JavaScript.
Okay, here is what I have of code. Note: Some variables and such are in Norwegian. I don't think it should be a problem, since I show the references to all.
My inputs (checkboxes):
<input type="checkbox" class="tur" value="0" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="1" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="2" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="3" onchange="funcSjekkBoks(this)">
<input type="checkbox" class="tur" value="4" onchange="funcSjekkBoks(this)">
I only need their value to be numbers, since I will use those in reference to an array list I have later.
Here is my function:
var inputTur = document.getElementsByClassName("tur");
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
var resultatListe = [];
if (checkboxEl.checked) {
resultatListe.push(inputTur.value);
console.log(resultatListe);
}
else {
console.log("usant")
}
}
What I would like to happen (if all checkboxes are checked from top to bottom):
resultatListe = [0, 1, 2, 3, 4]
When I uncheck a checkbox, it's value will be removed from the array.
Here is what currently happens:
When I check a checkbox I get [undefined] in my console, when I uncheck a checkbox I get usant (although that is the expected response, I haven't worked with the else part of my if-sentence yet.)
Below code will work for you:
var resultatListe = [];
function funcSjekkBoks(checkboxEl) {
var value = parseInt(checkboxEl.value);
if (checkboxEl.checked) {
resultatListe.push(value);
console.log(resultatListe);
}
else {
console.log("usant");
var indexToRemove = resultatListe.indexOf(value);
resultatListe.splice(indexToRemove,1);
}
}
You need to keep the array resultatListe outside the function other it will be initialized to empty everytime a checkbox is checked/un-checked, triggering the onchange handler. You were getting undefined as you were accessing 'value' property on HTMLCollection object which does not contain that property. Read more about it on MDN
var inputTur = document.getElementsByClassName("tur");
var resultatListe = [];
console.log(inputTur);
function funcSjekkBoks(checkboxEl) {
if (checkboxEl.checked) {
resultatListe.push(parseInt(checkboxEl.value));
}
else {
resultatListe = resultatListe.filter(d => d != checkboxEl.value)
}
console.log(resultatListe);
}
There were 2 mistakes in your logic:
1) You need to define resultatListe outside the function so that it won't get initialized to an empty array everytime
2) In you code resultatListe.push(inputTur.value); inputTur is the HTMLCollection of checkboxes whereas you need the single checkbox.
For the else logic, if the value of each checkbox is going to be unique you can use array.prototype.filter method to filter out the value of checkbox from resultatListe

How to get data attribute from radio button with JavaScript?

I want to get the data-price value from radio button which is checked. I tried something like that:
<input type="radio" name="vehicletype" id="vehicletype" value="{{$vehicletypeData->id}}" data-price="{{$vehicletypeData->km_rate}}" required="">
var vehicleTyp=document.getElementById("vehicletype");
var vetselindx=vehicleTyp.options[vehicleTyp.selectedIndex];
var prikm=vetselindx.getAttribute("data-price");
But this does not work. How can I solve this issue?
document.getElementById("vehicletype");
This gets the element with that id. The single element with that id. Multiple elements in a document cannot share an id.
vehicleTyp.options
Select elements have options. Radio buttons do not.
To find the checked element you should:
Get all the radio buttons. Consider getElementsByName
Loop over them until you find one where the checked property is true
Once you have found the element you are looking for you can use getAttribute("data-price"); or the dataset property.
You can reference the custom data- attributes of an element like so:
const el = document.getElementById("vehicletype");
const price = el.dataset.price;
For more information see the MDN docs on using data attributes.
Note: If you have a second dash in the attribute name e.g. data-price-new the dataset object property will reflect this in camelcase. dataset.priceNew
Working code, using getElementsByName
<input class="form-check-input" type="radio" data-type="one-time" name="payment-radio-btn" value="200" id="flexRadioDefault1" checked />One Time
<input class="form-check-input" type="radio" data-type="two-time" name="payment-radio-btn" value="300" id="flexRadioDefault1"/>Two time
<p> <button onClick="performAction()">Submit</button> </p>
function performAction(){
var amount = 0;
var type = '';
var radios = document.getElementsByName('payment-radio-btn');
for (var radio of radios) {
if (radio.checked) {
amount = radio.value;
type = radio.getAttribute("data-type");
}
}
alert(type)
}
Codepen-link

Check one checkbox when other is selected [duplicate]

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

Insert a multiple choice in a html page

What I have to do is to make the user select some languages among those present on a page and get an array or a string that contains all the selected languages.
Do you know how can I do?
The string or array it will serve subsequently in a JavaScript method.
you could use some checkboxes and save the values in an array like this:
var lang = [];
$('.cbLang').on('change', function() {
this.checked ? lang.push(this.value) : removeLang(this.value);
console.log(lang);
});
//REMOVE UNCHECKED LANGUAGE
function removeLang(removeLang){
lang = jQuery.grep(lang, function(value) {
return value != removeLang;
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="cbLang" type="checkbox" value="English">English
<input class="cbLang" type="checkbox" value="German">German
<input class="cbLang" type="checkbox" value="French">French
EDIT: If you also need a way to remove it from the array, check the JQuery grep(): http://api.jquery.com/jquery.grep/
EDIT2: I've added a function to remove a unchecked language from the array. This method calls, when a checkbox was unchecked and gives the value of the language as parameter. It should work like this.
Cheers
javascript
var lang = [];
$('.cbLang').on('change', function() {
''
this.checked ? lang.push(this.value) : removeLang(this.value);
console.log(lang);
});
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="cbLang" type="checkbox" value="English">English
<input class="cbLang" type="checkbox" value="German">German
<input class="cbLang" type="checkbox" value="French">French

Naming Lots of Input Checkboxes with a Counter

This is a pretty straightforward question, but I wasn't able to find the answer to it.
Is it possible to do something like this with JavaScript and HTML? So below the names of the checkboxes in order would be 1, 2, 3, 4
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
<input type="checkbox" name=counter()>
function counter() {
i++;
return i;
}
No, but yes in a different way. Don't include the name attribute (or set the value as ""), and put this code after your checkboxes:
<script type="text/javascript">
var chx = document.getElementsByTagName("input");
for (var i = 0; i < chx.length; i++) {
var cur = chx[i];
if (cur.type === "checkbox") {
cur.name = "checkbox" + i;
}
}
</script>
DEMO: http://jsfiddle.net/bLRLA/
The checkboxes' names will be in the format "checkbox#". This starts counting at 0. If you want to start the names with 1 instead (like you did say), use cur.name = "checkbox" + i + 1;.
Another option for getting the checkboxes is using:
var chx = document.querySelectorAll('input[type="checkbox"]');
With this, you don't have to check the .type inside the for loop.
In either case, it's probably better not to use document, and instead use some more specific container of these elements, so that not all checkboxes are targeted/modified...unless that's exactly what you want.
In the demo, I added extra code so that when you click on the checkbox, it will alert its name, just to prove it's being set properly. That code obviously isn't necessary for what you need....just the code above.
This code could be run immediately after the checkboxes, at the end of the <body>, or in window.onload.
You can get a nodeList of all inputs on the page and then loop through them adding the loop index to whatever the common name string you want for those that have a type of "checkbox". In the following example I have used Array.forEach and Function.call to treat the array like nodeList as an array, to make looping simple.
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
var inputs = document.getElementsByTagName("input");
Array.prototype.forEach.call(inputs, function (input, index) {
if (input.type === "checkbox") {
inputs.name = "box" + index;
}
});
on jsfiddle
Finally, though this has been demonstrated as possible, I think you need to be asking yourself the question "why would I do it this way?". Perhaps there is a better alternative available to you.
Since you're most probably processing the form server-side. you can possibly not bother altering the form markup client-side. For example, simple changing your form markup to the following will do the trick:
<input type="checkbox" value="One" name=counter[]>
<input type="checkbox" value="Two" name=counter[]>
<input type="checkbox" value="Tre" name=counter[]>
<input type="checkbox" value="For" name=counter[]>
Then, for example, using PHP server-side:
<?php
if ( isset( $_REQUEST['counter'] ) ) {
print_r( $_REQUEST['counter'] );
}
?>
I think you're better off creating the elements in code. add a script tag in replace of your controls and use something like this (create a containing div, I've specified one named container in my code below)
for(int i = 0; i < 4; i ++){
var el = document.createElement('input');
el.setAttribute('name', 'chk' + i.toString());
document.getElementById('container').appendChild(el);
}

Categories

Resources