Placing generated JavaScript URL into `<a href="{{Text here}}">` - javascript

So, I have an external JavaScript that generates 4 numbers and puts them between 2 parts of text, like this
document.getElementById("gen3").textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669";
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<div id="gen3"></div>
It generates properly and selecting it and opening it in a new tab works perfectly, but I'd like to make it easier by placing it directly into an href.

You can change your div into an a (anchor tag) in your HTML and use its href property in JavaScript to set the URL destination used when you click it. You can also choose to set its textContent to the same value, which makes it clearer to people using the tool where exactly they are going when they click the link.
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
Demo Snippet
var gen3 = document.getElementById("gen3")
function postmessage() {
// Pretending these are "random" values, and assuming you have the code for them already
var first = 1,
fnum = 2,
snum = 3,
tnum = 4
// Later...
gen3.href = gen3.textContent = "https://www.google.com/search?q=Lego+set:+" + first + fnum + snum + tnum + "&num=30&safe=off&source=lnms&tbm=isch&sa=X&ved=0ahUKEwj08YDU_MjSAhXLLMAKHSp4CxQQ_AUICCgB&biw=1366&bih=669"
}
<p>
<input id="gen-btn" type="button" value="Generate" onclick="postmessage();" />
</p>
<p>
<a id="gen3"></a>
</p>

You can create an anchor tag inside the div
Then you can do like this
JS
document.getElementById("linkText").setAttribute('href','www.google.com')
HTML
<div id="gen3">
Click Me
</div>
DEMO

Related

append a button with a link for each row

