Passing element ID to function - javascript

I have this function:
function op_up(){
this.style.color=#FF0000;
}
And I have this HTML element:
<span id="trigger" onClick="op_up(#element_1)">Click to change #element_1<span>
<span id="trigger" onClick="op_up(#element_2)">Click to change #element_2<span>
I would like the function to affect the id of the element in the onClick event.
Any help would be much appreciated. Thanks :)

Your function call is not valid, but you can pass a string to the function:
op_up('#element_1')
Then you can use document.querySelector to get a reference to the element:
function op_up(selector){
document.querySelector(selector).style.color='#FF0000';
}
Or as I already said in the comments, if you pass the ID as
op_up('element_1')
use document.getElementById:
function op_up(id){
document.getElementById(id).style.color='#FF0000';
}

Related

How to find and add the function to id?

I want to add a function to the attribute onChange of the element with id="custom-taxonomy". I don't want to edit the file.
I want to have a javascript solution.
My idea is to find the element by the id and then add the function.
How can i achiev this idea?
The code:
<div id ="custom-taxonomy">PRODUCT PRICES</div>
Expected result:
<div id ="custom-taxonomy" name="custom-product" onchange="return chothuephuongxa();>PRODUCT PRICES</div>
you can do that using setAttribute() and document.getElementById
let elm = document.getElementById('custom-taxonomy')
elm.setAttribute('name',"custom-product")
elm.setAttribute("onclick","return chothuephuongxa();")
console.log(elm.outerHTML)
<div id ="custom-taxonomy">PRODUCT PRICES</div>
Note:
You can't use name attribute of <div> but using elm.name = ... because name property in not available on <div> elements.
Similarly elm.onclick = "return chothuephuongxa();" is not correct because this will set event to string instead of function
You can use setAttribute to add attributes to elements:
document.getElementById('custom-taxonomy').setAttribute('name', 'custom-product');
the same can be done for your event.

Javascript passing parameter syntax issue

I am making a div clickable using Onlick Event of tag. Then also passing a parameter when a div is clicked.
I am facing issue while passing a parameter from one JS method to another.
</div>
callmethod1(parameter){
//definition goes on here
}
While calling the method with parameter, it shows
Documents.aspx:1 Uncaught SyntaxError: missing ) after argument list
Any help will be appreciated!
You have more than one issue to fix:
Anchor <a> tags cannot have block elements like <div>
<a> it is not closed; the first part of it, and the attribute is onclick not onlcick
<a href="#" onclick="callmethod1(a.b.c.1.0.1);">
_________^
Function parameters (arguments) cannot be like a.b.c.1.0.1. I would assume you are trying to pass a string "a.b.c.1.0.1"
Functions definition must be prefixed with function or var fnName = function()
function callmethod1(parameter){
// function
}
Fixed snippet
function callmethod1(parameter){
console.log(parameter);
}
<a href="#" onclick="callmethod1('a.b.c.1.0.1');">Click<a>
<div id="test"></div>
If your parameter is a string, you should embrace them with single quotes:
</div>

jQuery: $(this).attr('id') not find id of element - undefined

I'm trying to get id and just simply alert it onclick although is does just "undefined"...
Can you help me out?
important Code:
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='1' onclick="alertme()" />
jQuery:
function alertme() {
alert($(this).attr('id'));
}
Can you see the problem? I can't...
My bad:
I'm sorry, I wanted to simplify the code and I did not realize that I used "alert()" as name for customized function.
First problem to fix is the function name, which I suspect is different in your actual code because otherwise you wouldn't have gotten as far as you have.
You've used an old-school "onclick" attribute to associate the function with the element. Nothing assures that this will be bound to the element as you expect. You could either change the element:
Better would be to use jQuery to bind the handler:
$("#1").on("click", function() {
alert(this.id);
});
The problem is, as others said - the context of the this keyword.
this refers to the DOM element (as you thought it does) in the CALL ITSELF, but once you called alertme() it is not defined in its scope.
To see it you can look at this JS:
function alertme(){
alert($(this).attr('id'));
console.log(this);
}
and this HTML markup:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="console.log(this); alertme()" />
And you will see that you get in the console first the element, then in the alert 'undefined' and then in the console the window.
To fix it you can either simply specify the meaning of this in the call, using javaScript's Function.prototype.call() function:
Change only in the HTML the markup to
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme.call(this)" />
and it will work with the your alertme().
OR you can just pass this into alertme like so:
function alertme(elem){
alert($(elem).attr('id'));
}
HTML:
<img src="/pictures/picture.jpg" class="r-gal-photo" id='abc' onclick="alertme(this)" />
Sources:
Nice article to understand 'this' in jQuery
this in JS binded by on markup

