Ok so I do this:
<input type="checkbox" class="checkBoxClass" value="0" />
<input type="checkbox" class="checkBoxClass" value="1" />
<input type="checkbox" class="checkBoxClass" value="2" />
Then in javascript/jquery I'm trying to do something like this:
$('#btnHtml').click(function(){
for( var checks=''; $('.checkBoxClass:checked').val() ){
var checks = checks+', ';
}
});
Let's say all of those checkboxes are checked, how can I get var checks to be a string of '0, 1, 2' ?
Still trying to get used to the for() in JS, it might be the completely wrong way of going about it. Not sure how to do this.
Functional programming:
var str = $('.checkBoxClass:checked').map(function() {
return this.value;
}).get().join();
Reference: .map, .get, .join
Related
Im trying to delete duplicates of htmlcollections. Basically they are htmlcollection of input checkboxes with attributes name and value. I want to remove the entire <input> if the name and value are the same.
I couldn't find similar questions in stackoverflow. But what I have so far is to convert the htmlcollections first into array using
var arr = Array.from(htmlCollection);
and then use a Set to remove the duplicates, then convert it back to htmlCollection. This is way too long. Is there another way to do this?
EDIT: Just made a function undDeal to deal with elements that won't have a value AND OR a name
let removeDuplicates=(elem)=>{
let obj={} //for holding data for checking later
//below function for handling elements without a name AND OR value
//(so that <input name="undefined" value="1" /> isn't seen as <input value="1" />)
let undDeal=(val1,val2)=>{
if(val1==undefined){
if(val2==undefined){return Symbol.iterator}
return Symbol.match
}
return val1+val2
}
let elems=[...elem.children]
let check=(el)=>{
let specs=()=>undDeal(el.name,el.value)
if(obj[specs()]){return true}
obj[specs()]=1; return false
}
for(let i=0;i<elems.length;i++){
if(check(elems[i])){elem.removeChild(elems[i])}
}
}
removeDuplicates(document.body)
<body>
<input name="asdf1" value="1" />
<input name="asdf2" value="2" />
<input name="asdf1" value="2" />
<input name="asdf2" value="2" />
<input name="asdf2" value="1" />
</body>
I have the following series of checkboxes coming from the datatables in the form like below:
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
How can I separate that id from list-chk. Do I have to include data-id parameter?
As per my understanding, Try that
$('input[id^="list-chk"]').click(function(){
$(this).attr("id"); //Getting click control ID
$(this).val(); //Getting Value
});
You can use split if you know the ID always has that format.
var ins = document.getElementsByTagName('input');
for (var i = 0; i < ins.length; i++) {
document.write(ins[i].id.split('_')[1]);
}
// jQuery
$('input').each(function() {
$('body').append(this.id.split('_')[1]);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="list-chk_1" type="checkbox" />
<input id="list-chk_2" type="checkbox" />
<input id="list-chk_3" type="checkbox" />
Split will make an array from the given string, splitting it where you tell it to.
"list-chk_1".split('_') // results in ["list-chk", "1"]
Other methods could be using var idnr = this.id.replace('list-chk_', '');
I've dynamically loading check box fields, how can I send those to server based on user selection.
For example I've following doc,
<label>Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label>Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
Suppose if user selected first two values for each of them, then I need to send like
response[0][0]=199; // Id
response[0][1]=['Apple','Mango']; //values
response[1][0]=200
response[1][1]=['Red','Blue'];
I've tried some approaches suggested in existing posts but failed to implement how I want.
You can make some minor changes in the html then use .map()
<label class="set" data-id="199">Set1</label>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<label class="set" data-id="200">Set2</label>
<input type="checkbox" name="set_200[]" value="Red" />
<input type="checkbox" name="set_200[]" value="Blue" />
<input type="checkbox" name="set_200[]" value="Orange" />
then
var array = $('.set').map(function () {
var $this = $(this),
id = $this.data('id'),
array = [id];
array.push($('input[name="set_' + id + '\\[\\]"]').filter(':checked').map(function () {
return this.value;
}).get())
return [array]
}).get()
Demo: Fiddle
Yet another solution:
<lable>Set1</lable>
<input type="checkbox" name="set_199[]" value="Apple" />
<input type="checkbox" name="set_199[]" value="Mango" />
<input type="checkbox" name="set_199[]" value="Grape" />
<input type="button" value="check" class="js-submit">
Js:
$(".js-submit").on("click", function(){
var a = $("input[type='checkbox']:checked");
var values = {};
a.each(function(){
var value = $(this).val();
var name = $(this).attr("name");
if(!values[name]) values[name] = [];
values[name].push(value)
});
console.log(values)
});
Demo
To expand on my comment a little, here's how I'd do this... given that you're sending this as an ajax request, I'd still wrap these elements in a form element, and use that as a starting-point to build the object we'll be sending...
var myForm = document.getElementById('formID').elements,//get all input nodes
data = {},temp;
for (var i=0;i<myForm.length;++i)
{
temp = myForm.item(i).name.replace(/[[]]/g,'');//replace square brackets
if (!data[temp])
data[temp] = [];//create array if key does not exist
if (myForm.item(i).checked)//for checkboxes
data[temp].push(myForm.item(i).value);
}
That's the basic setup. If you want, you can add checks and further tailor this, so you can deal with various types of input fields, but in essence, it'll boil down to this.
You might also want to use Array.prototype.forEach on the myForm.elements NodeList, and use a callback to keep your code nice and clean.
Here's an example of a slightly more usable version of the same code:
btn.addEventListener('click', function()
{
var data = {};
Array.prototype.forEach.call(frm.elements, function(item)
{
var temp;
if (item === btn) return;//don't includ the button element
if (item.type === 'checkbox' && !item.checked ) return;//not checked, ignore
if (item.name.match(/[[]]/))
{
temp = item.name.replace(/[[]]/g, '');
if (!data[temp]) data[temp] = [];//if property does not exist, make an array
data[temp].push(item.value);
return;
}
//normal elements:
data[item.name] = item.value;
});
//ajax request using data variable goes here!
console.log(data);
},false);
And here's the fiddle of it
First of all thanks for all who have given answers to this question. I've derived my own solution for this issue but it is not possible without your help, especially this
var checkBoxArray = {};
$.each($("input[name^='set_'][type='checkbox']:checked"), function(i, item) {
var Id = item.name.replace(/^(set_)|[\[\]]/g, "");
var value = $(item).val();
if(!checkBoxArray[Id])
checkBoxArray[Id] = [];
checkBoxArray[Id].push(value)
});
$.map(checkBoxArray, function(value, index) {
reponse.push([index, value]);
});
Its worked for me, suggest if anything not proper in above code snippet.
So for a class project I have to make this simple calculator, which was very easy to do. However, I'm required to define my event listeners in JavaScript instead of using something like:
onclick="compute()"
But I need the result of my calculator to update whenever I change a value in my field or select any of the radio buttons. How can I do this? The code I have now is not working.
<script>
function compute(){
var functionSelected = document.getElementsByName("function");
var valueOne = Number(document.getElementById("fielda").value);
var valueTwo = Number(document.getElementById("fieldb").value);
var ans = 0;
if(functionSelected[0].checked){
ans = (valueOne+valueTwo);
}
if(functionSelected[1].checked){
ans = (valueOne-valueTwo);
}
if(functionSelected[2].checked){
ans = (valueOne*valueTwo);
}
if(functionSelected[3].checked){
ans = (valueOne/valueTwo);
}
if(ans>=9007199254740992){
document.getElementById("solution").textContent = "ERROR NUMBER TO LARGE TO BE COMPUTED";
}
else{
document.getElementById("solution").textContent = "Equals: " + ans;
}
}
document.getElementById("fielda").addEventListener("change", compute(), false);
document.getElementById("fieldb").addEventListener("change", compute(), false);
document.getElementByName("function").onclick = compute();
</script>
</head>
<body>
<p>
<input type="number" id="fielda"/><br />
<input type="number" id="fieldb"/><br />
<label><input name="function" type="radio" value="add"/> Add</label><br />
<label><input name="function" type="radio" value="subtract"/> Subtract</label><br />
<label><input name="function" type="radio" value="multiply"/> Multiply</label><br />
<label><input name="function" type="radio" value="divide"/> Divide</label><br />
</p>
<p>
<output id="solution">Solution Will Appear Here</output>
</p>
</body>
You can use
<select ... onchange="javascript:compute();">
There are a lot of events that you can use in response to different events depending on the control.
They are named onmouseover, onclick, onchange, etc. and you can assign a javascript function to each one if you want.
Another alternative is to use you following syntax:
document.getElementById("id_of_select_control").onchange = function() {
// your code here
}
Or if you use jQuery in your project, something like this:
$("#id_of_select_control").change(function() {
// your code here
});
How can we access the value of a radio button using the DOM?
For eg. we have the radio button as :
<input name="sex" type="radio" value="male">
<input name="sex" type="radio" value="female">
They are inside a form with name form1. When I try
document.getElementByName("sex").value
it returns 'male' always irrespective of the checked value.
Just to "generify" Canavar's very helpful function:
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
... which would now be referenced thusly:
getRadioValue('sex');
Strange that something like this isn't already a part of prototype.js.
Surprised no-one has suggested actually using the Selector API:
document.querySelector('input[name=sex]:checked').value
Browser support is good
If you need the selected one, most frameworks support functionality like this:
//jQuery
$("input[name='sex']:checked").val()
You can get your selected radio's value by this method :
<script>
function getRadioValue()
{
for (var i = 0; i < document.getElementsByName('sex').length; i++)
{
if (document.getElementsByName('sex')[i].checked)
{
return document.getElementsByName('sex')[i].value;
}
}
}
</script>
There are a couple of ways.
1. Put an id on each input
<input name="sex" id="sex_male" type="radio" value="male">
<input name="sex" id="sex_female" type="radio" value="female">
Then you can use document.getElementById("sex_male")
2. Use something like PrototypeJS (jQuery works too)
Then you can do something like this:
//This loops over all input elements that have a name of "sex"
$$('input[name="sex"]').each( function(elem) {
//Do something
});
Or even this to get at just the "male" radio button:
$$('input[name="sex"][value="male"]').each(function(elem) {
//Do something
});
An easy way to get started with Prototype is include it from Google by adding this between the <head></head> tags of your page:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/prototype/1.6.0.3/prototype.js"></script>
If you want the selected one, but don't have a framework handy, you can iterate over the element array looking for whichever one is checked:
for (var i = 0; i < document.form1.sex.length; i++) {
if (document.form1.sex[i].checked) alert(document.form1.sex[i].value);
}
var list = document.getElementsByName('sex');
for(var i=0;i<list.length;i++){
if(list[i].type=='radio' && list[i].checked){
alert(list[i].value);
break;
}
}
If you use document.form1.sex, you are returned an array.
document.form1.sex[0] = first radio button
document.form1.sex[1] = second radio button
To check which is checked you need to loop:
whoChecked(document.form1.sex)
function whoChecked(fieldName) {
for(var x=0;x<fieldName.length;x++) {
if(fieldName[x].checked) {
return fieldname[x].value
}
}
document.getElementByName("sex").value
You mean getElementsByName('sex')[0].value? (There's no getElementByName.)
That will of course always pick the first input element with that name — the one whose value is indeed male. You then check to see if it's selected by using the ‘.checked’ property.
For this simple case you can get away with:
var sex= document.getElementsByName("sex")[0].checked? 'male' : 'female';
For the general case you have to loop over each radio input to see which is checked. It would probably be better to get the form object first (putting an id on the form and using document.getElementById is generally better than using the ‘name’-based document.forms collection), and then access form.elements.sex to get the list, in case there are any other elements on the page that have name="sex" attributes (potentially other things than form fields).
function getEleByName(){
if(true==document.getElementsByName('gender')[0].checked){
alert('selected gender is: male');
}
else{
alert('selected gender is: female');
}
}
Loops can achieve the task, as others have shown but it could be simpler than using a loop, which will help performance if desired. Also, it can be portable/modular so it can be used for different radio groups.
Simple Example
function getValue(x) {
alert(x.value);
}
<input name="sex" type="radio" value="male" onChange="getValue(this)" />
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
A more complex example:
function getValue(x){
alert(x.value);
}
<fieldset>
<legend>Sex</legend>
<label>Male:
<input name="sex" type="radio" value="male" onChange="getValue(this)"/>
</label>
<label>Female:
<input name="sex" type="radio" value="female" onChange="getValue(this)" />
</label>
</fieldset>
<fieldset>
<legend>Age Group</legend>
<label>0-13:
<input name="ageGroup" type="radio" value="0-13" onChange="getValue(this)" />
</label>
<label>13-18:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>18-30:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
<label>30+:
<input name="ageGroup" type="radio" value="13-18" onChange="getValue(this)" />
</label>
</fieldset>
document.all.sex[0].checked
document.all.set[1].checked