Get id of an element through a function - javascript

I have a function that is called in an onclick event in a checkbox field.
<input type='checkbox' checked='' onclick='return changeEnable();' id='someid'>
and the function
function changeEnable()
{
var val = $(this).attr('id');
alert(val);
}
I have that but it returns undefined. Is my syntax wrong or did I miss something?
Those checkboxes are dynamically created and have different id's, that's why I want to get the id for some task.

Note that this in your changeEnable function will be the window. You need to pass the reference to the element as a parameter to the function:
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>
function changeEnable(el) {
var val = el.id
alert(val);
}
Or, as an improvement, use Javascript to attach your events for a better separation of concerns:
<input type="checkbox" id="someid">
$(function() {
$('#someid').change(function() {
var val = this.id
alert(val);
}
});
Note that the above uses the change event of the checkbox, which is better for accessibility reasons.

i think this code will help u a lot
<input type='checkbox' checked='' onclick='return changeEnable(this);' id='someid'>`
function changeEnable(thisobj)
{
var val = thisobj.id;
alert(val);
}

Also you should be aware of .call method which throws input context to function.
<input type='checkbox' checked='' onclick='changeEnable.call(this);' id='someid'>
function changeEnable()
{
var val = this.id;
alert(val);
}

use in this way:
<input type='checkbox' checked='' onclick='changeEnable(this);' id='someid'>
function changeEnable(el)
{
var val = el.id;
alert(val);
}

Related

jQuery Get data-attribute of all checkbox into a string

I have a list of checkboxes that looks like this:
<input type="checkbox" class="pcb" value="1" data-id="99">
<input type="checkbox" class="pcb" value="2" data-id="98">
<input type="checkbox" class="pcb" value="3" data-id="97">
And originally I only needed the value inside the value attribute of the checked checkbox. I use this javascript/jquery code to do that:
var receiptNos = $("#result input:checkbox:checked").map(function () {
return $(this).val();
}).get();
Using this code gives me: receiptNos = '1,2,3'
Now I need to have another string variable that will hold the content of data-id of all checked checkboxes: receiptNos2 = '99,98,97'
I tried using:
var receiptNos2 = $("#result input:checkbox:checked").attr('data-id').map(function () {
return $(this).val();
}).get();
but it doesn't work. Any ideas?
Instead return $(this).val(); you can use return $(this).data('id');
var receiptNos2 = $("#result input:checkbox:checked").map(function () {
return $(this).data('id')
}).get();

Javascript when checkbox is checked, add checkbox ID to an array

I am defining an array of checked checkboxes:
<script>
var all_checked = new Array();
function add_checked(checked_checkbox_id)
{
all_checked.push(checked_checkbox_id);
}
<html>
<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(?????);" />
</html>
So my question is how to pass the checked checkbox ID to the function to append to the global
all_checked
variable
Pass this in your function and then use it to get the id property:
HTML
<input type="checkbox" name="a" id="1" value="1" onclick="add_checked(this);" />
JavaScript
var all_checked = new Array();
function add_checked(el) {
all_checked.push(el.id);
}
Remember, this will push the id to the array no matter what, whether the box is checked or unchecked, even if the id already exists in the array.
JSFiddle
Use this keyword by passing to yout function.
onclick="add_checked(this)";
Here you can the id as
this.id
then in
function add_checked(checked_checkbox) {
all_checked.push(checked_checkbox.id);
}
FYI: script tag should be within html tag
HTML:
<button onclick="send_query(document.getElementsByTagName('input'))">
function send_query(check) {
var values = [];
for (i = 0; i < check.length; i++) {
if (check[i].checked == true) {
values.push(check[i].value);
}
}
console.log(values.join());
}

I can't use val()?

I'm having a problem with getting the val of an input element I have.
You see, I don't know if my code is wrong, but my Visual Studio (legal) doesn't even try to help me complete what I want to type. All it gives me is Value() and ValueOf().
The part of the code I'm using:
JS:
$(document).ready(start);
{
$("#b1").click(toev);
}
function toev() {
var value = $("#b1").val();
$("#output").append(value);
};
HTML:
<input type="text" id="output"/>
<td><input type="button" id="b1" value="1" /></td>
Demo http://jsfiddle.net/yS8tw/
Few things to note:
Use of document.ready
Use of Val
Also I like this appendVal function: http://jsfiddle.net/5R7eZ/ - Is it possible to do ".value +=" in JQuery?
Rest should fit the needs :)
code
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
alert(value);
$("#output").val(value);
}
With AppendVal
$(document).ready(function(){
$("#b1").click(toev);
});
function toev() {
var value = $("#b1").val();
$("#output").appendVal(value);
}
$.fn.appendVal = function (newPart) {
return this.each(function(){ this.value += newPart; });
};
You can't append content to an <input> element because it cannot have content. Perhaps you meant
$('#output').val(value);
to set its value.

I'm trying to assign a variable to check-boxes and adding that variable to an output variable when it's checked

I'm very new to Javascript and would appreciate ANY help! I'm also using a jQuery library if that changes anything.
What I need is that if the first checkbox was ticked the output should be 100kcal, while if both were ticked then it should add up to 300kcal. My problem is that when I untick it adds the variables AGAIN.
HTML:
<input type=checkbox onchange="myFunction(100)" value="scrambledEggs">Scrambled Eggs</input>
<input type=checkbox onchange="myFunction(200)" value="bacon">Bacon</input>
<p id="output">0kcal</p>
JS:
var result = 0;
function myFunction(x) {
if (this.checked) {
result -= x;
document.getElementById("output").innerHTML = result + "kcal";
}
else {
result += x;
document.getElementById("output").innerHTML = result + "kcal";
}
}
Firstly if you're using jQuery, you should use it to attach the event handlers instead of onchange attributes. Secondly, the input tag is self closing - your current HTML is invalid. Finally, you can use a data attribute to store the kcal value for the option:
<label><input type="checkbox" class="food-option" data-kcals="100" value="scrambledEggs" />Scrambled Eggs</label>
<label><input type="checkbox" class="food-option" data-kcals="200" value="bacon" />Bacon</label>
<p id="output"><span>0</span>kcal</p>
Then you can use jQuery to attach the event and total up all the checked values and display them:
$('.food-option').change(function() {
var totalKcals = 0;
$('.food-option:checked').each(function() {
totalKcals += parseInt($(this).data('kcals'), 10);
});
$('#output span').text(totalKcals);
});
Example fiddle
In your case you can use this code:
HTML
<input type="checkbox" value="scrambledEggs" data-kcal="100">scrambledEggs</input>
<input type="checkbox" value="bacon" data-kcal="200">bacon</input>
<p id="output"> 0 kcal</p>
it have data-kcal tag which is container for your kcal value.
JS
var result = 0;
$('input[type="checkbox"]').on("change", function() {
if($(this).attr('checked'))
{
result += parseInt($(this).attr("data-kcal"));
}else{
result -= ($(this).attr("data-kcal"));
}
$("#output").text(result + " kcal");
});
Also you can check how it works on this jsFiddle.
Your HTML should be like below
<input type='checkbox' value="100">Scrambled Eggs </input>
<input type='checkbox' value="200"> Bacon </input>
<p id="output">0kcal </p>
Then you better use JQuery, less code written, more readability. The code below will achieve your needs.
$('input[type=checkbox]').change(function (e) { //This will trigger every check/uncheck event for any input of type CheckBox.
var res = 0;
$('input[type=checkbox]:checked').each(function() { //Loop through every checked checkbox.
res += parseInt($(this).val()); //Sum it's value.
});
$('#output').text(res); //Add the final result to your span.
});
Demo
Pass the element that is clicked into the function...
HTML
<input type=checkbox onchange="myFunction(this, 200)" value="bacon">Bacon</input>
JAVASCRIPT
function myFunction(element, value) {
console.log(element.checked);
}
Check this JSFiddle for a demo.
Better way of doing it is like this...
HTML
<div id="checkboxes">
<input type=checkbox value="bacon">Bacon</input>
<input type=checkbox value="Other">Other</input>
</div>
<p id="output">0kcal</p>
JAVASCRIPT
var checkboxes = document.getElementById("checkboxes");
checkboxes.onchange = function (e) {
alert("Target: " + e.target.value + " Checked: " + e.target.checked);
};
See this fiddle for a demo.

Getting DOM element value using pure JavaScript

Is there any difference between these solutions?
Solution 1:
function doSomething(id, value) {
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id, this.value)" />
...and Solution 2:
function doSomething(id) {
var value = document.getElementById(id).value;
console.log(value);
//...
}
<input id="theId" value="test" onclick="doSomething(this.id)" />
Update: The question was edited. Both of the solutions are now equivalent.
Original answer
Yes, most notably! I don't think the second one will work (and if it does, not very portably). The first one should be OK.
// HTML:
<input id="theId" value="test" onclick="doSomething(this)" />
// JavaScript:
function(elem){
var value = elem.value;
var id = elem.id;
...
}
This should also work.
The second function should have:
var value = document.getElementById(id).value;
Then they are basically the same function.
In the second version, you're passing the String returned from this.id. Not the element itself.
So id.value won't give you what you want.
You would need to pass the element with this.
doSomething(this)
then:
function(el){
var value = el.value;
...
}
Note: In some browsers, the second one would work if you did:
window[id].value
because element IDs are a global property, but this is not safe.
It makes the most sense to just pass the element with this instead of fetching it again with its ID.
Pass the object:
doSomething(this)
You can get all data from object:
function(obj){
var value = obj.value;
var id = obj.id;
}
Or pass the id only:
doSomething(this.id)
Get the object and after that value:
function(id){
var value = document.getElementById(id).value;
}
There is no difference if we look on effect - value will be the same. However there is something more...
Solution 3:
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />
if DOM element has id then you can use it in js directly
This should also work.
function doSomething() {
yourElement = document.getElementById("yourID);
yourValue = yourElement.value; console.log(yourValue);
console.log(yourValue);
}
<div id="yourID" value="1" onclick="doSomething()">
</div>
function doSomething() {
console.log( theId.value );
}
<input id="theId" value="test" onclick="doSomething()" />

Categories

Resources