how to render JavaScript using pug/jade - javascript

For example, I pass a user variable to this pug file, and I want to run some js code after dom has loaded.
script.
document.addEventListener("DOMContentLoaded", function(event) {
console.log(#{user.name});//log the user's name
});
Is it possible to do so?

First, you're trying to use a string interpolation #{user.name} outside of a string. Use !{user.name} instead for unescaped code interpolation. If you need this to be in a string you'll need to surround the variable in quotes as well.
console.log('!{user.name}');

Related

Dynamic Unicode Generation into the DOM

I have a function linking to a method for a JavaScript library I'm working on. Basically taking romanized Korean and converting it to specific Unicode sequences and re-inserting it into the DOM. The resulting strings that it generates are correct, but the re-insertion back into the DOM seems off...
For example: If I have the following in my DOM:
<ko>hangug-eo</ko>
The function is meant to convert it accordingly, replacing hangug-eo with 한국어 to show on the browser:
한국어 within the <ko> tags...
The function that does the string setting within the DOM is as follows:
function (){
var z=document.getElementsByTagName('ko');
for(x=z.length;x--;){
z[x].childNodes[0].data=kimchi.go(z[x].childNodes[0].data);
}
}
However, it seems that all this seems to be doing is just placing the &# Unicode entities straight into the DOM without it converting to their respective character equivalents... So all I'm seeing is 한국어
Can anyone please point out what I may be doing wrong?
kimchi.go() is the function that ultimately provides the Unicoded string...
You can always just set the text directly using textContent without having to use HTML entities:
z[x].textContent = '한국어';
But if you need to use HTML entities, just use innerHTML instead
z[x].innerHTML = kimchi.go(z[x].childNodes[0].data);
You can see the latter in the example below.
https://jsfiddle.net/nmL3to8w/1/

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 + "\")'"

putting model variables inside js code

i have issues alternating js and razor syntax.
i am trying to pass the value of a model variable to a javascript function, let's say something like this
<script>
//this is my javascript function setTitle that simply changes the title
of a modal window, and i want to pass to it the title from the model
...
setTitle(#Model.titleName);
...
</script>
so when i do this it doesn't work, and the script seems to break.
If it's a string you have to surround it with quotes.
setTitle('#Model.titleName');
If it's an integer you obviously don't need that.
In situations like these it's helpful to Right Click -> View Source, and take a look at the javascript it generated, and also report any errors the console window showed when asking a question.
You need to encase the Razor code in quotes so the result is a JavaScript string
setTitle("#Model.titleName");

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

Pass variable to a javascript function in a c# code

I need to pass a variable to a javascript function,but I got a little trouble.
In the .cs file,I write like this:
string id = "someid";
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction("+id+")\">"));
I need to use the value of this id,but in the console.log(id),it just shows "object",not the "someid",what's the problem?
Look at the generated HTML:
<input type="button" onClick="myFunction(someid)">
You are generating a variable name when you want a string literal.
Add some quote marks.
Whenever you have a problem that manifests in the browser: Look at the code the browser is dealing with first. You should always start by determining if the JS you want is not working or if the server side code is not generating the JS you want.
just add '' around id as i did below will resolve your issue
this.Controls.Add(new LiteralControl("<input type=\"button\" onClick=\"myFunction('"+id+"')\">"));
Use the single quotes around id:
'"+id+"' (notice the single quotes then double quotes)
The problem is that it is looking for a saved variable on the page named someid, which is why you are getting the object in the console. Pranay Rana has a good solution which is to make sure the string someid is surrounded by single quotes.

Categories

Resources