Good morning, i need to handle this situation starting from this:
<input type='checkbox' NAME='city' id='11' onclick='funct()' > Rome
<input type='checkbox' NAME='city' id='47' onclick='funct()' > London
<input type='checkbox' NAME='city' id='54' onclick='funct()' > Paris
I have several checkbox with same name but different id. I need, each time the user clicks into a checkbox, to trigger the funct() function.
This function should check every checked id/ids and put them together (like 11,47) because after i need to send through ajax into a different page. can somebody help me? Thanks
Ps. I put up this jsfiddle to let you understand: https://jsfiddle.net/hduo2v5m/
CodePudding user response:
don't use onclick
, use onchange
instead, event.target
is checkbox changed
<input type='checkbox' NAME='city' id='11' onchange='funct(event)'> Rome
<input type='checkbox' NAME='city' id='47' onchange='funct(event)'> London
<input type='checkbox' NAME='city' id='54' onchange='funct(event)'> Paris
<script>
let funct = function (event) {
console.log(event.target.id);
let inputs = document.getElementsByTagName("input");
let arrCheck = [];
for (let i = 0;i < inputs.length;i ) {
let input = inputs[i];
if (input.checked) {
arrCheck.push(input.id);
}
}
console.log(arrCheck);
}
</script>
CodePudding user response:
If you want to get the id's of these inputs that are checked, you can use:
var ids = $('input[name="city"]:checked').map(function() {
return this.id
}).get()
Demo
function funct() {
var ids = $('input[name="city"]:checked').map(function() {
return this.id
}).get()
console.log(ids)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='checkbox' NAME='city' id='11' onclick='funct()'> Rome
<input type='checkbox' NAME='city' id='47' onclick='funct()'> London
<input type='checkbox' NAME='city' id='54' onclick='funct()'> Paris
CodePudding user response:
Lets pass an argument to your function : Like below :
function funct(ele){
alert(ele.id);
}
<input type='checkbox' NAME='city' id='11' onclick='funct(this)' > Rome
<input type='checkbox' NAME='city' id='47' onclick='funct(this)' > London
<input type='checkbox' NAME='city' id='54' onclick='funct(this)' > Paris
CodePudding user response:
You should use value instead of ids, anyway:
function funct() {
const cbs = document.getElementsByName("city");
const result = [];
for(let i=0; i<cbs.length; i ) {
if(cbs[i].checked) result.push(cbs[i].id)
}
console.log(result, result.join(","));
}
<input type='checkbox' name='city' id='11' onclick='funct()' > Rome
<input type='checkbox' name='city' id='47' onclick='funct()' > London
<input type='checkbox' name='city' id='54' onclick='funct()' > Paris