In my JavaScript code I have the following line:
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed('test')'>Se resultat</button>");
The style and type properties work fine but when I try to pass a parameter to the JavaScript function Proceed it doesn't work. I have also tried (\'test\')
How do I solve this problem?
Edit: full html script
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title here.</title>
<script>
function Proceed(var test)
{
alert(test);
}
</script>
</head>
<body style="font-family:Palatino">
<img src="logo.png"/>
<hr/>
<h1 style="text-align:center">Description here.</h1>
<script>
if (window.XMLHttpRequest)
{
request=new XMLHttpRequest();
}
else
{
request=new ActiveXObject("Microsoft.XMLHTTP");
}
request.open("GET","data.xml",false);
var XMLdocument;
request.onreadystatechange=function()
{
if (request.readyState==4)
{
XMLdocument = request.responseXML;
}
};
request.send();
var questions = XMLdocument.getElementsByTagName("question");
for(i = 0; i < questions.length; i++)
{
var x = questions[i];
var questionvalue = x.getElementsByTagName("questionvalue");
document.write("<p style='margin-top:50px; font-size:20px; font-weight:bold; text-align:center'>" + questionvalue[0].childNodes[0].nodeValue + "</p>");
var answers = XMLdocument.getElementsByTagName("answer");
document.write("<form>");
for(n = 0; n < answers.length; n++)
{
y = answers[n];
var answervalue = y.getElementsByTagName("answervalue");
document.write("<input style='margin-left:43%; margin-right:20px;' type='radio' name='" + questionvalue[0].childNodes[0].nodeValue + "' value='" + answervalue[0].childNodes[0].nodeValue + "'>" + answervalue[0].childNodes[0].nodeValue + "<br/>");
}
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed(\"test\")'>Se resultat</button>");
}
</script>
</body>
</html>
It doesn't work because it's invalid HTML:
document.write("</form><button ... onclick='Proceed('test')'>...</button>");
Will be written as:
</form><button ... onclick='Proceed('test')'>...</button>
When it's written to the DOM, the quoting style of onclick dictates where it ends, essentially making the value of onclick Proceed(. You need to change your quoting characters:
document.write("</form><button ... onclick=\"Proceed('test')\">...</button>");
or:
document.write("</form><button ... onclick='Proceed(\"test\")'>...</button>");
Edit: See this plunkr for a simple example
Changing them to escaped double quotes should work for you.
document.write("</form><button style='margin-top:100px; width:150px; position:absolute; left:50%; margin-left:-75px' type='button' onclick='Proceed(\"test\")'>Se resultat</button>");
You could change the single quotes to escaped double quotes:
onclick='Proceed(\"test\")'
Related
I am trying to extract everything before the ',' comma. and replace it with a same name image. How do i do this in javascript or jquery? I tried this but not working for the first and the last string
here is my codes:
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings.join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>
you need to apply loop as :
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
document.write('<img src="/images/'+ arrayOfStrings[i].join('.png" /><img src="/images/') + '/>');
}
}
Same basic premise as #Hemanshi karelia, but instead of using document.write, I suggest creating a string from the image elements and then when all elements have been added to this image string - adding it to the div using jquery's .html(). This is advantageous because it only manipulates the DOM at the end, when all of the image elements have been built and passed into the image string that is then passed into the div, rather than all the other posted answers which alter the DOM on each iteration.
splitString('brickfast,travel insurance,guide,sim cart,tour');
function splitString(stringTotal) {
var stringPortions = stringTotal.split(",");
var imageString="";
for(i = 0; i < stringPortions.length; i++){
imageString += "<img src='/images/" + stringPortions[i] +".png'/>";
}
$('.slidepop').html(imageString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="slidepop"></div>
When you use a split method you get an array of strings in return. But you are directly joining the array with the html tags. You can try something like below in which I am joining the string at a particular index of the array of strings.
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
document.write('<img src="/images/'+ arrayOfStrings[1].join('.png" /><img src="/images/') + '/>');
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>`
If you want to display all images in the array of strings, you can traverse through all array like this.
<html>
<head>
<script>
function splitString(stringToSplit, separator) {
var arrayOfStrings = stringToSplit.split(separator);
var imagesHtml = '';
for(var i = 0; i < arrayOfStrings.length; i++){
if(arrayOfStrings[i] !== ''){
imagesHtml = imagesHtml + '<img src="/images/' + arrayOfStrings[i] + '.png" />'
}
}
var newDiv = $("<div></div>");
newDiv.append(imagesHtml);
$(".slidepop").append(newDiv);
}
</script>
</head>
<body>
<div class="slidepop">
<script> splitString(',brickfast,travel insurance,guide,sim cart,tour',',')</script>
</div>
</body>
</html>`
This is probably a silly question but why do I lose all the formatting when the function test() starts? What should I change in my code? I would really appreciate your help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<style type="text/css">
body {
background: #E6E6FA;
font-family: book antiqua;
}
h1, h2 {
color: grey;
}
</style>
</head>
<h3>Title</h3>
<body bgcolor="#E6E6FA">
<input type="text" id="userInput"></input>
<button onclick="test()">Submit</button>
<p id="Demo"></p>
<p id="Beg"></p>
<p id="Fin"></p>
<script>
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = document.write("Your secret code: " + l + pocz + kon);
var one = nam.slice(-1)
if (one == "a") {
document.write(nam.slice(0,-1) + "bbb");
} else {
document.write(nam + "ccc");
}
}
</script>
</body>
</html>
If document.write is called after the DOM loaded, it replaces the document. Also you are using document.write incorrectly, it doesn't return anything. Just omit it and it will work fine.
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
For the other uses, do the same thing and assign the value to an element via innerHTML.
Please read the documentation before you use an unfamiliar function.
Never use document.write. Ever. Just don't use it. It is completely antiquated.
Felix Kling's answer will work for the first part, since you are assigning html to an element directly. but the later calls are adding more content to the document, not replacing content, so you must append new content to the document, or make another placeholder (like demo). here is how to do it with appending new content:
function test()
{
var nam= document.getElementById("userInput").value;
var l = nam.length;
var pocz = nam.slice(0,1);
var kon = nam.slice(-1);
document.getElementById("Demo").innerHTML = "Your secret code: " + l + pocz + kon;
var one = nam.slice(-1);
if (document.getElementsByClassName("spantext").length===0)
{
var text=document.createElement("span");
text.setAttribute("class","spantext");
document.getElementsByTagName("body")[0].appendChild(text);
}
else {
var text=document.getElementsByClassName("spantext")[0];
}
if (one == "a") {
text.innerHTML=nam.slice(0,-1) + "bbb";
} else {
text.innerHTML=nam + "ccc";
}
}
fiddle
I want to add any URL of CurrentTabs here in this "popup.js" to bookmarks.
function GetUrls()
{
var CurrentTabs = new Array();
chrome.tabs.query({}, function (tabs) {
for (var i = 0; i < tabs.length; i++)
{
CurrentTabs[i] = tabs[i];
}
for (var i = 0; i < CurrentTabs.length; i++)
{
document.write("<b>" + CurrentTabs[i].title+"</b>"+"<br/><a href='" + CurrentTabs[i].url + "' target='_blank'>" + CurrentTabs[i].url + "</a><br/><br/>");
}
});
}
window.addEventListener("DOMContentLoaded", GetUrls());
document.getElementById("addBookmark").addEventListener('click',addGoogleBookmark);
function addGoogleBookmark()
{
chrome.bookmarks.create({title:"Extension bookmarks",parentId:?????,url:"http://www.google.com"});
alert("Added to bookmarks");
}
The problem here in the function addGoogleBookmark() what is the parentId?
Any idea?
And this is popup.html:
<!DOCTYPE html>
<html>
<head>
<title>Links Collector</title>
<script src="popup.js"></script>
</head>
<body>
<input id="addBookmark" type="button" value="Add a Google bookmark"></input>
<style>
body {
width:500px;
height: 300px;
}
</style>
</body>
</html>
As described in the official documentation:
parentId ( optional string )
The id of the parent folder. Omitted for the root node.
As the parameter is optional for the chrome.bookmarks.create function, you can omit it for a default usage. In this case, the bookmark will go in the Other Bookmarks folder.
For more advanced usage, take a look at the chrome.bookmarks Documentation
I would like to be able to control the font-weight of text if bracketed inside a p tag using JavaScript.
For instance:
The cow jumped over the {moon}. font-weight within {} would be increased.
This so the end user can type this into a text area and on submit the would print to page altering the font-weight within the braces or curly brackets.
Any help on this would be great.
Here is how you can do this:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\{(.*?)\}|\((.*?)\)/g, function (m) {
return '<span style="font-weight: bold;">' + m + '</span>';
});
});
And of course a fiddle.
For the example you need just pure JavaScript, no additional libraries.
Edit:
If you don't want to see the brackets in the result you can use:
var ps = document.getElementsByTagName('p');
foreach = Array.prototype.forEach;
foreach.call(ps, function (p) {
var content = p.innerHTML;
p.innerHTML = content.replace(/\((.*?)\)|\{(.*?)\}/g, function (m) {
return '<span style="font-weight: bold;">' + m.replace(/[\(\)\{\}]/g, '') + '</span>';
});
});
Fiddle: http://jsfiddle.net/ma47D/4/
Best regards!
You can do it with mootools like this:
window.addEvent('domready', function()
{
$$('P').each(function(p)
{
p.set('html', p.get('text').replace(/{([^\}]*)*}/g,"<b>$1</b>"));
});
});
domready is important because it must be done after page is completely loaded. converting to jquery would not be so hard.
http://jsfiddle.net/Smw7Q/1/
Locally you can handle it like this:
<!DOCTYPE html>
<html>
<head>
<script>
function transfer(){
document.getElementById("result").innerHTML=document.getElementById("demo").value.replace(/{/g,'<strong>').replace(/}/g,'</strong>');
}
</script>
</head>
<body>
Input: <input type="text" name="input" id="demo"><br>
<input type="button" value="Submit" onclick="transfer();">
<p id="result"></p>
</body>
</html>
If you submit the text to server, the magic can be done similarly at server side.
My suggestion
<!DOCTYPE html>
<html>
<head>
<style>
p span {
font-size:1.5em;
}
</style>
<script>
function regex(){
document.getElementById("output").innerHTML=
document.getElementById("input").value.replace(/{(.*?)}/g, "<span>$1</span>");
};
</script>
</head>
<body>
<p id="output"></p>
<textarea id="input" rows="30" cols="80"></textarea>
<input type="button" value="Input" onclick="regex();"/>
</body>
<html>
Of course, prior to submitting, you need to sanitize your data.
If tried something, but I'm sure there are more elegant solutions.
http://jsfiddle.net/xT7Fg/
$(document).ready(function(){
$(tb).blur(function(){
var str = '';
var nextFont = 0;
$.each($(tb).val(),function(i,char){
if(nextFont == 0){
if(char == '{'){
if($(tb).val().indexOf(i,'}')){
str += '<font size="15">';
nextFont = $(tb).val().indexOf('}', i);
} else {
str += char;
}
} else {
str += char;
}
} else if (nextFont === i) {
str += '</font>';
nextFont = 0;
} else {
str += char;
}
});
$("#txt").html(str);
});
});
I'm writing my first program to make an extension in Google chrome, i just took the "hello world" tutorial as example from here
This is my html file source code :
<!doctype html>
<html>
<head>
<title>Getting Started Extension's Popup</title>
<style>
body {
min-width:357px;
overflow-x:hidden;
}
img {
margin:5px;
border:2px solid black;
vertical-align:middle;
width:75px;
height:75px;
}
</style>
<!-- JavaScript and HTML must be in separate files for security. -->
<script src="popup.js"></script>
</head>
<body>
</body>
</html>
ad this is my javascript file source code :
var req = new XMLHttpRequest();
req.open(
"GET",
"http://api.flickr.com/services/rest/?" +
"method=flickr.photos.search&" +
"api_key=90485e931f687a9b9c2a66bf58a3861a&" +
"text=hello%20world&" +
"safe_search=1&" + // 1 is "safe"
"content_type=1&" + // 1 is "photos only"
"sort=relevance&" + // another good one is "interestingness-desc"
"per_page=20",
true);
req.onload = showPhotos;
req.send(null);
function showPhotos() {
var photos = req.responseXML.getElementsByTagName("photo");
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
for (var i = 0, photo; photo = photos[i]; i++) {
var img = document.createElement("image");
img.src = constructImageURL(photo);
document.body.appendChild(img);
}
}
// See: http://www.flickr.com/services/api/misc.urls.html
function constructImageURL(photo) {
return "http://farm" + photo.getAttribute("farm") +
".static.flickr.com/" + photo.getAttribute("server") +
"/" + photo.getAttribute("id") +
"_" + photo.getAttribute("secret") +
"_s.jpg";
}
The example is very simple and it works fine, but when add my own javascript instruction, it doesn't display it, the instruction that added is in showPhotos() function and it's :
var element = document.createElement('h1');
element.appendChild(document.createTextNode
('tete '+document.location.href+'hgdfhgd'));
in the result, i can see the other content but my 'h1' i don't see it.
i missed something ? can anyone help me please ?
Thanks
You're creating an element but you're not adding it to the page. So it can't be visible.
You can see it you add it, for example like this :
var element = document.createElement('h1');
element.appendChild(document.createTextNode ('tete '+document.location.href+'hgdfhgd'));
document.body.appendChild(element);