I have several js for "loops" and I need the cleanest syntax to specity an id value using the "for loop counter". Here is an example that works, but it looks kludgy and it doesn't thrill me much to have to use such janky code. See that:
"USCF_ID' +i +'"' +'
// USCF ID #
items += '<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID' +i +'"' +' name = "USCF_ID" /> </td>';
Can you make a suggestion about expressing ID = USCF_ID1 programically in plain js? No jQuery if you can avoid it, please.
It was kind of difficult for me to follow along with your question, but what I got from your explanation is that you're just trying to find a cleaner way to concatenate your data. I would recommend that you use string templates here. Here's an example:
items += `<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID${i}" name = "USCF_ID" /> </td>`;
Creating a string with the `...` syntax creates a string template literal that allows you to insert JavaScript code between the ${ } curly brackets and concatenate the result.
You can use a string template where "USCF_ID' +i +'"' +' can be replaced by ${id}. String templates are defined using a backtick character - `:
items += `
<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID${id}" name = "USCF_ID" />
</td>`;
Additionally you can extract the template into a function:
function getItem(id) {
return `
<td style="display:none;">
<input onblur="showID();" name = "ID" id = "USCF_ID${id}" name = "USCF_ID" />
</td>`;
}
Then you can generate your list as:
items += getItem(id);
JS itself doesn't have built-in string formatting like other languages (with an exception later). You can simulate it yourself in a simple case like this with the replace method:
template = '<td style="display:none;"><input onblur="showID();" name="ID" id="USCF_ID$i" name="USCF_ID"/></td>';
...
items += template.replace("$i", i);
ES6 has template strings that can do this, but may not be available depending on the browser you are trying to support (note the backticks instead of single quotes):
items += `<td style="display:none;"><input onblur="showID();" name="ID" id="USCF_ID${i}" name="USCF_ID"/></td>`;
I want to display a colorpicker on an MVC5 application. This feature works if manually typed out and adapted for each page that uses it. Obviously, this is excessively duplicated code so I created a Utils method to generate the data. Here is the definition for that method:
public static string GetColorsList()
{
string colorsList = "<option style=\"color:gray\" value=\"null\">select color</option>" +
"<option style=\"color:azure\" value=\"Azure\">Azure</option>" +
"<option style=\"color:blue\" value=\"Blue\">Blue</option>" +
"<option style=\"color:cyan\" value=\"Cyan\">Cyan</option>" +
"<option style=\"color:green\" value=\"Green\">Green</option>" +
"<option style=\"color:magenta\" value=\"Magenta\">Magenta</option>" +
"<option style=\"color:orange\" value=\"Orange\">Orange</option>" +
"<option style=\"color:red\" value=\"Red\">Red</option>" +
"<option style=\"color:violet\" value=\"Violet\">Violet</option>" +
"<option style=\"color:yellow\" value=\"Yellow\">Yellow</option>";
return colorsList;
}
The reason I return a string instead of an IEnumerable is that a JS method adds new data (i.e. create a new row in the table) to the page using:
$(#tablename tbody).append(newcontent);
where new content is a string of the HTML to insert. Ideally I could just create an Html.DropDownList to display the picker contents but this does not return a string-friendly result.
What I want to accomplish: take colorsList, put in in ViewData["x"], turn ViewData["x"] into a string, and concat that string with other content that belongs in newcontent.
ViewData["x"].ToString() yields the following result:
<option style="color:gray" value="null">select
color</option><option style="color:azure" value="
Azure">Azure</option><option style=
"color:blue"
value="Blue">Blue</option><option style="
color:cyan" value="Cyan">Cyan</option><
option style="color:green" value="Green">
Green</option><option style="color:magenta" value=
"Magenta">Magenta</option><option style=
"color:orange" value="Orange">Orange</option
><option style="color:red" value="Red">
Red</option><option style="color:violet" value=
"Violet">Violet</option><option style=
"color:yellow" value="Yellow">Yellow</option>);
The workaround here is to run:
colorpickerContent = colorpickerContent.replace("$lt;", "<");
colorpickerContent = colorpickerContent.replace("$gt;", ">");
colorpickerContent = colorpickerContent.replace(""", "\"");
So that all the proper characters exist. When running, the program throws a syntax error because the output does not start with the quotation marks needed to consider it a string. Any suggestions on how I can make ViewData["x"] a workable string? I attempted JSON.stringify() but found similar results.
You're looking for the HtmlString that one won't be escaped.
I used a code that I found in the web and then changed a little thing:
<script type="text/javascript">
var foodList = [];
function addToFood (addFood) {
alert(addFood);
//foodList.push(addFood);
//for (i = 0; i < foodList.length; i++) {
// var newFood = "<a href='#' onClick='removeRecord(" + i + ");'>X</a> " + foodList[i] + " <br>";
//};
//document.getElementById('foods').innerHTML += newFood;
}
</script>
At this moment I only want to alert the parameter on addToFood. The function should be called:
echo "<a href='javascript:addToFood(". $zeile1['TITLE'] .");' class='band-head'>Add</a>";
this line shows how I add an <a> with the javascript in the href. The php render the right line but the addToFood is never called.
Have a look at the online Demo: http://anthraxx.sytes.net/ maybe it can help you more then me.
The error I get via Google Chrome: Uncaught SyntaxError: Unexpected identifier But just can't figure that unexpected identifier out.
Thanks
You need to wrap the $zeile1['TITLE'] inside a string, as such:
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</a>";
You can see that I added escaped quotes \" after the opening parenthesis, and before the ending one, in the JS-call.
Otherwise it will try to pass an variable to the function, instead of a string.
Why escaped? That is because you are echo:ing it with PHP. If I didn't escape the quote, the PHP would interpret it as I was ending the string, which is not what we want. I want to put the quotes in there as inline-code.
Just scope your vaiable between ' ' or " " ,When you don't scope String's ,javascript read it like Var.
You need to escape the $zeile1['TITLE'], thats true and you can do that by using following line -
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</a>";
This is working.
try this
echo 'Add';
Replace :
echo "<a href='javascript:addToFood(". $zeile1['TITLE'] .");' class='band-head'>Add</a>";
With:
echo "<a href='javascript:addToFood(\"". $zeile1['TITLE'] ."\");' class='band-head'>Add</a>";
I am a beginner to javascript ! I am trying to call a function from another function inside the same script tags. When I do this without sending arguments it works fine but when i do that with arguments that another function is not called..
Here is what I am doing
function measurement_convert()
{
var mc = "Measurement Conversion";
txt = "<h2>" + mc + "</h2> <br><br>";
txt +=
"<form action='' method='post'>" +
"Select Type <select name='conversion_type' onchange='loadXML('abcd')'> "+
"<option value='area'>Area</option>"+
"<option value='length'>Length</option>"+
"<option value='volume'>Volume</option>"+
"<option value='weight'>Weight</option>"+
"</select> <br><br>"
document.getElementById("content_main_top").innerHTML=txt;
}
So, I am calling the function from onchange of this form.
And here's the another function
function loadXML(var1)
{
document.getElementById("content_main_top").innerHTML=null;
document.getElementById("content_main_bottom").innerHTML=null;
}
Can anyone help me ?
Your problem is that you are trying to nest the same type of quote:
onchange='loadXML('abcd')'
This actually gets interpreted as:
onchange='loadXML('
Instead, try (note the escaped double-quotes, since this code is inside a PHP string):
Select Type <select name=\"conversion_type\" onchange=\"loadXML('abcd')\">
Your single quotes are clashing in the onchange value, as you use the same for closing the value in.
You can change it to:
"Select Type <select name='conversion_type' onchange=\"loadXML('abcd')\"> "
I'm building a small app with a few modal dialog windows. The windows require a tiny bit of HTML. I've hard coded the window HTML in the javascript library but am not thrilled with this solution. Is there a more elegant way to do this? It seems that JavaScript doesn't have multi line strings/heredoc syntax.
var html = "<div id='email_window'><h2>Email Share</h2><div>";
html = html + "<form action='javascript:emailDone();' method='post'>";
html = html + "<div><label for='to'>To</label><input id='to' type='text'></div>";
html = html + "<div><label for='from'>From</label><input id='from' type='text' value='" + email + "'></div>";
html = html + "<div><label for='subject'>Subject</label><input id='subject' type='text' disabled='disabled' value='" + subject + "'></div>";
html = html + "<div><label for='body'>Body</label><input id='body' type='text' disabled='disabled' value='" + body + "'></div>";
html = html + "<div><input type='submit' value='Send'><input type='button' value='Cancel' onClick='javascript:$.fancybox.close();'></div>";
html = html + "</form></div>";
$("#data").html(html);
Added to clarify the original message-
Any solution can't use Ajax/XHR to pull in the template file because the javascript library will be on a different domain that the html file it's included in
It's a little like ShareThis. The library will be included on a number of different sites and attached to the onClick event of any anchor tag inside divs with attribute sharetool="true".
For example:
http://www.bar.com - index.html
<html>
...
<script type="text/javascript" src="http://www.foo.com/sharetool.js"></script>
...
<body>
<div sharetool="true">
</div>
...
</html>
You can include the HTML as regular markup at the end of the page, inside an invisible div. Then you're able to reference it with jQuery.
You then need to programmatically set your variable fields (email, subject, body)
<div id='container' style='display: none;'>
<div id='your-dialog-box-contents'>
...
...
</div>
</div>
<script type='text/javascript'>
$("#from").val(from);
$("#subject").val(subject);
$("#body").val(body);
$("#data").html($("#your-dialog-box-contents"));
</script>
Templates. Pick your poison
EJS
jQuery templates (nb: development discontinued)
underscore templates
mustache
jResig micro templates
Either inline them as script blocks or load them using ajax as external resources.
I personally use EJS as external template files and just get EJS to load them and inject them into a container with json data bound to the template.
new EJS({
url: "url/to/view"
}).update('html_container_name', {
"foobar": "Suprise"
});
And then view files use generic view logic.
// url/to/view
<p> <%=foobar %></p>
For multiline strings (no frameworks, just javascript) there are several solutions. See my answer to this SO Question. You could combine that with some simple templating:
String.prototype.template = String.prototype.template ||
function (){
var args = Array.prototype.slice.call(arguments)
,str = this
,i=0
;
function replacer(a){
var aa = parseInt(a.substr(1),10)-1;
return args[aa];
}
return str.replace(/(\$\d+)/gm,replacer)
};
//basic usage:
'some #1'.template('string'); //=> some string
//your 'html' could look like:
var html =
[ '<form action="javascript:emailDone();" method="post">',
' <div><label for="to">To</label>',
' <input id="to" type="text"></div>',
' <div><label for="from">From</label>',
' <input id="from" type="text" ',
' value="$0"></div>',
' <div><label for="subject">Subject</label>',
' <input id="subject" type="text" disabled="disabled" ',
' value="$1"></div>',
' <div><label for="body">Body</label>',
' <input id="body" type="text" disabled="disabled" ',
' value="$2"></div>',
' <div><input type="submit" value="Send"><input type="button" ',
' value="Cancel" ',
' onClick="javascript:$.fancybox.close();"></div>',
'</form>'
] .join('').template(email, subject, body);
Personally I like building DOM trees like this:
$('#data').html(
$('<div/>', {
id: 'email_window',
html: $('<h2/>', {
html: 'Email Share'
})
}).after(
$('<form/>', {
action: 'javascript:emailDone();',
method: 'post',
html: $('<div/>', {
html: $('<label/>', {
for: 'to',
html: 'To'
}).after($('<input/>', {
id: 'to',
type: 'text'
}))
}).after(
... etc
)
})
)
);
There is 2 solutions tto your problem:
- An alternative to the heredoc Syntax in javascript is to escape the newline char with \ :
var tpl = "hello\
stackoverflow\
World !";
The char is escaped so ignored, and it wont take place in the resulting string.
You can also create a plain html file with your template, and in your js script you create a hidden iframe and load the crossdomain html template. You can now access the document object of the iframe and retreive body.innerHTML. In theory! I Didn't tested this solution yet....
You're right, JS doesn't have heredocs or multi-line strings. That said, the usual approach to this is to have the HTML in...the HTML, and show or hide it as appropriate. You're already using jQuery, so you're most of the way there:
<div style="display:none;">
<form method='post' class="email">
<input id='from' type='text'> <!-- other form fields omitted for brevity -->
</form>
<form method='post' class="facebook"></form> <!-- again, omitted for brevity -->
</div>
Then, you can populate the form and toss it in the right spot:
$('#data').html($('form.email').find('input#from').val(email).end().html());
Cook.js
div([
button({click:[firstEvent, secondEvent]},
'You can bind (attach) events on the fly.'),
p('Here are some popular search engines'),
ul([
li([
a('Google', {href:'http://www.google.com'})
]),
li([
a('Bing', {href:'http://www.bing.com'})
]),
li([
a('Yahoo', {href:'http://www.yahoo.com'})
])
])
]);
how it works
Objects = Attribute & Events
-> {href:'facebook.com', src:'static/cat.gif', ng-bind:'blah'}
String = Text or Html
-> 'hello world'
Array = Elements
-> [a('hello world', {href:'facebook.com'}), img({src:'static/cat.gif'})]
more on cook.js!