I'm new to JavaScript so excuse me for this question,,
when i use jQuery to append data from firebase to a table
i want to append a button but has a href url from variable
url_val = is a variable url i want when i click to the button go to website
$("#data").append("<tr><td>" + title_val + "</td><td><button class='box'> " + url_val + "</button></td></tr>");
i was trying to do the fowling
$("#data").append("<tr><td>" + title_val + "</td><td> <button class='box'> " + GO + "</button></td></tr>");
but i cant add a variable inside
is there a solution for this
I think you've made two mistakes, the first is not using + to concantate strings appropriately as mentioned by #Taplar and #abney317.
Secondly you have unnecessarily taken 'GO' out of your hard coded string, but also not stored it as a variable or concatenated it appropriately.
I have fixed both of these and provided a demonstration.
Let me know if you were hoping for something else.
Demo
// Add click event to add row
$("#addRow").click(function() {
// Store variables
title_val = "Title";
url_val = "www.google.com";
// Append data
$("#data").append("<tr><td>" + title_val + "</td><td> <button class='box'>GO</button></td></tr>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
</table>
<button id="addRow">Add Row</button>

LocalStorage element not corresponding with visual element after moving

I created a note-taking front end page which saves the data from text field into the localStorage. The problem occurs when the user deletes one field using the Delete button, which corresopndents to DeleteT function.
For example if we have three textareas with id txt1, txt2, txt3 they apper with the sames names in the localStorage. After the user deletes for example txt2 using the Delete button, in the local Storage the left ones are txt1 and txt3 but on the next reload there are two textareas with id txt1 and txt2 because in the localStorage the number of textareas is saved by key AllNum. The data from txt3 in the localStorage should go to txt2 in the DOM on the page.
The problematic functions:
// Deletes textelemnt
function DeleteT(num) {
localStorage.removeItem("txt" + num);
localStorage.removeItem("h" + num);
console.log('del');
i=i-1;
var now = localStorage.getItem("AllNum");
if((now-1)<0){
now=0;
localStorage.setItem("AllNum", (0));
}else{
localStorage.setItem("AllNum", (now-1));
}
$("div.textarea" + num).remove();
}
//Loads all the text elemnts with a for loop until the number of areas is reached
function load() {
if (document.getElementById("alltxt").childElementCount < localStorage.getItem('AllNum')) {
for (var i = 1; i <= localStorage.getItem('AllNum'); i++) {
$('#alltxt').append('<div class="textarea' + i + '"><input onkeyup="save()" id="h' + i + '"></input><textarea onkeyup="save()" id="txt' + i + '"></textarea></br><button onClick="cut(txt' + i + ')" class="f b">Cut</button> <button onClick="copy(txt' + i + ')" class="f b">Copy</button> <button onClick="speak(txt' + i + ')" class="f b">Speak</button> <button onClick="download(' + i + ')" class="f a">Save</button><button onClick="textFull(' + i + ')" class="f">Fullscreen</button> <button onClick="DeleteT(' + i + ')" class="f">Delete</button> </div>');
document.getElementById('txt' + i).innerHTML = localStorage.getItem("txt" + i);
document.getElementById("h" + i).setAttribute('value', localStorage.getItem("h" + i));
}
}
}
https://codepen.io/abooo/pen/NoqOXX?editors=1010
To experience the problem create three textareas using the + button. Then Enter data in the them. After this delete the latter. Finally reload the page and make sure the two textreas appeared. You can see the data from the second one is missing replaced with null value. How to fix this issue?
The result
LocalStorage values
The value "AllNum" only stores total number of items; it does not contain any information about which items were there before reloading. So in first load, if you add 3 items and remove the 2nd, your local storage will have "AllNum" equal 2, and the next time it loads, your load() function will iterate from 1 to 2, looking for data of text1 and text2. That's why only 1st item displays correctly.
Another problem that you might notice after fixing the above issue is that the iteration is not good for unique id; a simple test can prove it: you add 3 items, remove the 2nd - now you have text1 and text3 in localStorage, and AllNum is 2. If you add one more, the newest item will have id as 3 and all its data will be written on top of the existing text3 and h3.
2 suggestion for your code:
Use something else as unique id instead of iteration number. Use Math.random(), for example.
Store all your unique ids in localStorage, not AllNum. Rewrite your code to add and delete unique ids from localStorage.
A small example of how to modify the 2 function add() and save():
function add() {
var newId = Math.random();
// your render logic here. Replace i with newId
save(newId);
}
function save(newId) {
localStorage.setItem("txt" + newId, document.getElementById('txt' + a).value);
localStorage.setItem("h" + newId, document.getElementById('h' + a).value);
var allIds = JSON.parse(localStorage.getItem('AllIds'));
allIds.push(newId);
localStorage.setItem("AllIds", JSON.stringify(allIds));
}

jQuery .html() function removing text

I am trying to edit the div's text, but when i use my function to update the rowcount, everytime the text vanihes completely. Would by nice if you could also explain why.
Thanks in advance.
My update function:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + String(rowCountF) + ")";
var vtext = "Teilnehmer (" + String(rowCountV) + ")";
$("#divf").html(ftext);
$("#divv").html(vtext);
My div layer:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
Code for divf:
<div id="divf"class="tableheader"> <h2>Teilnehmer</h2> </div>
You are actually replacing the contents of the div itself with your text. This means the heading disappears and there is only plain text.
Probably you wanted to replace the heading contents:
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
This will select the h2 elements inside the divs and hence will update only the text inside the headings.
The result will look like the following:
<div id="divf"class="tableheader"> <h2>Teilnehmer (987)</h2> </div>
<div id="divf"class="tableheader"> <h2>Teilnehmer (123)</h2> </div>
.html() sets the HTML, meaning it replaces anything that's currently there. If you want to add to the HTML, you'll need to set the HTML to what's already there plus what you're adding, like so:
var rowCountF = $('#tablef tr').length;
var rowCountV = $('#tablev tr').length;
var ftext = "Teilnehmer (" + rowCountF + ")";
var vtext = "Teilnehmer (" + rowCountV + ")";
//Get already-existing HTML
var divfHtml = $("#divf").html();
var divvHtml = $("#divv").html();
//Set the new HTML to the existing + the new text
$("#divf").html(divfHtml + ftext);
$("#divv").html(divvHtml + vtext);
If you only want to replace the heading, then just target the <h2> as Martin Zikmund suggested in his answer.
You need to reference the h2 for the div. using .html() will replace ALL of the html inside the #divf which in this case means it will replace the h2
$("#divf h2").html(ftext);
$("#divv h2").html(vtext);
Example: https://jsfiddle.net/qhef0toc/3/

Jquery Replace function not working properly in ie7 and ie 8

I have the following Raduio buttons with Labeles associated with that.
<div id="dependents">
<input ng-non-bindable type="radio" id='Partner' name="relationship" class="dependent-relation" value='P' />
<label for="Partner">Prtner</label>
<input ng-non-bindable type="radio" id='Child' name="relationship" class="dependent-relation" value='C' />
<label for="Child">Child</label>
</div>
Above div will be added dynamically to the page. We can have multiple dependants.
So every time while appending this div, i'm changing the Id, name of Radio button along with for label. Below is the script i'm trying to replace.
var html = htmlContent; // html content will be above code
html = html.replace('Partner', 'Partner' + count); // Replacing Id : Working fine
html = html.replace('for="Partner"', 'for="Partner' + count + '"'); // Replacing for : Not working
html = html.replace('Child', 'Child' + count); // Replacing Id : Working fine
html = html.replace('for="Child"', 'for="Child' + count + '"'); // Replacing for : Not working
This is working perfect in IE9, IE 10, chrome, but its not working IE7 and IE8.
Can any one help me on this?
I have found the problem...
I think whenever i tried to replace like this
html = html.replace('name="relationship"', 'name="relationship"' + count + '"');
its not working(only in IE 8 & 7). Any suggestion???
the reason it does not work is because before you are replacing the same word.
Try with:
var html = "<div id="Dependents"> ... </div>";
html = html.replace('for="Partner"', 'for="Partner2' + count + '"');
html = html.replace('Partner', 'Partner' + count);
html = html.replace('Partner2', 'Partner');
html = html.replace('for="Child"', 'for="Child2' + count + '"');
html = html.replace('Child', 'Child' + count);
html = html.replace('Child2', 'Child');

How to access an element that is placed next to it?

I have following html structure:
<span class="thump">1</span>
<a class="tp" href="#" programm="5">Post</a>
Now I want to write thump according to programm attribute. This is how I get the the a element according to the programm number:
$("a.tp[programm='" + programm + "']");
How do I refer to the thump element that is next to this a element?
var anchor = $("a.tp[programm='" + programm + "']");
var thump = anchor.prev();
Or if there is only one thump element (previous is recommended, especially if they are adjacent elements):
var anchor = $("a.tp[programm='" + programm + "']");
var thump = anchor.siblings('.thump');

Categories