creating html paragraphs using javascript functions - javascript

I am writing a small game in javascript. When the user presses a button, text is returned. I am getting the feeling that there is an easier way than writing:
document.getElementById("logBox").innerHTML = "<p> X event is happening <p>" + document.getElementById('logBox').innerHTML;
So I am trying to write a function I can use like this:
function LOG(input){
document.getElementById("logBox").innerHTML = "<p> input <p>" + document.getElementById('logBox').innerHTML;
}
But even using the special characters sign like \ I have not been able to make it work. I have been searching for a solution but cannot seem to find one. Any suggestions? Thanks

function LOG(input){
// get the #logBox element, then keep it in a variable
// until the end of the function
var logBox = document.getElementById("logBox");
// This will never work -- unless you literally want to add a paragraph
// that says "input" each time you call this function.
// logBox.innerHTML = "<p> input </p>" ...
// Try this
logBox.innerHTML = "<p>" + input + "</p>" + logBox.innerHTML;
}

Related

JavaScript. Help copying text from x.path and inserting into a popup text box

I am trying to create a script to insert a sentence into a pop-up box. The sentence will remain the same, with only the person's name changing.
I select a check box on the webpage, copy the person's name from the web page using the ClassName (also tried xPath), select the upload button and finally, enter a sentence with the person's name inserted. Everything works fine until I insert the code to copy the name.
I activate the script from a bookmark in firefox as this will be the first of many scripts, and it is in a convenient place when working.
I thought this would be simple, but it is causing me some problems. Any help on this would be greatly appreciated.
document.getElementById("1234").click();
NAME = document
.getElementsByClassName("CLASS_NAME");
.getText()
.then(function (value) {
return value;
});
document.getElementById("UploadBoxButton").click();
document.getElementById("Notes").value = "Hello " + NAME + ". How are you?";
document.getElementById("Notes").click();
Solved:
async function example() {
let NAME = document.querySelector("CSS PATH").textContent;
let CANDIDATE = NAME.trim()
document.getElementById("ELEMENTID").click();
document.getElementById("ELEMENTID").click();
document.getElementById("ELEMENTID").value = "Hello " + CANDIDATE;
}
example()
What is the problem exactly ? NAME hasn't the expected value ?
I think this is due to the use of async function. I mean, when NAME is called to set Notes value, getText() has probably not finished to be call asynchronously.
Moreover, where does getText() come from ? Can't you simply use :
document.querySelector("#1234").click();
const NAME = document.querySelector(".CLASS_NAME").textContent;
document.querySelector("#UploadBoxButton").click();
document.querySelector("#Notes").value = "Hello " + NAME + ". How are you?";
document.querySelector("#Notes").click();
And what is Notes ? Are you sure you can change its value like this ? Otherwise, try this :
document.querySelector("#Notes").textContent = "Hello " + NAME + ". How are you?";

Add onclick event for tr element dynamically from JavaScript

