Dynamically change string with JS? - javascript

I'm using a form that needs to pass a hidden field:
<script type="text/javascript">
var ss_form = {'account': 'XXXXX', 'formID': 'XXXXX'};
ss_form.width = '100%';
ss_form.height = '500';
ss_form.domain = 'app-XXXXX.marketingautomation.services';
ss_form.hidden = {'field_XXXXX': 'test item, another item' };
</script>
All it needs to be is a comma separated list, but I'm trying to dynamically add comma separated items using external buttons, for example clicking:
<button>add this string</button>
would make it
ss_form.hidden = {'field_XXXXX': 'test item, another item, add this string' };
I've tried using append to a div and then using innerHTML as a variable but it's just passing the initial div content from page load rather than the dynamically added items as well. JS is not my strong suit... any help is very much appreciated. Thank you!

Looks like you want something like this:
<button id="button">add this string</button>
document.getElementById("button").onclick = function(event) {
ss_form.hidden.field_XXXXX += ' ' + this.innerHTML;
}

Have you tried to concatenate the values?
The conactenacion is a process in which two or more values are joined by an operator, commonly more (+) or two points (..).
Try this way
<button id="btn">add this string</button>
<script>
document.getElementById ("btn").onclick = function (event) {
   ss_form.hidden.field_XXXXX + = this.innerHTML + ', '; //Add separated comma values
}
</script>

Related

How to extract an array of all HTML tags from a textbox using javascript

I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)

Javascript library to compare 2 html string like freecodecamp

I have a project where we have a compare the original code and code written by the user. The user can code and then on button click we have to compare the written code with original code.
I have both original and new code in string
originalHtml : <html><body style='color:white;background:purple;'></body></html>
newHtml : <html> <body style="background:purple;color:white;"> </body> . </html>
Here there are 3 things to keep in mind
1) White space (should not show the difference for white space)
2) ' and " (should not compare quotes, both are valid in HTML)
3) Attribute order (should show difference only for missing attribute, ignore attributes order)
Any suggestions or alternative solution will be appreciated.
I have created a code pen for you, this will solve your problem.
https://codepen.io/bearnithi/pen/KEPXrX
const textArea = document.getElementById('code');
const btn = document.getElementById('checkcode');
const result = document.getElementById('result');
let originalHTML = `<html><head>
<title>Hello </title>
</head><body>
<p class="hello"></p>
</body>
</html>`
btn.addEventListener('click', checkCode);
function checkCode() {
let newHTMLCode = textArea.value.replace(/\s/g,"");
let oldHTMLCode = originalHTML.replace(/\s/g,"");
if(newHTMLCode === oldHTMLCode) {
console.log(true);
result.innerHTML = 'TRUE';
} else {
console.log(false);
result.innerHTML = 'FALSE';
}
}
<textarea id="code">
</textarea>
</br>
<button id="checkcode">Check Code</button>
<p id="result"></p>
You can convert all of them to one uniform and compare them.
Example:
remove all space, tab (with one space)
replace all ' to "
sort attribute.
and some rule you defined
Example cheerio to get attribute:
var cheerio = require('cheerio');
var yourString = `<html><body attr2='hi' attr1='hello' style='color:white;background:purple;'></body></html>`;
var $ = cheerio.load(yourString);
var yourAttrs = $('body')[0].attribs;
var sorted = {};
Object.keys(yourAttrs).sort().forEach(function(key) {
sorted[key] = yourAttrs[key];
});
console.log(sorted);

Get specific value from a HTML output

I am getting the following result from a data source.
"<span class=\"highlight\">DSDT10</span><div>011XBY</div>"
The value in span and div could vary.
And I want only the value inside the span "DSDT10" in a separate variable.
What I have tried:
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.replace(/<\/?span[^>]*>/g, "");
$('#output').append(formattedData);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="output"></div>
Expectation:
Retrieve only "DSDT10" from the data variable.
Any suggestion is appreciated. Thanks.
You just want to get the text within the span? You could modify your regex a bit and use a match..
var data = '<span class=\"highlight\">DSDT10</span><div>011XBY</div>';
var formattedData = data.match(/<span[^>]*>([^<]*)<\/span>/, "")[1];
But since you're using jquery you could also just do this:
var formattedData = $("<div>", {html: data}).find("span").text()
Only two lines of code:
_str = "<span class=\"highlight\">DSDT10</span><div>011XBY</div>";
_span = $(_str).filter('span').text();
It's enough only one line:
$('#output').html($('span').html());

