how to add space to the end of a string in javascript? - javascript

I have the following string.
<span class="add">foo bar1</span>
Now I have to check the last character in this string.If the last character in this string is 1,add a space to the end of the string and move the cursor out of the span tag, Else if the last character in this string is not 1,just move the cursor out of the span and do not add a space.
So can anyone help me how it can be done in javascript.This will happen when I click a button 'Done'. I am quite new to stackoverflow.So if I made q mistake in the question,please forgive me.
Thanks

Is this what you are looking for? This will loop through all elements with the tag
You should add an ID to the tag in HTML
<span class="add" id="test">foo bar1</span>
<br /><br />
<button onclick="addSpace()">Button</button>
Then use the following JS:
function addSpace() {
var testElem = document.getElementById("test");
var contents = testElem.innerHTML;
if (contents.slice(-1) === "1") {
testElem.innerHTML=testElem.innerHTML + "----";
}
}
I made a fiddle
http://jsfiddle.net/nJeyz/2/

You can't move the mouse of the user, that's impossible. However, you can revert focus to an arbitrary element instead.
<button onclick="mine()">Click</button>
<input id="testdiv">
<span id="test">foo bar1</span>
<script>
function mine() {
$string = document.getElementById("test").innerHTML;
if ($string.substring($string.length-1) == "1")
document.getElementById("test").innerHTML+= " ";
document.getElementById('testdiv').focus();
}
</script>

Related

Error with Javascript TypeError code, variable undefined