I am creating a table dynamically, I need to add an onclick event for each element as it is added, but this needs a dynamic parameter add, I have tried the following
trElements[i + 1].onclick = function () {
navigateToController('/Home/Client', "'" + machine.DeviceID + "'");
};
but this shows the onclick event as navigateToController('/Home/Client', "'" + machine.DeviceID + "'")
and not navigateToController('/Home/Client', 'DeviceName'); as I thought it would, I have also tried to have the onclick event in the html, and replace the DEVICEID with the actual deviceid.
var element = trElements[i + 1].outerHTML.replace('DEVICEID', machine.DeviceID);
trElements[i + 1].outerHTML = element;
this shows up as been correct, but when the page is loaded, it still has deviceid in there ?
I am sure it is something really simple... but any pointers would be appreciated.
I'm not entirely sure I understand the question, but it might be a scope issue. You might need to use bind to create the handler with the current value of DeviceID:
var machineId = 0;
function navigateToController(machineId) {
alert(machineId);
}
function addRow() {
var t = document.getElementById('thetable');
var tr = t.insertRow();
var td = tr.insertCell();
td.appendChild(document.createTextNode("machine " + machineId));
tr.addEventListener('click', navigateToController.bind(null, machineId));
machineId++;
}
<button onclick="addRow()">Add Row</button>
<table id="thetable"></table>
but this shows the onclick event as navigateToController('/Home/Client', "'" + machine.DeviceID + "'")
You're not going to see the value of the variable in the markup, if that's what you mean.
Why not just navigateToController('/Home/Client', machine.DeviceID )? It's already a string. No need to try to add quotes around it. You'd end up with a parameter that includes the quotes.
var deviceId = 'theDeviceId';
// This is not what you want. Notice this alert includes the single quotes as part of the string: "'theDeviceId'"
alert( "'" + deviceId + "'");
// This is what you want. This alert has just the (unquoted) value.
alert( deviceId );
The better way to do this is not to do it at all.
Better attach the event handler to existing container (the table in this case seems good) and check for bubbling events.
With jQuery is quite simple:
var myTable = $("table#theTable");
myTable.on("click", "tr", function(){ // Click event handler.
var clickedRow = $(this);
...
});
If you need some data related to each row, simply attach to it in "data-" attributes (i.e. «data-myId="someId"») of the tag. Then you could read them simply by clickedRow.data("myId") from event handler function.
This way you have single function to handle all events for all rows. Simpler and wasting too less mamory.
trElements[i + 1].onclick = (function () {
var deviceId = machine.DeviceID;
return function(){
navigateToController('/Home/Client', "'" + deviceId + "'");
}
})();
ok, so I couldn't get to the bottom of adding an onClick function dynamically, so, I changed my code around, and pass a viewModel array containing all the data I needed to create the table, so when I open the clients view, I send a list of all the relevant clients, and when I select the row I need, I just pass a single viewmodel of the client, I then update the html with the c# code #model.variable. I can easily update these from my signalr code once its created.
thanks for everyones input.
Just to update, I have found a solution I think, I could create the element, add the data to the innerHtml, and use:
setAttribute("onclick", "navigateToController('/Home/Client', '" + deviceId + "')");
I have used this in another part of my solution, and it works...

Adding and Displaying Array Issue

var reset = function ()
{
var p = parseFloat($("#IA").val());
var q = parseFloat($("#IB").val());
var m = parseFloat($("#CGCD").val());
var aR = [];
aR += ["GCD(" + p + "," + q + ")=" + m];
document.getElementById("PGCD").innerHTML = aR + "\n";
document.getElementById("IA-error").innerHTML="";
document.getElementById("IB-error").innerHTML="";
$("#IA").focus();
};
The code above is only for a 'reset' function, a part of additional code (not present), the purpose which is to find the Greatest Common Denominator, GCD.
My 'reset' function is connected to a button, #reset, the purpose of which is to do four things:
add and store the string GCD(p,q)=m to the array 'aR'; p/q/m are variable stand-ins for the values of the input text areas #IA, #IB, and #CGCD (the GCD of #IA and #IB);
display the array 'aR' in a text-area #PGCD each time the reset button is clicked; this is why I used an array;
clear the two input text areas #IA and #IB;
clear the one output text area;
As it stands, all four objectives are completed successfully, with one exception: for the second objective, only the most recent GCD calculation is outputted; none of the previous calculations output.
I cannot get the array to list the different saved calculations within it. I think (?) the new calculations are being added to the array, but I am not sure.
I've tried a 'for' statement, and an 'if' statement, neither of which worked. I don't know whether I coded it wrong, or if it wasn't the right solution for my issue.
I tried to search the forums (here) for a solution, but was unable to find one.
Thank you.
If I'm understanding what you are describing, I believe your problem is that you are attempting to use += to add elements to an array. You should use
aR.push("GCD(" + p + "," + q + ")=" + m);
The += operator is used for addition of a value to itself as well as string concatenation.
Edit: per comments below, the main issue was declaration of aR as a local variable. It needs to be either global or declared within the same scope.

Create Regex from a string variable in javascript