Highlight given strings on a static HTML page with javascript

There is a static HTML file:
<html>
<body>
ABC
XYZ
foo
bar
</body>
</html>
Our question: How can I put in buttons/links (?) to this single, static HTML file, so that the people that are visiting this page can highlight given predetermined strings after clicking on the button/link on the page? With javascript? But how?
UPDATE: Place "ABC" from the above HTML into <big><b> tags like:
<big><b>ABC</b></big>
There are several ways you could do this.
a. Using plain javascript, you can try this:
1- Have a variable with the strings you want highlighted.
highlight = ['ABC', 'XYZ', ... ];
2- Make the function that highlights the strings from the highlight variable
makeHL = function(strings) {
// Get the HTML you want to search and replace strings on
myHTML = document.getElementsByTagName('body')[0].innerHTML;
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
strings.forEach(function(str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
document.getElementsByTagName('body')[0].innerHTML = myHTML
}
3- When the user clicks your link or your button, just call makeHL(highlights)
jsFiddle Here
Make sure that you include a Ecmascript5 shim such as es5-shim for use of .forEach() in browsers that don't support it.
b. Using a library like jQuery, it's easier to work around browser incompatibilities:
1- Include jQuery before the rest of the code:
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
2- Have a variable with your replacements:
highlight = ['ABC', 'XYZ', ... ];
3- Make the function that highlights the strings from the highlight variable and bind it to the click event:
$('.makeHL').on('click', function() {
// Get the HTML you want to search and replace strings on
myHTML = $('body').html();
// Use string.replace to add <b></b> to them or another form of highlighting.
// You can use regular expressions here to make it more reliable.
$.each(highlight, function(i, str) {
myHTML = myHTML.replace(str, '<b>' + str + '</b>');
});
// Reinsert your new html with the strings highlighted.
$('body').html(myHTML);
});
jsFiddle Here
Working example
HTML:
<p>
<button class="highlight-text">Highlight "ABC"</button>
</p>
ABC
XYZ
foo
bar
JS:
(function(){
function highlightText(textToHighlight) {
var searchExpression;
searchExpression = new RegExp('(' + textToHighlight + ')', 'g');
document.body.innerHTML = document.body.innerHTML.replace( searchExpression, '<b>$1</b>' );
}
document.querySelector('.highlight-text').addEventListener(
'click',
function(){ highlightText('ABC'); },
false
);
})();
http://jsfiddle.net/medda86/9g8XD/
html
ABC
XYZ
foo
bar
<button class="button">Button</button>
Jquery
var predefinedStrings = new Array('ABC','bar');
var arrLength = predefinedStrings.length;
$('.button').click(function(){
for (var i = 0;i < arrLength;i++){
$('body').html($('body').html().replace(predefinedStrings[i],'<b>'+predefinedStrings[i]+'</b>'));
}
});
I would suggest using Jquery javascript library
JQUERY
function highlight(word,content){
//gi makes the replace recursive and case insensitive
var regex = new RegExp( '(' +word+ ')', 'gi' );
return content.replace( regex, bold );
}
function unhighlight(word,content){
var regex = new RegExp( '(' +bold(word)+ ')', 'gi' );
return content.replace( regex, strip );
}
function bold(word){
return "<b>"+word+"</b>";
}
function strip(word){
return word.replace("<b>","").replace("</b>","");
}
highlighted = null;
$(document).ready(function (){
$("body").delegate(".highlight","click",function (e){
var word = $(this).text();
var container = $("body");
var content = container.html();
if(highlighted!=word){
//this is optional if you would like to unhighlight prev selections
content = unhighlight(highlighted,content);
content = highlight(word,content);
highlighted = word;
container.html(content);
}
});
});
HTML
<html>
<body>
ABC
XYZ
foo
bar
ABC
XYZ foo FOO Bar ABC
<button class="highlight">ABC</button>
<button class="highlight">FOO</button>
</body>
</html>
Heres a FIDDLE

Javascript event handler to update a JSON object name

I am just starting out in Javascript and was wondering if anyone would mind pointing me in the right direction with this query I have.
I have created a JSON array and now wish to update some text on the page from the array upon clicking of the button. I have an event handling function that updates an image OK but I can't work out how to have the object name (pageRef) update within the 'nextPage' function so that the text updates from the contents of the array. I appreciate that this is probably a really obvious question but a pointer in the right direct will be greatly appreciated.
var diary_1938 = {
'page_1': {
'date_0': '1st Jan','entry_0': 'This is the first line',
'date_1': '2nd Jan','entry_1': 'This is the second line',
'date_2': '4th Jan','entry_2': 'This is the third line',
'img': 'image_1.jpg'},
'page_2': {
'date_0': '12th Jan','entry_0': 'This is the first line',
'date_1': '13th Jan','entry_1': 'This is the second line',
'date_2': '14th Jan','entry_2': 'This is the third line',
'img': 'image_2.jpg'},
};
var counter = 1;
var pageRef = "page_"+counter;
function nextPage() {
counter++
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
function prevPage() {
counter--
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}
</script>
</head>
<body>
<button type = "submit" name = "submit_prev" onClick = "prevPage()"> << </button>
<button type = "submit" name = "submit_next" onClick = "nextPage()"> >> </button>
<br/>
<script> document.write(diary_1938[pageRef].date_0 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_0 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_1 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_1 + "<br/><br/>"); </script>
<script> document.write(diary_1938[pageRef].date_2 + "<br/>"); </script>
<script> document.write(diary_1938[pageRef].entry_2 + "<br/><br/>"); </script>
<script>document.write("<img id = 'DiaryImage' src = 'image_1.jpg' width='370' height='790' name ='Dunford'/>"); </script>
</body>
document.write is only read once as the page is being loaded into the browser, it's not really best practice to use it for updating dynamic content.
What you could do, is wrap up your dynamic content in a div like so:
<div id="content"></div>
then write a function that populates this div from the JSON data (this could be a lot more elegant but as you're just starting out, for simplicity's sake):
function populatePageFromJson(JSONobject){
var divElement=document.getElementById("content");
divElement.innerHTML=JSONobject[pageRef].date_0+"<br/>"+
JSONobject[pageRef].entry_0+"<br/><br/>"+
JSONobject[pageRef].date_1+"<br/>"+
JSONobject[pageRef].entry_1+"<br/><br/>"+
JSONobject[pageRef].date_2+"<br/>"+
JSONobject[pageRef].entry_2+"<br/><br/>"
}
And when the page loads have this function load up:
window.onload= function() {
populatePageFromJson(diary_1938);
}
also change prevPage() and nextPage() as well (Note that in your case, you forgot to update pageRef):
function prevPage() {
counter--
pageRef = "page_"+counter;
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
populatePageFromJson(diary_1938);
}
Here is a jsFiddler example to tie it all up.
Again this is hardly the most elegant way of doing so, but hopefully it will give you some insight into Javascript.
Once you're comfortable with the understanding of basic Javascript I recommend you getting acquainted with jQuery. It will make such tasks much easier. Good luck!
Because you code in nextPage() is invoked every time when button is clicked. However, your code like :*var counter = 1;var pageRef = "page_"+counter;document.write(diary_1938[pageRef].date_0 + "");* is executed only once when initializing. so you'd better write you code as:
function nextPage() {
counter++;
pageRef = "page_"+counter;
/*clear written content before*/
document.write(diary_1938[pageRef].date_0 + "<br/>");
/*other document.write,*/
document.getElementById("DiaryImage").src = "image_"+counter+".jpg";
}

Categories