I am trying to get the element with the ID 1a, 2a, 3a etc. according to whenever the function is run.
It then compares that elements value (using jQuery) with the value of the input where the function is wrong
It brings up an error saying:
TypeError: var1.toUpperCase is not a function. (in 'var2.toUpperCase()','var1.toUpperCase' is undefined)
Any help would be appreciated.
Thanks
(UPDATE usually there would be text in questionNumber like: 1, 2, 3 etc every time the another function is run.)
EDIT: Every time a different function is run, questionNumber is increased by 1. I save questionNumber's text in a variable called word. I then add the letter a to that variable. Then, I get the element that has ID of the variable word, then compare it's contents to the value of the input, but the comparison is uppercase to avoid problems. If they are equal, the input is replaced with a div with green text. Hope this makes it clearer.
function textVerify(item) {
var word= document.getElementById(($('#questionNumber').text()+'a'));
if (item.value.toUpperCase() === word.toUpperCase()){
item.style.color = "green";
$( item ).replaceWith( "<div style='color:green;'>"+word+"</div>" );
main()
} else {
item.style.color = "black";
}
<span class="ihide" id="questionNumber"></span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
The var word is p tag, so you need to get the inner text of it and compare it with the input text. Also, when replacing it, access the text() property of it. See below. main() is commented out here, but you can keep as per the need.
function textVerify(item) {
var word = document.getElementById(($('#questionNumber').text() + 'a'));
if (item.value.toUpperCase() === $(word).text().toUpperCase()) {
item.style.color = "green";
$(item).replaceWith("<div style='color:green;'>" + $(word).text() + "</div>");
//main()
} else {
item.style.color = "black";
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span class="ihide" id="questionNumber">1</span>
<p id="1a" class="ihide">Seven</p>
<input id="1" name="Seven" type="text" value="" onkeyup="textVerify(this)" autofocus="">
In your code ($('#questionNumber').text()+'a') this part returns just 'a', as text of the id questionNumber is nothing.
And in your HTML there is no such id. I think you need to make this changes to your HTML code:
<span class="ihide" id="questionNumber">1</span>
This should work.
EDIT: Also, can you please share the JS code associated with 'item', there can be an error in that part too.

Replacing [b][/b] to apply BOLD text on a DIV

On my Ionic App I have a Textarea where the user can select a text and with button [BOLD]
add [b] [/b] around the selection.
How can I apply BOLD formating, replacing the [b] [/b] on the output text?
Thats my code. And here's the JsFiddle
<textarea id="TheTextInput" rows="5"></textarea>
<input type="button" id="TheButton" value="click" />
<input type="button" id="bold" value="BOLD" />
<pre id="TheOutput"></pre>
$(document).ready(function () {
$('#TheButton').click(PutTextIntoDiv);
});
function PutTextIntoDiv() {
var TheText = encodeURIComponent($('#TheTextInput').val());
$('#TheOutput').text(decodeURIComponent(TheText));
}
$( "#bold" ).click(function() {
var textArea = document.getElementById("TheTextInput");
if (typeof(textArea.selectionStart) != "undefined") {
var begin = textArea.value.substr(0, textArea.selectionStart);
var selection = textArea.value.substr(textArea.selectionStart, textArea.selectionEnd - textArea.selectionStart);
var end = textArea.value.substr(textArea.selectionEnd);
textArea.value = begin + '[b]' + selection + '[/b]' + end;
}
});
Thanks for your help!!
*Its not duplicate from Is it possible to display bold and non-bold text in a textarea?
Cause I don't want format the text inside the textarea, but the OUTPUT text.
Consider PutTextIntoDiv() replacing with:
function PutTextIntoDiv() {
$('#TheOutput').html($('#TheTextInput').val().replace(/\[b\]/g, '<b>').replace(/\[\/b\]/g, '</b>'));
}
The <pre> in your JSFiddle should render <b> fine.
You can do a RegEx replace to convert the "BBCode" tags into html tags using .replace(/\[b\](.*)\[\/b\]/g, '<b>$1</b>'). Additionally, jQuery's .text() automatically encodes HTML entities, so you will not be able to add stylized text, so you should be using .html() instead. Overall, your code should be:
function PutTextIntoDiv() {
var TheText = encodeURIComponent($('#TheTextInput').val());
$('#TheOutput').html(decodeURIComponent(TheText).replace(/\[b\](.*?)\[\/b\]/g, '<b>$1</b>'));
}
I'm not sure what the purpose of encoding and immediately decoding uri components is, but I tried to keep as much as I can untouched. Here's an updated fiddle: http://jsfiddle.net/TheQueue841/62karfm1/

Replacing a string from one class to another with jQuery

I'm trying to figure out how to replace a string from class to another. I have a H1 tag on the page and the idea is that when it's visible the user can place some text into a text box to override the H1 tag (header class) and the corresponding menu item (thing class). Currently I can get the H1 tag to replace but the I can't figure out how to replace the string in the menu. All of my experiments have lead to all of the strings being replaced.
<div class='thing'>One</div>
<div class='thing'>Two</div>
<div class='thing'>Three</div>
<div class='thing'>Four</div>
<div class='thing'>Five</div>
<h1 class='header'>One</h1>
<input type="text" name="textbox" id="textbox" value="">
Some of my JavaScript for replacing the H1 tag:
var userInput = $('#textbox').val();
$('.header:visible').text(userInput);
Any help would be greatly appreciated.
Just loop through menu items and search your header value:
var userInput = $('#textbox').val(),
headerValue = $('h1').text();
$('.thing').each(function() {
if ($(this).val() == headerValue) {
$(this).val(userInput);
}
});
Got it working using merezha's code however I replaced .val with .text
var userInput = $('#textbox').val(),
headerValue = $('h1').text();
$('.thing').each(function() {
if ($(this).text() == headerValue) {
$(this).text(userInput);
}
});
Thanks everyone!

Replace input value .val() with jQuery

So basically here is my jsFiddle - http://jsfiddle.net/CmNFu/ .
And code also here -
HTML -
<b style="float: left; margin-right: 10px;">category 1</b><input type="checkbox" value="category1" style="float: left;" class="portfolio-category" /><br />
<b style="float: left; margin-right: 10px;">category 2</b><input type="checkbox" value="category2" style="float: left;" class="portfolio-category" /><br />
<br />
<br />
<input type="text" name="categories" id="portfolio-categories" />​
jQuery -
jQuery(document).ready(function() {
jQuery(".portfolio-category").click(function() {
if(jQuery(this).is(":checked")) {
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+" "+jQuery(this).val());
}
else {
var portfolioCategories = jQuery("#portfolio-categories").val();
alert("before + "+portfolioCategories);
var currentElement = jQuery(this).val()+" ";
alert(currentElement);
portfolioCategories = portfolioCategories.replace(currentElement, "");
alert(portfolioCategories);
}
});
});
​Well basically what I would like to achieve is, when user checks the checkbox, the value automatically adds inside input field (Done, it's working, whooray!), but the problem is when it unchecks the checkbox, the value should be removed from input box (the problem starts here), it doesn't remove anything. You can see I tried assigning val() function to variables, but also without success. Check my example on jsFiddle to see it live.
Any suggestions? I guess replace() is not working for val(), is it?
So, is there any other suggestions?
I'd do this:
jQuery(document).ready(function() {
jQuery(".portfolio-category").on('change', function() {
var string = "";
$('input[type="checkbox"]').each(function() {
var space = string.length>0?' ':'';
string += this.checked?space+this.value:'';
});
$("#portfolio-categories").val(string);
});
});
FIDDLE
You have quite the issue with spaces in that input box. but we'll get to that in a moment.
first, this will kind of work (if it weren't for the spaces problem):
add this line before the last alert:
jQuery("#portfolio-categories").val(portfolioCategories);
this will work, but not always, as the last element you append doesn't have a space after it.
but if you change the 4th line to this:
jQuery("#portfolio-categories").val(jQuery("#portfolio-categories").val()+jQuery(this).val()+" ");
it will work, as it adds the space after each element, instead of before.
http://jsfiddle.net/CmNFu/5/
your issue was that you changed the values in the variable: portfolioCategories, but you haven't updated the input itself. (notice, changing the value of a string, doesn't change the value of the input it originally came from)
What you need is to insert back the string portfolioCategories into the input. Also the spaces are creating a lot of problems. You could use $.trim(str) to remove any leading and trailing spaces from a string.
Have updated your fiddle with a solution that works.
http://jsfiddle.net/CmNFu/11/
Hope this helps.

How can I make this feature faster in Javascript?

I have created a highlight feature that will highlight anything contained in a <p> red using a user specified keyword. When the submit button is clicked Javascript/jQuery pull the keyword from the input field and compare it to any lines that conain it and then highlight those lines red. It works great... but its slow. Is there another way to do this that is faster when working with over 1000 lines of <p>?
HTML
Keyword: <input type="text" id="highlight_box" class="text_box" value="--Text--" />
<input type="button" id="highlight" value="Highlight" />
<!--Print area for the Access log-->
<div id="access_content" class="tabbed-content">
<ul id="access-keywords-row" class="keywords-row">
<!--When a user submits a keyword it is placed as a tag here so it can be deleted later-->
</ul><br /><br />
<div id="access_log_print" class="print-area">
<p>Some Content</p>
<p>Some more content</p>
<!--Most of the time this could contain 1000's of lines-->
</div>
</div>
JavaScript
//add highlight and tag
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
$("#access-keywords-row").append("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
$("#access_log_print p:containsi(" + id + ")").css("color","red"); }
});
//remove highlight and tag
$(".keywords-row").on("click", ".delete_filter",
function() {
var val = $(this).val();
//remove element from HTML
$(this).parent().remove();
$("#access_log_print p:containsi(" + val + ")").css("color","black");
});
Adding color, red means adding the style attribute to each p, I think this can be improved adding a class:
p.highlight {
color:red;
}
And replacing
$("#access_log_print p:contains(" + id + ")").css("color","red");
by
$("#access_log_print p:contains(" + id + ")").addClass('highlight');
This probably speeds a little bit the process
I've written a small solution using jQuery's contains() method. Obviously you can throw in some string validation.
http://jsfiddle.net/W2CZB/
Try defining a css class, e.g.:
.red{background-color:#f00;}
and then instead of adding to each "style=background-color:#f00;" you will just .addClass("red");
just less code to put, but still jQuery will have to go thru all lines and if it is a lot then I guess it depends on your machine speed ;)
The following solution will probably increase performance at the cost of space. It works by building a word mapping of the lines and accessing directly to add or remove the highlight class. This solution also keeps a count of the number of times a filter hit that line so it stays highlighted until the last filter is removed. I have tested with a few lines, I am not sure how will it perform with 1000s. You tell us :)
$(function(){
buildIndex();
$("#highlight").click(
function(){
var id = $("#highlight_box").val();
if(id == "--Text--" || id == ""){
alert("Please enter text before highlighting.");
}else{
var filter = $("<li><img src=\"images/delete.png\" class=\"delete_filter\" value=\"" + id + "\" /> " + id + " </li>");
filter.click(function(){
$(this).remove();
removeHighlight(id)
});
$("#access-keywords-row").append(filter);
$.each(index[id], function(i,line){
if (line.highlightCount)
line.highlightCount++;
else {
line.addClass('highlight')
line.highlightCount=1;
}
});
}
});
function removeHighlight(id) {
$.each(index[id], function(i,line){
line.highlightCount--;
if (line.highlightCount<1)
line.removeClass('highlight')
});
};
});
var index={};
function buildIndex(){
$("#access_log_print p").each(function(i) {
var line = $(this)
var words = line.text().split(/\W+/);
$.each(words, function(i,word){
if (!index[word]) { index[word]=[]; }
index[word].push(line);
});
});
}

Categories