Admittedly not a js expert. - How can I remove the trailing <br> on the last element? Feel free to comment on the general approach and make comments or suggestions. Thanks!!
$(document).ready(function() {
$.getJSON("{% url "relationship_sidebar_ajax" app_label=app_label model=model object_id=object.id %}", function(data) {
var str = ""
for (var item in data) {
var itemData = data[item];
str += '<dt>' + item + '</dt>';
for (idata in itemData) {
str += '<dd>' + itemData[idata].href;
if (itemData[idata].is_owned) {
str += ' <i class="icon-lock"></i>';
}
str += ' ' + data[item][idata].add_href + '</dd>';
}
str += '<br />'
}
$('#relations').append(str)
});
})
Use an array to hold the lines, and then join them with <br/> at the end.
$(document).ready(function() {
$.getJSON("{% url "relationship_sidebar_ajax" app_label=app_label model=model object_id=object.id %}", function(data) {
var arr = []
for (var item in data) {
var itemData = data[item];
var str = '<dt>' + item + '</dt>';
for (idata in itemData) {
str += '<dd>' + itemData[idata].href;
if (itemData[idata].is_owned) {
str += ' <i class="icon-lock"></i>';
}
str += ' ' + data[item][idata].add_href + '</dd>';
}
arr.push(str);
}
$('#relations').append(arr.join('<br />'));
});
})
Well, the last five characters of your string will always be <br /> so you could always just append str.substring(0, str.length - 5). It might be preferrable to wrap the dt and subsequent dd elements in a div.
if you want to remove the br tag in the beigining of string this would be helpful.
var str = "<br />Some string";
var regex = /^(<br\/>|<br \/>)/;
alert(str.replace(regex,""));
Related
var swTitle = {};
var favorite = [];
$.each($("input[name='Title']:checked"), function() {
favorite.push($(this).val());
console.log($("input[name='Title']:checked"));
});
swTitle.domain = favorite;
var List = {};
for (var m = 0; m < favorite.length; m++) {
var swTitleObj = [];
$.each($('input[name="' + swTitle.domain[m] + '"]:checked'), function() {
console.log(swTitle.domain[m]);
swTitleObj.push($(this).attr("class"));
console.log(swTitleObj);
});
List[swTitle.domain[m]] = swTitleObj;
}
var swSkillData = " ";
$.each(List, function(key, value) {
console.log(key + ":" + value);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Output will be like:
Fruits:Apple,Banana,Orange,Grapes
I want my output be like:
Fruits:Apple,Banana,Orange & Grapes
I have an array of keys and values separated by commas. I want to insert "and" and remove the comma before the last checked element. Kindly help me out with this issue.
I think you can reduce your code, with an option of adding and before the last element like,
var inputs=$("input[name='Title']:checked"),
len=inputs.length,
swSkillData='',
counter=0;// to get the last one
$.each(inputs, function() {
sep=' , '; // add comma as separator
if(counter++==len-1){ // if last element then add and
sep =' and ';
}
swSkillData += '<li>' + this.value + // get value
' ' + ':' + ' ' +
this.className + // get classname
sep + // adding separator here
'</li>';
});
Updated, with and example of changing , to &
$.each(List, function(key, value) {
console.log(key + ":" + value);
var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
swSkillData += '<li>' + key + ' ' + ':' + ' ' + value + '</li>';
});
Snippet
var value ='Apple,Banana,Orange,Grapes';var pos = value.lastIndexOf(',');// get last comma index
value = value.substring(0,pos)+' & '+value.substring(pos+1);
console.log(value);
Here is an easy and customizable form of doing it.
(SOLUTION IS GENERIC)
$(document).ready(function() {
var ara = ['Apple','Banana','Orange','Grapes'];
displayAra(ara);
function displayAra(x) {
var str = '';
for (var i = 0; i < x.length; i++) {
if (i + 1 == x.length) {
str = str.split('');
str.pop();
str = str.join('');
str += ' and ' + x[i];
console.log(str);
$('.displayAra').text(str);
break;
}
str += x[i] + ',';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Fruits : <span class="displayAra"></span>
str = str.replace(/,(?=[^,]*$)/, 'and')
I solved my own issue. I replaced my last comma with "and" using the above regex. Thanks to Regex!!!
I have tried my best to debug thoroughly but i just can't figure out why this code does not work.. I know its my fault but i can't find the bug. Please help me guys
https://codepen.io/blaze4dem/pen/zZmqKa
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options){
var radioList = options.fn();
radioList = radioList.trim().split("\n");
var output = "";
for(var val in radioList){
var item = radioList(val).trim();
output += '<input type="radio" name="'+ name +'" value="'+ item +'"> '+ item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innaHTML += tempdata;
I see 3 issues in the code.
for in is best to iterate over objects. In this case when you split the output is an array. User for loop instead.
You have a typo, when you are replacing the element. Supposed to be innerHTML
radioList(val) --> () will invoke a method, where as you want to access a property. So it has to be [].
You can try this approach. But I strongly feel that you should be using a different delimiter instead of \n
var docs = document.getElementById('pag_temp').innerHTML;
var template = Handlebars.compile(docs);
Handlebars.registerHelper("makeradio", function(name, options) {
debugger;
var radioList = options.fn();
var hasSpaces = radioList.indexOf(' ') > -1;
var hasNewLines = radioList.indexOf('\n') > -1;
if (hasNewLines) {
radioList = radioList.trim().split("\n");
} else if (hasSpaces) {
radioList = radioList.trim().split(" ");
}
var output = "";
// for in is best to iterate over objects.
// use for loop instead
for (var i = 0; i < radioList.length; i++) {
var item = radioList[i].trim();
output += '<input type="radio" name="' + name + '" value="' + item + '"> ' + item + '<br/>';
};
return output;
});
var tempdata = template({});
document.getElementById('dynamic').innerHTML += tempdata;
Check Fiddle
I have a string and I want change some words.
I write next function. If a word to change is alone in my string, this work normal. But if that words more then one it change only last.
<div class="container">
<div id="main-arr">How are you my friend?</div>
<div id="main-arr__last"></div>
</div>
$(document).ready(function() {
var sometext = $('#main-arr').text();
var someArr = sometext.split(' ');
for ( var i = 0; i < someArr.length; i++ ) {
if ( someArr[i] === 'you' || someArr[i] === 'he' || someArr[i] === 'she' ) {
var newArr1 = someArr.slice(0, i);
var newArr2 = someArr.slice(i + 1, someArr.length);
newArr1 = newArr1.join(' ');
newArr2 = newArr2.join(' ');
var word = 'error!';
console.log(newArr1);
console.log(newArr2);
$('#main-arr__last').html(newArr1 + '<span class="red">' + ' ' + word + ' ' + '</span>' + newArr2);
}
}
});
The function is not changing only the last word. The problem is that every time you replace a word you replace the html in #main-arr__last too.
Here is a better solution:
$(document).ready(function() {
var sometext = $('#main-arr').text();
sometext = replaceAll(sometext, ' you ', ' error! ');
sometext = replaceAll(sometext, ' he ', ' error! ');
sometext = replaceAll(sometext, ' she ', ' error! ');
var someHtml = toHtml(sometext, 'red');
$('#main-arr__last').html(someHtml);
});
function replaceAll(str, search, replacement){
return str.replace(new RegExp(search, 'g'), replacement);
}
function toHtml(str, clazz){
return replaceAll(str, 'error!', '<span class="' + clazz + '">error!</span>');
}
First we implement a function replaceAll to replace all occurrence of a word in a text, after that we have the text with all the words, you, he and she, in our case, replaced by error!.
Then we implemented the function toHtml to involve all 'error!' word in a span with a determined class passed as a parameter.
In jquery, I am trying to get the text from a textarea tag, with the new lines as \n and not br tags. The problem is if I select it and get its val, the firefox debugger does not even show the \n or br. If I alert it, then I see there is two lines, but then if I insert it into the DOM, it removes all the new lines. I want it to keep its new lines.
I get it like this:
var handleSend = function(thread_id) {
var user = GLOBAL_DATA.user;
$(context).find("#message-form").unbind('submit').submit(function() {
var field = $(this).find("textarea");
runAJAXSerial($(this).serialize(), {
page : 'message/setmessage',
id : user['id'],
thread_id : thread_id
}, function(response) {
var user = GLOBAL_DATA.user;
var obj = {
user_id : user['id'],
message : field[0].value.replace(/<br\s*\/?>/mg,"\n"),
date_sent : getDate() + ' ' + getTime()
};
alert(obj.message);
cleanResponse(obj);
field.val("").focus();
displayMessages([obj], true);
}, function(data,status,xhr) {
});
return false;
});
};
function cleanResponse(response) {
if (Object.prototype.toString.call( response ) === '[object Array]') {
var i = 0, l = response.length;
for (i=0; i<l; i+=1) {
response[i] = cleanResponse(response[i]);
}
} else if (Object.prototype.toString.call( response ) === '[object Object]') {
for (var property in response) {
if (response.hasOwnProperty(property)) {
response[property] = cleanResponse(response[property]);
}
}
} else {
response = escapeHTML(response);
}
return response;
}
function escapeHTML(str) {
return $("<p/>").text(str).html();
}
var displayMessages = function(response, onBottom) {
var user = GLOBAL_DATA.user, i=0, l=response.length, acc = '';
for(i=0; i<l; i+=1) {
var obj = response[i];
var acc_temp = "";
acc_temp += '<div class="message ' + (obj['user_id']==user['id'] ? 'message-right' : 'message-left') + '">';
acc_temp += '<img src="' + getImage(obj['user_id']) + '" align="right" class="message-image" />';
acc_temp += '<div>' + Autolinker.link(obj['message']) + '</div>';
acc_temp += '<br/>';
if (obj['user_id']!=user['id']) {
acc_temp += '<div class="message-details">' + obj['first_name'] + ' ' + obj['last_name'] + '</div>';
}
acc_temp += '<div class="message-details">' + obj['date_sent'] + '</div>';
acc_temp += '</div>';
acc = acc_temp + acc;
}
addMessage(acc, onBottom);
};
var addMessage = function(html, onBottom) {
var list = $(context).find("#message-list");
if (onBottom) {
list.append(html);
scrollBot();
} else {
list.prepend(html);
}
};
displayMessages inserts the text into the DOM.
cleanResponse encodes the text so that the user can't execute scripts.
Does anyone know whats wrong?
Thanks
New lines in the DOM are treated like any other whitespace. You are getting the expected behaviour of adding the new lines.
If you want an new line to be rendered then you need to use a <br> element or modify the white-space CSS property.
Trying to write some html to a div in 001, 002, 003 style format but I can't get it to work.
Here's the code:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + String.format("%03d", i) + "<br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
When I hopefully get it to work, I intend to load some images to the div like so:
function loadpics(x, url) {
var txt, i;
txt = "";
for(i = 1; i < x; i++) {
txt = txt + "<img src=\"" + url + "/t/" + String.format("%03d", i) + ".jpg\"></img><br/>";
}
document.getElementById("myDiv").innerHTML = txt;
}
Can't get the string formatting to work though. Not exactly sure what I'm doing wrong.
If anyone can put me straight it would be most appreciated.
Try using pad() instead of String.format().
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
Add this to your page
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
And replace txt=txt... with this
txt += "<img src='" + url + "/t/" + pad(i,3) + ".jpg'></img><br/>";
Also have a look at this topic