how to insert multi line string html using jquery? - javascript

I have following structure and i want to append it to a <div>
but it's showing a compile time error.
$('#row1').html("<div class="4u 12u(mobile)">
<section>
<img src="images/kokan.jpg" alt="" />
<header >
<h3>result[i]</h3>
<p></p>
</header>
</section>
</div>");

$('#row1').html('<div class="4u 12u(mobile)">'
+'<section>'
+'<img src="images/kokan.jpg" alt="" />'
+'<header >'
+'<h3>'+result[i]+'</h3>'
+'<p></p>'
+'</header>'
+'</section>'
+'</div>');
You need to build a proper string, by concatenating parts. "<div class="4u this part was also breaking, you should use combinations of " '' ".

Related

Javascript Regex - add only a character to matched string

I am trying to create a JS regex that matches a a string inside a given piece of code by it's beggining and ending and then only adds one character to that matched string.
Please see below what I mean:
Imagine that I supply the following code:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>
What I need to do is to have the script finding all instances of <img> and add a closing slash to the <img> elements so I would have something like this:
<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image" />
</a>
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>
Any help will be appreciated.
Regards,
T
Usually regex should be avoided for dealing with html/xml, but since your img tag seems broken and img tags are not nested, you can use following regex,
(<img[^>]*)>
and replace it with
$1 />
and fix your broken img tags.
Demo
const s = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
<img src="https://someotherrandomsrc.com" alt="another random image" />
</div>`
console.log('Before: ' + s);
console.log('After: ' + s.replace(/(<img[^>]*[^/])>/g,'$1 />'));
Edit1:
Yes just change the regex to (<img[^>]*[^/])> so that it won't match the one which already has a proper closing tag />.
Updated Demo
Just select the img and its content in a group (<img\s.*?) except the closing tag and use replace with a global flag to replace after it with / slash.
const string = `<div>
<p>This is just some random text</p>
<a href="https://somerandomsrc.com">
<img src="https://somerandomsrc.com" alt="random image">
</a>
<img src="https://someotherrandomsrc.com" alt="another random image">
</div>`
const result = string.replace(/(<img\s.*?)>/g, '$1 />')
console.log(result)

Append Content to HTML and Remove Appended Content When Click Button

The following code allows me to append new content to the div "users". However, I want to be able remove the appended content if the user clicks button.
The current code removes only the "remove" button when its clicked. However, I need to remove the entire appended code with the class "removeuser", in the beginning of the appended code.
Any help will be appreciated!
<div id="users"></div>
<script>
function adduser() {
count += 1;
$('#users').append('<div id="field'+ count +'" class="removeuser[]"><div
id="left"><div id="fieldname">user #'+ count +' Name:</div><div
id="field"><input id="user_name'+ count +'" name="user_name[]"' + '"
type="text" /></input></div><div id="clear"></div></div><div id="leftleft">
<div id="fieldname">user #'+ count +' Age</div><div id="field"><input
type="number" id="user_age'+ count +'" name="user_age[]"
style="width:50px;" min="0"></input></div><div id="clear"></div><br></div>
<div id="leftleft"><a href="javascript: void(0)" onclick="adduser(); return
false;"><div id="field" class="add"><div
style="position:relative;left:-4px;top:1px;">add another user +</div></div>
</a><br></div> <div id="leftleft"><a href="javascript: void(0)"
onclick="$(this).remove();" ><div id="deluser[]" class="add"><div
style="position:relative;left:-4px;top:1px;">-</div></div></a><br></div>
<div id="clear"></div></div>');
var no = document.getElementById("deluser");
no.onclick = function(){
$('#users .removeuser').$(this).remove();
};
</script>
From what I can tell this is might be the solution you're looking for (note not supported in all browser. See below for transpiled version)...
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count))
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = `
<div>
<a href="javascript: void(0)" onclick="deluser(event); return false;">
<div class="add delete-user" data>
<div style="position:relative;left:-4px;top:1px;">-</div>
</div>
</a>
<br>
</div>
`;
return `
<div class="user-container">
<div id="left">
<div class="fieldname">
user #${count} Name:
</div>
<div class="field">
<input id="user_name${count}" name="user_name[]" type="text" /></input>
</div>
<div id="clear"></div>
</div>
<div>
<div class="fieldname">
user #${count} Age
</div>
<div class="field">
<input type="number" id="user_age${count}" name="user_age[]" style="width:50px;" min="0"></input>
</div>
<div id="clear"></div><br>
</div>
<div>
<a href="javascript: void(0)" onclick="adduser(); return false;">
<div class="field" class="add">
<div style="position:relative;left:-4px;top:1px;">add another user +</div>
</div>
</a>
<br>
</div>
${count > 0 ? deleteButton : ""}
<div class="clear">
</div>
</div>
`;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
There area quite a few things wrong with your initial attempt though and I don't mean to be rude, but you should probably do more work learning the basics of HTML, JS and in this case jQuery. Treehouse is where I started out many years ago and think it is a great introduction to web development (Treehouse - front-end web development). That being said here are the most glaring issues...
Unique ids
id attributes must be unique per HTML document. As in, having id="leftleft" and then on another element in same document having id="leftleft" is invalid.
Missing closing bracket of function block }
HTML template strings
Honestly I don't know how you're able to read that HTML template string, but this is one of the issues front-end frameworks like React and Angular are meant to solve. Writing HTML templates like this will definitely introduce bugs and also drive you insane.
Instead or rewriting your whole program in React or Angular I would suggest using Template Literals and either using Webpack + babel to transpile your code to achieve browser support or for now just visit Babel repl and manually drop in your JS (with template literals) then replace with output code.
This is how the code would look after being transpiled through Babel, which would be supported in all browsers..
var count = 0;
adduser();
function adduser() {
$('#users').append(newUser(count));
count++;
}
function deluser(e) {
$(e.target).closest('.user-container').remove();
}
function newUser(count) {
var deleteButton = "\n <div>\n \n <div class=\"add delete-user\" data>\n <div style=\"position:relative;left:-4px;top:1px;\">-</div>\n </div>\n \n <br>\n </div>\n ";
return "\n <div class=\"user-container\">\n <div id=\"left\">\n <div class=\"fieldname\">\n user #".concat(count, " Name:\n </div>\n <div class=\"field\">\n <input id=\"user_name").concat(count, "\" name=\"user_name[]\" type=\"text\" /></input>\n </div>\n <div id=\"clear\"></div>\n </div>\n <div>\n <div class=\"fieldname\">\n user #").concat(count, " Age\n </div>\n <div class=\"field\">\n <input type=\"number\" id=\"user_age").concat(count, "\" name=\"user_age[]\" style=\"width:50px;\" min=\"0\"></input>\n </div>\n <div id=\"clear\"></div><br>\n </div>\n <div>\n \n <div class=\"field\" class=\"add\">\n <div style=\"position:relative;left:-4px;top:1px;\">add another user +</div>\n </div> \n \n <br>\n </div> \n ").concat(count > 0 ? deleteButton : "", "\n <div class=\"clear\">\n </div>\n </div>\n ");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="users"></div>
use something like this
$( '#users' ).empty();
You need to use following code
var no = $(".deluser"); // add class 'deluser' to each div
no.onclick = function(){
$('#users').empty();
};
I tried to illustrate your approach in another way, I hope it will help you.
var count = 0;
function addUser(i) {
var userBloc = '<li class="list-group-item" id="user'+i+'"> I am the user'+ i +
' <br><button class="btn btn-danger remove" data-count="'+i+'">Remove me</button><hr></li>';
return userBloc;
}
$('#add').click(function(){
$('#blocs').append(addUser(count));
$('#user'+count).fadeIn(activeRemove); //important to active remove event
count++;
});
function activeRemove(){
$.each($('button.remove'), function(i,item){
$(item).click(function(){
$('#user'+$(item).attr('data-count')).remove();
});
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="blocs" class="list-group"></div>
<button id="add">Add a another user</button>

Change image source attribute in string HTML and return string HTML again

I have html web page and i want to download this web page as pdf. So that i convert this web page to string, and i must sent to the service. Namely i have unchanging string html. I can't add indicator for split string html. When the html web page too large with base 64 string images, i must change this base 64 string with avatar image url (Because it is too large to send data with json). i have short html string with changing base 64 string and then i can send to the service side to download pdf. I have an HTML string (it looks like my real html string) see below:
var stringHTML =
"
<div id="myDiv">
<img src="abc" /></div>
<img src="abc" /></div>
<img src="abc" /></div>
<img src="abc" /></div>
</div>
";
I want to change image src attribute value to xyz. Namely I want to convert the HTML string to:
stringHTML =
"
<div id="myDiv">
<img src="xyz" /></div>
<img src="xyz" /></div>
<img src="xyz" /></div>
<img src="xyz" /></div>
</div>
";
How can change this source attribute values with return again string value ? Namely i must have string html after change operation..
Based off of the linked possible duplicate question, you would do something like this:
stringHTML = stringHTML.replace(/abc/g,"xyz");
or
stringHTML = stringHTML.replace(new RegExp("abc","g"),"xyz");
It's also worth noting that your current string is not valid. You'll either need to replace the opening and closing double-quotes (") with single-quotes (') or escape the double-quotes used inside the string. And, as Ivan mentioned in the comments, javascript cannot span lines without special allowances (escaping the newline, etc). You could define it like this, I think:
let stringHTML = ' +
<div id="myDiv"> +
<img src="abc" /></div> +
<img src="abc" /></div> +
<img src="abc" /></div> +
<img src="abc" /></div> +
</div>';
You could also create an array and join it immediately:
let stringHTML = [
'<div id="myDiv">',
'<img src="abc" /></div>',
'<img src="abc" /></div>',
'<img src="abc" /></div>',
'<img src="abc" /></div>',
'</div>'
].join('');
See this question for more on multiline string definition.

Jquery pass this.Text() as identifier

Basically im just trying to get the value of this.Text() and edit css of all class with that value.
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">First</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Second</span> phrase</p>
</div>
<div>
<img class="First" style="display:none">
<img class="Second" style="display:none">
<img class="Third" style="display:none">
<p><span class="firstWord">Third</span> phrase</p>
</div>
Im using this code to get the first word but im a bit lost on how to pass this.Text as indentifier. Im just trying to unhide an image with a class the same with the value of this.Text() :
$('.firstWord').each(function() {
fwtext = $(this).text();
$('#' $fwtext).css("display", "block");
});
The div and all tags inside it are dynamically generated and repeated so i cant simply go on editing them.
THANK YOU SO MUCH EVERYONE FOR HELPING.
This is wrong:
$('#' + $fwtext)
//-----^
Add a + for concatenation. Also since you are using a class and not an id, you must use . instead of #:
$('.' + $fwtext)
Your img tags have a class, not an id. So your jQuery selector should look like: $("." + fwtext). And yes - it will display necessary image only in corresponding div. jsFiddle for testing.
$(".firstWord").each(function () {
var fwtext = $(this).text();
var currentBlock = $(this).parents("div");
currentBlock.find("." + fwtext).show();
});
Remove the $ sign and add + in place of it
$('#'+ fwtext).css("display", "block");
based on your comment here is the edit
$('.firstWord').each(function() {
$('<div></div>').text($(this).text()).css("display", "block");
});

Can't pass parameters in HTML onClick function

Me and my teammates have an issue we haven't been able to solve and hope someone can help us.
We have 4 images on the top and we want to change the content of another div when we click on them.
This is the code of the JavaScript function which puts the 4 upper images and works well. The problem appears when we try to pass parameters from the onClick() function to our modificarDetailed(). (Scroll to the right to see the most important part of img)
function insertRecommended(parent,events) {
var hola = events[0].author;
parent.append('<div class="row">\
...
<div class="col-md-3 col-sm-6">\
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed('+events[1].nameEvent+','+events[1].category+','+events[1].author+','+events[1].dateInit+','+events[1].image+');">\
</div>\
...
</div>')
}
This is the function which adds the HTML code of a DetailedEvent. As you can see, we try to make it dynamic and change the content of the inputs
function insertDetailedEvent(parent,event) {
parent.append('<!-- Features Section -->\
<div class="row" > \
<form id="' + "detailedform" + '">\
<div class="col-lg-12">\
<h2 class="page-header"><input type="text" name="eventname" value="'+event.eventName+'"/></h2>\
</div>\
<div class="col-md-6">\
<ul>\
<li><strong>Categoría: </strong><input type="text" name="category" value="'+event.category+'"/></li>\
<li><strong>Creador: </strong><input type="text" name="author" value="'+event.author+'"/></li>\
<li><strong>Fecha de Inicio: </strong><input type="text" name="dateInit" value="'+event.dateInit+'"/></li>\
</ul>\
<p>'+event.description+'</p>\
</form>\
</div>\
<div class="col-md-4 .col-md-offset-4">\
<img name="eventImage" class="img-responsive" src="'+event.image+'" alt="">\
</div>\
</div>\
<!-- /.row -->')
}
After that, we have this to update the content of DetailedEvent
function init(parent){
listEvent("logon",function(events){
insertRecommended(parent,events);
insertDetailedEvent(parent,events[0]);
},function(){},function(){});
}
function modificarDetailed(eventName,category,author,dateInit,image){
var documento= $("#detailedform");
documento.find('input[name="eventname"]').val(eventName);
documento.find('input[name="category"]').val(category);
documento.find('input[name="author"]').val(author);
documento.find('input[name="dateInit"]').val(dateInit);
//documento.find('img[name="eventImage"]').src(image);
}
And this is how we call the init in the html main document
<script type="text/javascript">
$(document).ready(function() {
init($('#Content'));
});
</script>
Thanks in advance.
Finally we found the solution. We saw it yesterday searching on the net but we did it wrong so it didn't work at first.
It is necessary to use '\', so this is how it was:
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed('+events[1].nameEvent+','+events[1].category+','+events[1].author+','+events[1].dateInit+','+events[1].image+');">\
And this is how it must be done:
<img class="img-responsive img-portfolio img-hover" src="'+ events[1].image+'" alt="" onclick="modificarDetailed(\''+events[1].nameEvent+'\',\''+events[1].category+'\',\''+events[1].author+'\',\''+events[1].dateInit+'\',\''+events[1].image+'\',\''+events[1].description+'\');">
Thanks anyway to #Barmar and #yak613 for their try.

Categories

Resources