run jQuery function by inline onClick and use function variable/reference - javascript

I am very new to this, but I wrote this and thought it would work first time, but I get an 'ReferenceError: Can't find variable: street' console error.
I get this error if I click on the 'Street' button.
It's quite basic but this is the first time I've made a function to use a var/ref from the onClick attribute.
Please see onClick markup...
Supersport
Street
Cruiser
Scooter
Motocross
Enduro
Kids
then please see my function, which gets the ref error above...
Also please note I am trying to use the onClick var/ref within my function so I can target specific elements relative to the button being clicked.
bikeFilter = function (y) {
$('.bike').fadeOut();
scrollTo(186);
$('.bike[data-group=' + y + ']').fadeIn();
bikeSliderNav();
bikeSlider();
return false;
}
Any expert advice would be really helpful.
Thanks in advance.

You'd probably wanna pass a String as input to your function and not the name of an undeclared and uninstantiated variable.
Try to use the single quotes to refer it as a String constant (you need single quotes since you are already using double quotes to tell your html tag the attribute value):
onclick="bikeFilter('scooter')"
Take a look here to see the difference in data typing in js, and here for a quick start about functions.

You should use them like :
onclick="bikeFilter('motocross')"
Don't forget to put ' around your parameters

Related

Cannot insert HTML value into another

I'm trying to have the value of an HTML element equal the value of another. Sounds simple enough but when I try various options, it doesn't work
Here's what I'm trying to do:
I tried a few things. First, I made a javascript function that when they info button is pressed, it simply sets the value of the newname textbox to the title and then I was going to use javascript to trim off the extension. As you can see on the page, it simply outputs {{modal_header}}. I believe this is because when the function is being called, the value hasn't been set yet and that's why it's outputting this. I couldn't find out where else to call the function in order for it to work.
To get around that issue, I tried using PHP to retrieve the name. The only thing I could find related to the name was which in stuck in the value property of newname, but this output only the last file in the directory, no matter what file you selected.
I tried a bunch of different little things, but without any luck. You guys have any ideas?
Website: http://box.endurehosting.com/
HTML: http://pastebin.com/dZ5rKGUY
try this code
$(function(){
var title = $("#title").html();
title = title.substr(0, title.indexOf('.'));
$("#newname").val(title);
})

jQuery string escape onclick='deleteRow(item"+count+")' how to quote around item and count

I don't even know how to ask this question correctly, I tried to put quotes around a part of my string however it always break.
I am creating html dynamically and I am encountering error when I try to do this:
onclick='deleteRow("item"+count+"")'
I am trying to pass item1 as a string to a deleteRow function however best I could do is pass it like this deleteRow(item1) with no quotes. I am not sure how to escape them so that they would show.
This line of code is generated inside my JavaScript file.
I would recommend to use jQuery event handlers instead of inline one..
But in this case the below should do it
"onclick='deleteRow(\"item"+count + "\")'"

JavaScript JQuery String Var to show in a field

I'm working with JavaScript JQuery, and when i try to show the content of the vars in a field, it doesn't work.
There is my code:
function editEvolution(pos, nature, desc, di) {
$('#diE').val(di);
$('#natureE').val(nature);
$('#descE').val(desc);
$('#BtnAddEditEvo').attr('value', "Update");
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution("+pos+")");
}
Thank's in advance for help.
the value of fields $('#diE'), $('#natureE') and $('#descE') doesn't change if the vars nature, desc, are strings but it works if it is a number
The problem is that you are mixing the worst from both the native JS, inline JS and jQuery worlds. You NEVER EVER put code inside a string, period. If you do it, you are doing it wrong.
So.. how to do it properly?
$('#BtnAddEditEvo').val('Update').on('click', function() {
doEditEvolution(pos);
});
In case you call editEvolution multiple times on the same object, add .off('click') before the .on(...) call to unbind previous handlers.
First do not use attr to set onclick...
I will explain what is wrong
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution("+pos+")");
if pos="foo", it will render as
<div onclick="doEditEvolution(foo);"></div>
See the problem? It is looking for a variable foo. You would need to add quotes.
$('#BtnAddEditEvo').attr('onclick', "doEditEvolution('"+pos+"')");
^ ^
Why does a number work? Because numbers do not need quotes. It makes a valid call. It renders as:
<div onclick="doEditEvolution(3);"></div>
What you need to do is use jQuery the right way and use events.
$('#BtnAddEditEvo').on('click', function() { doEditEvolution(pos); });
and you should set value with .val()

