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>`
Related
So I am currently trying to find out how to select text between two characters(for the example I will use a slash / )
Here is what I have so far.
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var secondStartingPoint, startPointOne, startPointTwo;
if (text.indexOf("/", 0) !== -1) {
//I did -1 because indexOf returns -1 if nothing is found.
/*Also, the second argument in indexOf() acts as my starting
point for searching.*/
secondStartingPoint = text.indexOf("/") + 1;
startPointOne = text.indexOf("/") + 1;
if (text.indexOf("/", secondStartingPoint) !== -1) {
startPointTwo = text.indexOf("", secondStartingPoint) + 1;
var selectedText = slice(startPointOne, startPointTwo);
$("body").append("<p>" + selectedText + "</p>");
//but nothing happens.
}
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>/can I select and duplicate this?/</p>
</body>
</html>
But it doesn't do anything.
It could be achieved simply by using a regex like :
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
function startWhenLoaded() {
var text = $("p").text();
var extracted = text.match(/\/(.*)\//).pop();
alert('The extracted text is :'+extracted);
}
</script>
</head>
<body onload="startWhenLoaded()">
<p>Some text here in the start /can I select and duplicate this?/ Some extra text at the end</p>
</body>
</html>
Regex is simplest and easiest way to get your solution.
use exec() function to get text between '/';
console.log(/^\/(.*)\/$/.exec('/some text, /other example//'))
i have a code that is supposed to read from a html file, split it into an array and display parts of that array, but when going though with alert, i found that $.get is not actually getting the file
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
var info = "";
$.get("../Read_Test/text.html", function(data) {
SomeFunction(data);
});
alert(info);
var array = info.split("§n");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML = people[i] + "<br>";
}
}
function SomeFunction(data) {
var info = data;
}
</script>
</body>
</html>
the directories are on a server and go like so:
Sublinks->Read_Test->This_File.html,text.html
The objective of this is that a file would have something along the lines of "a§nb1,b2,b3,§n" and the script would split it via "§n" then get "array[1]" and split that via ",". lastly it displays each part of that newly created array on a new line, so a file with "a§nb1,b2,b3,§n" would result in:
b1
b2
b3
Please help
Ajax is asynchronous, it make request and immediately call the next instruction and not wait for the response from the ajax request. so you will need to process inside of $.get. success event.
I have changed delimiter character to ¥. change same in text.html. problem was you have not mentioned character set to utf8 and due to this it could not recognized the special character and subsequently not able to split the string. i have aldo document type to HTML5.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myfunction()">update</button>
<div id="div1"></div>
<script>
function myfunction() {
$.get("../Read_Test/text.html", function(data) {
var info = data;
var array = info.split("¥");
var people = array[1].split(",");
for (var i = 0; i < people.length; i++) {
document.getElementById("div1").innerHTML += people[i] + "<br>";
}
});
}
</script>
</body>
</html>
When using the code below I am unable to add the HTML string to the innerHTML of the target HTMLElement. What am I doing wrong? Is there a better way to do this?
<html>
<head>
<title>Add HTML input with jQuery</title>
<!--
* This code is meant to include the jQuery library v.1.9.1
* from Google API
-->
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js' type='text/javascript'></script>
<script>
$('document').ready(function(){
$('#add').click(function(){
var src = $('#src'); // alert(src);
var trgt = $('#src'); // alert(trgt);
var x = null;
var child = null;
var str = null;
if(null != src.val()){
alert(1);
x = trgt.children().length;
str = '<input type="text" name="array[]" id="index' + x + '" value="' + src.val() + '" />';
trgt.html().append(str);
src.val() = null;
}else{
alert('src value is emppty');
}
});
});
</script>
</head>
<body>
<div id="box">
<label></label> <input type="text" name="src" id="src" value="" /> <button id="add">+</button>
<div id="trgt">
</div>
</div>
</body>
</html>
var trgt = $('#src'); ... Your source and target selectors are the same.
This var trgt = $('#trgt') is not the only problem I noticed.
There is trgt.html().append(str); which should be trgt.append(str);.
And then src.val() = null;, are you trying to reset the <input> value? You can simply do it with src.val('');
See this jsfiddle.
i am using innerHTML to add text boxes dynamically. The code sample is as follows:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
document.getElementById("y").innerHTML += tag;
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html
Are there any ways to add text boxes dynamically without losing values of previous text box when a new text box is added?
Similar question has been posted, but there are no answers :(
What if I want to add textbox in this situation:
function add() {
var element='<li class="ie7fix" style="width:620px;"><div class="m_elementwrapper" style="float:left;"><label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4"><span><span class="pspan arial" style="text-align:right;font-size:14px;"><span class="ispan" xml:space="preserve"></span></span></span></label><div style="float:left;width:475px;" class="m_elementwrapper"><input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent"><div class="fielderror"></div></div></div><div style="clear:both;font-size:0;"></div></li>';
document.getElementById("addskills").innerHTML += element;
i++;
}
Yes, through DOM Manipulation:
function add() {
var tag = document.createElement('input'); // Create a `input` element,
tag.setAttribute('type', 'text'); // Set it's `type` attribute,
tag.setAttribute('name', i); // Set it's `name` attribute,
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(tag); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
This doesn't trigger the browser's DOM parser like a innerHTML does, leaving everything intact.
(innerHTML forces the browser to re-parse the entire DOM, because anything could be added with innerHTML, so the browser can't predict anything, in contrast to adding a node to a element.)
Now, to add this:
<li class="ie7fix" style="width:620px;">
<div class="m_elementwrapper" style="float:left;">
<label class="fieldlabel" style="width:106px;float:left;padding-top:3px;" for="p1f4">
<span>
<span class="pspan arial" style="text-align:right;font-size:14px;">
<span class="ispan" xml:space="preserve">
</span>
</span>
</span>
</label>
<div style="float:left;width:475px;" class="m_elementwrapper">
<input type="text" style="font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;" name="' + i + '" class="fieldcontent">
<div class="fielderror">
</div>
</div>
</div>
<div style="clear:both;font-size:0;">
</div>
</li>
You'll need:
function add() {
// Create elements
var d1 = c('div'), s1 = c('span'), ip = c('input'),
d2 = c('div'), s2 = c('span'), li = c('li'),
d3 = c('div'), s3 = c('span'), la = c('label'),
d4 = c('div');
// You can "chain" `appendChild`.
// `li.appendChild(d1).appendChild(la);` is the same as `li.appendChild(d1); d1.appendChild(la);`
li.appendChild(d1).appendChild(la).appendChild(s1).appendChild(s2).appendChild(s3);
d1.appendChild(d2).appendChild(ip);
d2.appendChild(d3);
li.appendChild(d4);
setAttributes(
[li, d1, la, s2, s3, d2, ip, d3, d4],
[
{'class':"ie7fix", 'style':"width:620px;" },
{'class':"m_elementwrapper", 'style':"float:left;" },
{'class':"fieldlabel", 'style':"width:106px;float:left;padding-top:3px;", 'for':"p1f4" },
{'class':"pspan arial", 'style':"text-align:right;font-size:14px;" },
{'class':"ispan", 'xml:space':"preserve" },
{'class':"m_elementwrapper", 'style':"float:left;width:475px;" },
{'class':"fieldcontent", 'type':"text", 'style':"font-family:Arial, Helvetica, sans-serif;font-size:14px;width:244px;max-width:244px;", 'name':''+i},
{'class':"fielderror" },
{'style':"clear:both;font-size:0;" }
]
);
var br = document.createElement('br'); // Create a `br` element,
var y = document.getElementById("y"); // "Get" the `y` element,
y.appendChild(li); // Append the input to `y`,
y.appendChild(br); // Append the br to `y`.
i++;
}
// Apply a array of attributes objects {key:value,key:value} to a array of DOM elements.
function setAttributes(elements, attributes){
var el = elements.length,
al = attributes.length;
if(el === al){
for(var n = 0; n < el; n++){
var e = elements[n],
a = attributes[n];
for(var key in a){
e.setAttribute(key, a[key]);
}
}
}else{
console.error("Elements length " + el + " does not match Attributes length " + al);
}
}
// Alias for shorter code.
function c(type){
return document.createElement(type);
};
use jquery library
<html>
<head>
<script src='jquery.js' type="text/javascript"></script>
<script type="text/javascript" >
var i=0;
function add()
{
var tag = "<input type='text' name='" + i + "' /> <br/>";
var div_content=$('#y').append(tag);
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
I've got round this before by reading all of the values into an array before replacing the innerHTML and then writing them back again afterwards. This way you can write whatever you like into the div. Following works on all browsers that I have tried:
<html>
<head>
<script type="text/javascript" >
var i=0;
function add() {
if(i>0) {
values=new Array();
for(z=0;z<i;z++) {
values.push(document.getElementById(z).value);
}
}
var tag = '<input type="text" name="' + i + '" id="' + i + '" /> <br/>';
document.getElementById("y").innerHTML += tag;
if(i>0) {
for(z=0;z<i;z++) {
document.getElementById(z).value=values[z];
}
}
i++;
}
</script>
</head>
<body>
<input type="button" id="x" value="Add" onclick="add();" />
<div id="y"></div>
</body>
</html>
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);
});
});