How to select element inside button using jQuery

What I'm trying to do is, to change i's class (which located inside button) on click
<button><i class="fa fa-square-o"></i></button>
Using js code like below (inside on click function):
...
$(this).child("i.fa").removeClass("fa-square-o");
...
getting child is not a function error
What am I doing wrong?
Yes, really there is no child() method in jQuery.
You may use find() or children() for that.
$(this).children("i.fa").removeClass("fa-square-o");
You could use find() instead.
$('button').click(function() {
$(this).find("i.fa").removeClass("fa-square-o");
});
Fiddle
child is not a function.
try this function:
$(this).children("i.fa").removeClass("fa-square-o");
jQuery accepts a second argument as context:
$('button').click(function() {
$('i.fa', this).removeClass('fa-square-o');
});
You are looking for jQuery .children() function. If you are trying to call that function from onclick attribute, you have to remember to pass reference to object by using "this" word.
<button onclick="removeClass(this)"><i class="fa fa-square-o">test</i></button>
removeClass = function(obj){
$(obj).children("i.fa").removeClass("fa-square-o");
}
Working fiddle:
http://jsfiddle.net/4wvgvzL9/

How can a function find a parent element of the anchor which originally called the function?

Ok, the question alone is making my head spin.
I have an anchor tag that is calling a function:
Add a Guest
Just for reference, this is the function that's being called:
function addPerson() {
//current keeps track of how many rows we have.
current++;
console.log($(this).parent('form').attr('id'));
var strToAdd = '<div class="row">\
<div class="column grid_2">\
<label for="two-guests-name'+current+'">Guest '+current+':</label>\
</div>\
<div class="column grid_5">\
<input name="two-guests-name'+current+'" type="text" id="two-guests-name'+current+'" value="Name" onfocus="RemoveFormatString(this, \'Name\')" /> \
<input name="two-guests-age'+current+'" type="text" class="guestage digits" id="two-guests-age'+current+'" value="Age" size="4" maxlength="3" onfocus="RemoveFormatString(this, \'Age\')" />\
</div>\
</div>'
$('#numberguests').append(strToAdd)
};
I'd like to allow this function to work on multiple forms on a single page. So my thinking was to travel back in the tree to the parent form element, get its id and use that (somehow) to allow the function to work on multiple forms in the page.
You can see I tried using a quick console.log to test my idea, but it kept coming back "Undefined". I also tried running the console.log in the anchor tag itself, but it also was "Undefined".
I tested .parents() and it works perfectly in the anchor tag, but not in the function iteslf.
Any suggestions?
You should pass $(this) into add parents and then you'll have the proper scope to work with in your function. So:
Add a Guest
and then in the function use:
function addPerson(anchorElement) {
var form = anchorElement.parents("form");
//etc.
}
Don't use the onclick attribute use jQuery event binding. As you didn't provide any info about the markup you need to fill in the selector yourself
//this binds the same function to all a tags specified by the selector
$("form somemoreselectorgotgettheright a").bind("click", function() {
console.log($(this).parent("form").attr("id"));
....
});
The this context is different. Change the onclick to this:
addPerson.call(this);
That will make the this in the function match up with the this in the anchor tag.
Or better yet, don't use an onclick attribute at all, but use a jQuery event handler attachment, like this:
$(document).ready(function() {
$('#addPerson').click(function(ev) {
ev.preventDefault();
// Do something with $(this), which is the anchor tag
});
});
And your anchor tag would not have any click handler on it:
Add a Guest
Use parents() with a selector (this will search upward through all parents until the match i found). e.g.
$(this).parents('form').[...]
Pass in the id as a parameter. Eg
Add a Guest
then...
function addPerson(parent_id) {
// do something with parent_id

Categories

Resources