var tags=["div","span","body"];
for (i=0; i<=tags.length; i++){
source = source.replace(/\&lt\;<tags[i]/i, '<span class="tags[i]"><tags[i]</span>');
}
Basically, I'm trying to put all the opening div,span and body tags around a span with a class set accordingly. But, I am having issues getting the variables inside there.
I can put lines and lines for each different tag but considering this function is called on every key press I want to keep the code as small and efficient as possible.
Or are there other alternatives? I mean it would be even better if something along these lines was possible:
source = source.replace(/\&lt\;<div|<span/i, '<span class="div|span"><div|span</span>');
But, it clearly does not get me anywhere.
You can construct your regex from a string using the RegExp object:
source = source.replace(new RegExp("\\&lt\\;<" + tags[i], "i"), '<span class="' + tags[i] + '"><' + tags[i] + '</span>');
But your idea for an alternative is also possible by capturing the tag and referencing it in the replacement:
source = source.replace(/\&lt\;<(div|span|body)/i, '<span class="$1"><$1</span>');
You can use regexes with | (equivalent of OR): () are used to get the matched elements (div, span or body), and you can get them with $1
source.replace(/<(div|span|body)/i,'<span class="$1"><$1></span>')

Delimiting four nested items in Javascript/Html

Okay this is frustrating me to no end. I recently coded a page in JS for a buddy of mine who wants to display wedding pictures to a family to see which ones they'd like to purchase.
I used a for loop to count 1-904:
for (beginnum=1;beginnum<=904;beginnum++) { yada yada...
Then, I used adobe bridge to rename the camera files to be 1-904 and their thumbnails (1-904 + _thumb) and used the loop number to display 904 image spaces, and the correctly numbered picture:
[note:using <) in place of the usual open tag since the site wont display it]
IE...
document.write(beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' />");
Opera...
document.write("<div>" + beginnum + ":" + "<img src='pictures" + beginnum + "_thumb.jpg' /></div>")
This all works perfectly in IE and Opera (with external CSS modifying the div to not line break).
I then created a function to call up the large version of the picture when clicked on.
The problem is, when I try and nest this function into the JavaScript generated HTML I would need four delimiters. I've heard ''' or """ or the &+numeric; work in some cases as a third and fourth but I can't seem to get them to work... where I run into a problem is here...
[note:again using <) for open tag]
document.write("<a href='javascript:void(0); onClick=
Since I've already used up " and ' I now have nothing left to use to call the function when a picture is clicked.
I usually don't ask for any help, but this time I can't think of anything else that should work... I assume maybe using JS to generate the HTML leaves me with ONLY 2 delimiters that will be recognized by the browser but I am not sure, anyone know for sure? Any fixes anyone can think of?
Thanks,
~Z~
Maybe this will work
for (i=0; i<904;i++)
{
document.write("<div class=\"DivClassName\"><img src=\"pictures_" + i + "thumb.jpg\" onclick=\"OpenAWindowAndDisplayTheBigPhoto(" + i + ")\"></div>");
}
Another approach: Suppose you put everything inside a <DIV id="mainDIV">
var mainDIV = document.getElementByID("mainDIV");
var div, img, a;
for (i=0; i<904; i++)
{
div = document.createElement("DIV");
div.className = "DivClassName";
a = document.createElement("A");
a.href = "javascript:void(0)";
a.onclick = function() {OpenAWindowAndDisplayTheBigPhoto(i);};
img = document.createElement("IMG");
img.src = "pictures_" + i + "thumb.jpg";
mainDIV.appendChild(div);
div.appendChild(a);
a.appendChild(img);
};
Try building the string one piece at a time instead of trying to build the whole literal for the document.write.
Whenever things get too convoluted to follow, just do one part at a time.
var s;
s = "'Hello.' ";
s += '"I must be going."';
Without seeing code it is hard to say for a fact, but you may want to take more advantage of the fact that javascript is a first-class language, so you can create functions and pass them as arguments to other functions, or have functions return functions.
By doing this, you can decompose your page into something that sounds a bit more manageable.
Also, take advantage of the onclick event.
You should be able to simplify the javascript and so avoid this problem, IMO.

Categories