Pass multiple values with onClick in HTML link

Hi Im trying to pass multiple values with the HTML onclick function. Im using Javascript to create the Table
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
But in my Javascript function the userName is undefined and the valuationId is a string with the valuationId and the UserName combined
function ReAssign(valautionId, userName) {
valautionId;
userName;
}
If valuationId and user are JavaScript variables, and the source code is plain static HTML, not generated by any means, you should try:
Re-Assign
If they are generated from PHP, and they contain string values, use the escaped quoting around each variables like this:
<?php
echo 'Re-Assign';
?>
The logic is similar to the updated code in the question, which generates code using JavaScript (maybe using jQuery?): don't forget to apply the escaped quotes to each variable:
var user = element.UserName;
var valuationId = element.ValuationId;
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
The moral of the story is
'someString(\''+'otherString'+','+'yetAnotherString'+'\')'
Will get evaluated as:
someString('otherString,yetAnotherString');
Whereas you would need:
someString('otherString','yetAnotherString');
Solution: Pass multiple arguments with onclick for html generated in JS
For html generated in JS , do as below (we are using single quote as
string wrapper).
Each argument has to wrapped in a single quote else
all of yours argument will be considered as a single argument like
functionName('a,b') , now its a single argument with value a,b.
We have to use string escape character backslash() to close first argument
with single quote, give a separator comma in between and then start next argument with a
single quote. (This is the magic code to use '\',\'')
Example:
$('#ValuationAssignedTable').append('<tr> <td>Re-Assign </td> </tr>');
$Name= "'".$row['Name']."'";
$Val1= "'".$row['Val1']."'";
$Year= "'".$row['Year']."'";
$Month="'".$row['Month']."'";
echo '<button type="button" onclick="fun('.$Id.','.$Val1.','.$Year.','.$Month.','.$Id.');" >submit</button>';
enclose each argument with backticks( ` )
example:
<button onclick="updateById(`id`, `name`)">update</button>
function updateById(id, name) {
alert(id + name );
...
}
Please try this
for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"
That is because you pass string to the function. Just remove quotes and pass real values:
Re-Assign
Guess the ReAssign function should return true or false.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
Re-Assign
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
function ReAssign(valautionId, userName) {
var valautionId
var userName
alert(valautionId);
alert(userName);
}
Re-Assign

Passing value to function from html

I'm trying to pass a value from html to a function but when I do I get an error - reference error: cant find the variable: "var value". The code below I'm removing spaces and replacing them with underscores then trying to pass that to a function called onToDate.
var theFunction2 = theFunction.replace(/ /g,"_");
$('#inserted').append('<div id="'+theFunction2+'"><li onclick="onToDate('+theFunction2+')"><img width="30px" height="25px" src="style/soccer.png"><div id="popupContactClose2">'+counted+'</div></img>'+ rs.rows.item(0)['playing']+'</li>');
onToDate is simply there to alert the value passed to it:
function onToDate(hello){
alert(''+hello+'');
console.log(''+hello+'');
}
This is where I get the error. I don't really get whats happening I've used this before and it worked fine.
Any help would be great,
Thanks
onclick="onToDate('+theFunction2+');
is turning into something like:
onToDate(some_thing);
so in the above case, some_thing is a variable that is undefined, meaning that this is a Reference error.
So,
onclick="onToDate(\"'+theFunction2+'\");
should fix it
First of all #IAbstractDownvoteFactor is right. You should fix onclick definiton.
If this code runs in $(document).ready() block, then your onToDate function is not accesible from that scope. Your click event calls from global scope. You should define it like this;
window.onToDate = function(hello){
alert(hello);
}
And no need for those single quotes...

Categories

Resources