I have 2 different links with inline js added.
I would like to add both to a single inline onclick.
Here are the two separate one:
<a href="#" onclick=\'$("#id").toggle();\'>
<a href="#" onclick="myvar = '1';">
And this is what I would like to do:
<a href="#" onclick="$("#id").toggle();myvar = '1';">
How could I do this?
I have 2 different links with inline js added.
I would like to add both to a single inline onclick.
Here are the two separate one:
<a href="#" onclick=\'$("#id").toggle();\'>
<a href="#" onclick="myvar = '1';">
And this is what I would like to do:
<a href="#" onclick="$("#id").toggle();myvar = '1';">
How could I do this?
Share Improve this question asked Sep 25, 2012 at 13:23 Satch3000Satch3000 49.4k90 gold badges224 silver badges349 bronze badges 12-
You want this ?
<a href="#" onclick="$('#id').toggle();myvar = '1';">
. Did you see you have problems with quotes ? – Denys Séguret Commented Sep 25, 2012 at 13:24 - 1 What actually are you trying to do? Why do you separate JavaScript code into several inline event handlers? – VisioN Commented Sep 25, 2012 at 13:24
- Just write this: <a href="#" onclick="$('#id').toggle();myvar = '1';"> – Sebastian Breit Commented Sep 25, 2012 at 13:25
- First of all: there's no jQuery in here. And second: don't do this. Separate your HTML and the client code. Bind event handlers not in the HTML. You'll thank me. – user659025 Commented Sep 25, 2012 at 13:26
-
3
I could answer the question by telling you to escape the quotes in
$("#id")
, but that would mean that you'd continue to use inline javascript, which is pretty much always the wrong approach. – zzzzBov Commented Sep 25, 2012 at 13:27
6 Answers
Reset to default 6you can use
$("a").click(function(){
$('#id').toggle(); myvar = '1';
})
Attach your event handlers in javascript (why?), then it bees trivial:
HTML:
<a href="#" id="myAnchor" />
JS:
document.getElementById('myAnchor').onclick = function () {
$("#id").toggle();
myvar = '1';
};
Exactly like you have, but with syntax errors fixed...
<a href="#" onclick="$('#id').toggle(); myvar = '1';">
Incidentally, be ready for a slew of people telling you not to use inline code.
simply use this
$("a").click(function(){
$("#id").toggle(); myvar = '1';
})
... You did it, basically. You just have to unify how you're declaring your strings and you're all set:
<a href="#" onclick="$('#id').toggle();myvar = '1';">
Voila.
Can't you just do what you are doing in javascript?
$(document).ready(function(){
$('#id').toggle(function(){
myVar = 1;
});
});
... or something.