jQuery looping checkboxes - javascript

I have a page that contains many checkboxes. There are a set of checkboxes that have an ID prefixed with pbfam_ and it is only these I am interested in.
When a user clicks on one of these, I need to get a list of the IDs from that subset of only the ones that are checked, and I need it to be a comma delimited string of the IDs.
The HTML looks like this:
<input type="checkbox" id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />
There are about 40 of these checkboxes. What I'm looking for is a string like:
"pdfam_711131, pdfam_711341"
I've tried various things and nothing has worked. I'm quite new to jQuery. This gives me a list of checked ones and returns the checked value in an alert and I was trying to mess around with this but I have got nowhere.
$('input:checkbox[id^="pdfam_"]:checked').each(function(){alert($(this).attr("id")););

A simple way is to use .map() to make an array of the IDs, then use .toArray().join(", ") to get your string.
var s = $('input:checkbox[id^="pdfam_"]:checked')
.map(function(i, el) { return el.id })
.toArray()
.join(", ");
console.log(s);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />

You can get all those are selected followed by Join.The get() method returns a specified element from a Map object.
console.log($('input:checkbox[id^="pdfam_"]:checked').map(function() {
return this.id || null;
}).get().join(','))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" checked id="pdfam_711131" />
<label for="pdfam_711131" class="VIEWBOX">Temporary Staff</label>
<br />
<input type="checkbox" checked id="pdfam_711341" />
<label for="pdfam_711341" class="VIEWBOX">Other Contractors</label>
<br />

Related

How to get the value field of HTML Control in Javascript?

How to get the value field of HTML Control in Javascript?
Instead of picking the Id , I am trying to get the value which is 4875.
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
if ($("input:radio[name='ChangesInTreat']:checked").length > 0) {
var isChecked1 = document.getElementById("ChangesInTreatYes").checked;
alert(isChecked1);
}
jQuery makes it simple -- for nearly all form elements, .val() will return the value of the element.
let toggleEl = $("input[name='ChangesInTreat']")
toggleEl.on("change", function(){
console.log($(this).val() );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
To do the same thing with plain old javascript:
let toggleEl = document.querySelectorAll("input[name='ChangesInTreat']")
// Go over each radio button, and add an event handler
toggleEl.forEach(function(element){
element.addEventListener("change", function(){
console.log(this.value)
})
})
<input data-val="true" data-val-required="Required" id="ChangesInTreatYes" name="ChangesInTreat" type="radio" value="4875" /> Yes
<input id="ChangesInTreatNo" name="ChangesInTreat" type="radio" value="4876" /> No
FYI, you are intermixing jQuery and javascript. Would suggest choosing one type and sticking with it.
Get value of radio using javascript by name:
var isChecked1 = document.querySelector("input[name='ChangesInTreat']:checked").value;
Get value of radio using jQuery by name:
var isChecked1 = $("input[name='ChangesInTreat']:checked").val();

How do you reference the checked value in a radio input control for a javascript function?

I need the output element of an html form to display content that is based off whatever item is checked from a radio button set. When I only need to display which value is checked it works fine, but when I try to use a function to switch the output, the if statement doesn't work - the function always returns 'Farenheit' as though option.value remains 'celcius' (regardless of how often the option buttons are swapped):
<script>
function switchOpt(opt){
if (opt='celcius'){
return 'Farenheit';
}else{
return 'Celcius';
}
}
</script>
<form oninput="swap.value=switchOpt(option.value)">
<input type="radio" name="option" value="celcius" checked /> Celcius <br />
<input type="radio" name="option" value="farenheit" /> Farenheit <br />
<output name="swap"></output>
</form>
The same setup for the if statement works in other functions, so I'm guessing the problem is that there's a datatype mismatch or something in how I'm trying to refer to the values here.
How do you refer to the checked value in a set of radio buttons within a function?
function switchOpt(opt) {
if (opt == 'farenheit') {
return 'Farenheit';
} else {
return 'Celcius';
}
}
<form oninput="swap.value=switchOpt(option.value)">
<input type="radio" name="option" value="celcius" checked /> Celcius <br />
<input type="radio" name="option" value="farenheit" /> Farenheit <br />
<output name="swap"></output>
</form>
Note the change in the if condition...
=== operator checks both value and type whereas == only compares the value. For example, 3 == '3' will return true even though one is a string and the other is a number and to avoid this should use ===. Therefore, I’d say it’s safer to use the former although I did use == here :)
Single = is for assigning. For example var x = document.getElementById(‘box’);
You should use === in your if clause instead of =.
In addition always add labels for your radio buttons and checkboxes.
<script>
function switchOpt(opt){
if (opt==='celcius'){
return 'Farenheit';
}else{
return 'Celcius';
}
}
</script>
<form oninput="swap.value=switchOpt(option.value)">
<input type="radio" name="option" id="celcius" value="celcius" checked /> <label for="celcius">Celcius</label> <br />
<input type="radio" name="option" id="farenheit" value="farenheit" /><label for="farenheit"> Farenheit</label> <br />
<output name="swap"></output>
</form>

How to get html input in JavaScript?

I am using the code below in a html form:
<input type="text" name="cars[]" required>'
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
I would like to get the answers from all the inputs in JavaScript.
How can this be done?
I have the following WRONG code for this:
var element = document.getInput("cars[]");
for (i = 0; i < element.length; i++) {
alert(element[i].value);
}
You have to use document.getElementsByName() like this:
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
alert(element[i].value);
}
<input type="text" name="cars[]" value="a" required>
<input type="text" name="cars[]" value="b" required>
<input type="text" name="cars[]" value="c" required>
These two things in pure JavaScript net approximately the same result. The first is using the HTML form element to find all of the input elements attached to it. However, the syntax for finding the array called "cars[]" is troublesome and in my opinion a tad annoying. If I was going to do something in pure JavaScript I'd probably prefer the second way, using document.querySelectorAll.
window.addEventListener('load', function() {
var form = document.getElementById('thing');
form.elements['cars[]'].forEach(function(el, i) {
console.log("value is ", el.value)
}); //Form.elements[] array has been available since Chrome 7 or so. It should be available for use in just about any browser available.
var items = document.querySelectorAll('[name="cars[]"]');
items.forEach(function(el, i) {
console.log("Item Value is ", el.value)
});
});
<form id="thing">
<input type="text" name="cars[]" value="1" />
<br />
<input type="text" name="cars[]" value="2" />
<br />
<input type="text" name="cars[]" value="3" />
<br />
<input type="text" name="cars[]" value="4" />
<br />
<input type="submit" value="submit" />
</form>
You write
Note the use of "cars[]" for the name.
This allows me to have multiple inputs with the same name.
In HTML, you can have many inputs in the same form with the same name, regardless of that name having a [] suffix or not. This has always been used for, say, checkboxes. Most server-side libraries will then return the values for those inputs as an array.
An example of gathering all values for inputs with a given name could be the following:
document.querySelector("#b").addEventListener("click", () => {
const values = [];
document.querySelectorAll("input[name='color']").forEach(e => values.push(e.value));
console.log(values); // outputs ["foo", "bar", "baz"] if values unchanged
});
input { display: block; margin: 5px; }
<label>Enter your favorite colors
<input type="text" name="color" value="foo"/>
<input type="text" name="color" value="bar"/>
<input type="text" name="color" value="baz"/>
</label>
<label>
Enter your favorite food
<input type="text" name="food" value="flub"/>
</label>
<button id="b">Click me to output favorite colors</button>
You can give same id to all inputs like
<input type="text" id="inputId" name="cars[]" required>'
In Javascript iterate the element to get the value
var element = document.getElementsByName("cars[]");
for(i=0; i<element.length;i++){
console.log(element[i].value);
}

Why does IE8 fail to resolve my JQuery selector for a checked radio option?

This following line works as expected in Firefox but IE returns 'undefined'.
var selectedChoice = $("input[name='my.test[0].SelectedOption']:checked", '#myForm').val();
Here is a standalone sample that you can run...
Note the problem seems to be the use of '.' and '[]' in the name of the radio element. However this is how ASP.NET MVC renders them. Here is an example which works fine in Firefox but fails in IE.
<html>
<head>
<title>Testing radio selection jquery in IE 8</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
</head>
<body>
<form id="myForm">
<input name="selected.Option[0]" id="selected_Option1" type="radio" value="1" checked="checked" />
<label for="selected_Option1">Option 1</label>
<br />
<input name="selected.Option1" id="selected_Option2" type="radio" value="2" checked="checked" />
<label for="selected_Option2">Option 2</label>
<br />
<input name="selectedOption[2]" id="selected_Option3" type="radio" value="3" checked="checked" />
<label for="selected_Option3">Option 3</label>
<br />
<input name="selectedOption3" id="selected_Option4" type="radio" value="4" checked="checked" />
<label for="selected_Option4">Option 4</label>
<br />
<span id="displaySelectedChoice1">No value selected.</span>
<br />
<span id="displaySelectedChoice2">No value selected.</span>
<br />
<span id="displaySelectedChoice3">No value selected.</span>
<br />
<span id="displaySelectedChoice4">No value selected.</span>
</form>
<script language="javascript" type="text/javascript">
var selectedChoice = $("input[name='selected.Option[0]']:checked").val();
$('#displaySelectedChoice1').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selected.Option1']:checked").val();
$('#displaySelectedChoice2').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selectedOption[2]']:checked").val();
$('#displaySelectedChoice3').html('You have selected: ' + selectedChoice);
var selectedChoice = $("input[name='selectedOption3']:checked").val();
$('#displaySelectedChoice4').html('You have selected: ' + selectedChoice);
</script>
</body>
</html>
Notice that the 2nd, 3rd and 4th all work but the 1st returns 'undefined' for IE. Its the only one with both '.' and '[]'.
Thanks
Try to escape the square braces in the selector, I don't think IE likes 'em too much. Also, you forgot to close the attribute selector.
var selectedChoice = $('input[name="my.test[0].SelectedOption"]:checked', '#myForm').val();
Or with escaped square braces and periods:
var selectedChoice = $('input[name="my\\.test\\[0\\]\\.SelectedOption"]:checked', '#myForm').val();
Yes, there are 2 backslashes.
I think this will work:
var selectedChoice =
$('input[name="my.test[0].SelectedOption"]:checked', '#myForm').val();
UPDATE:
Replace your JS with this:
var $radio = $('input[name="my\\.test\\[0\\]\\.SelectedOption"]');
$radio.change(function() {
$("#displaySelectedChoice")
.html("You have selected: " + $radio.filter(":checked").val());
});
See working jsFiddle demo
Your select test is invalid javascript:
var selectedChoice = $('input[name='my.test[0].SelectedOption:checked', '#myForm').val();
^--embeded quote breaks the string
This should work better:
var selectedChoice = $("input[name='my.test[0].SelectedOption']:checked", '#myForm').val();
Note that the :checked portion is not in the name= portion
I think you need to escape those [] inside your selector:
var selectedChoice = $("input[name='my.test\\[0\\].SelectedOption']:checked", '#myForm').val();
http://api.jquery.com/category/selectors/
At the top it has an entire paragraph about escaping.
I find your code pretty complicaded. Try something like this:
<form id="myForm">
<input name="my.test[0].SelectedOption" class="test" type="radio" value="1"/>
<label for="my_test_0__SelectedOption_1">Option 1</label>
<br />
<input name="my.test[0].SelectedOption" class="test" type="radio" value="2"/>
<label for="my_test_0__SelectedOption_1">Option 2</label>
<br />
<input name="my.test[0].SelectedOption" class="test" type="radio" value="3"/>
<label for="my_test_0__SelectedOption_1">Option 3</label>
<br />
<span id="displaySelectedChoice">No value selected.</span>
</form>
<script language="javascript" type="text/javascript">
$(".test").change(
function () {
var value = $(this).val();
$("#displaySelectedChoice").replaceTo("you choose: "+value)
}
)
</script>
Dont know wich version of jquery youre using, but even though I red about the new version of jquery that IE has a problem to "see" what you want with this ":checked".
Anyways avoid using this atribute for radio because, well the only checked radio is the one changed anyways.
My point is make a simpler code, it might help.

how to access checkboxes and their values with getElementsByName

Suppose I have the following section of a form:
<td>
<p>
<input type="checkbox" name="faddon" onchange="iaddon()" value="89.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="29.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="49.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="39.00" />
</p>
</td>
<td>
<p>
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" /><br />
<input type="checkbox" name="faddon" onchange="iaddon()" value="69.00" />
</p>
</td>
Every time the user selects or deselects a checkbox, I need the script to recalculate the variable addon to the total of all values of the boxes which are checked. This is the code I came up with first, but it does not appear to work for me:
function iaddon() {
addon=0;
av=document.getElementsByName("faddon");
for (e=0;e<av.length;e++) {
if (av[e].checked==true) {
addon+=av[e];
}
}
}
The script keeps returning NaN as the value of addon. At first, I wondered if javascript was reading the values as strings and not integers, but adding a (x)*1 around av[e] did not fix this. Then, I read a little more into getElementsByName and read about it possibly not being a typical array, but instead a nodeList.
I'm new to Javascript and can't figure out after hours of googling how to manipulate this nodeList. Any help is appreciated. I'd like to keep the 8 checkboxes in seperate table cells, so using something like childNodes wouldn't exactly work here, as far as I can tell. I also would like to steer clear of any jQuery at this point...I'm still learning and I want to make sure I understand how to do it in plain old javascript first. Thanks!
You need to use the value property and also parse it to a number.
e.g:
function iaddon()
{
addon = 0;
for (e = 0; e < av.length; e++)
{
if (av[e].checked == true)
{
addon += parseInt(av[e].value, 10);
}
}
}
av[e] will return the element not the value of the element there for addon is not a number.
I believe you want to use av[e].value
also note that since you set addon=0 at the start of the function the value of addon will always only be the value of av[e].value during the function call.
function iaddon() {
addon=0;
av=document.getElementsByName("faddon");
for (e=0;e<av.length;e++) {
if (av[e].checked==true) {
addon+=av[e].value;
}
}
}
btw, obtrusive js
<input type="checkbox" name="faddon" onchange="iaddon()" value="89.00"/>
is very depressive to maintain your code, for both js and html code are written together.
Try to write unobtrusive js code like:
In html:
<input id="index1" type="checkbox" name="faddon" value="89.00"/>
In js:
$('index1').click(function() {
// Edit your function
});

Categories

Resources