div search form with formatting - javascript

I am trying to create a syntax highlighted search field, where certain items are a particular color, bold, underline, etc. when I type. As I type, I would like the word in to become bold. This works with what I currently have, but when in is typed the cursor goes to the beginning of the div, and you can't type anything after the word in either. What can I do to fix this? You can see the jsfiddle here.
The JavaScript:
$(document).on("keyup", "#q", function(){
var val = $(this).text();
val = val.replace(/\sin\s/ig, " <b>in</b> ");
$(this).html(val);
});
The HTML
<div id="q" name="q" class="form-control input-lg" contenteditable="true"></div>

With the rangy library I was able to accomplish this like this:
$(document).on("keyup", "#q", function(){
var savedSel = rangy.saveSelection();
var val = $(this).html();
val = val.replace(/\sin\s/ig, " <b>in</b> ");
$(this).html(val);
rangy.restoreSelection(savedSel);
});

Related

How to automatically change a specific text value with an input value?

What I'm trying to achieve is that when I'm entering an input value, the specific number of a textarea's value would replaced too according to the input value.
F.e: If I would enter into the input value a number 4, textarea's specific value (in this case a number) would be 4 too. If I would delete a value from the input, the value would be deleted from textarea too.
As you can see in the snippet, it works bad. It changes a value just one time. After that, 'text-areas' value isn't changing.
Could someone help me with that? Thank you for your time
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var specificString = '4';
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
There are a couple of issues with your code. The first is that the specificString value is being reassigned each time you do a keyup, so you need to set the default outside of the event handler. But also, if you delete the value, it will have no way of finding it and will prepend it to the start.
I'd personally recommend using a template based approach, rather than storing the previous value:
var specificString = '[numRows]';
var recommendationText = $('.textarea').val();
$('.text1').keyup(function() {
var numRows = $(this).val();
if (isNaN(parseFloat(numRows)) || !isFinite(numRows) || numRows.length < 1) {
numRows = 0;
}
var str = recommendationText.replace(specificString, numRows);
$('.textarea').val(str);
}).keyup();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1" value="4">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of [numRows] rows.
</textarea>
This could use a proper templating language like Handlebars or Underscore.js templates, but that is too opinion-based to include in my answer.
Declare and initialize specificString outside of keyup() event.Otherwise your value for specificString will be always 4.
var specificString = '4';
$('.text1').keyup(function() {
var recommendationText = $('.textarea');
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
});
Well your issue is you replace the string so next time you look for the 4 it is not there. Reason why is you redefine specificString inside of the loop so it is always 4 and not what the user last typed. So if you move it outside it will work ("sort of")
Your design will fail if the user enters in something that matches another word. EG This, it will replace the first occurrence, not the string you want to replace. Or if you delete the string, you will not have any match.
So what can you do? I would use a data attribute with the original and use that. And I would make some sort of "template" so you know what you are replacing and do not replace another part of the string with the replacement when user matches text.
$('.text1').keyup(function() {
var ta = $('.textarea')
var specificString = /\{4\}/;
var entry = $(this).val() || "4";
var str = ta.data("text").replace(specificString, entry);
ta.val(str);
}).trigger("keyup");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50" data-text="This is a textarea of {4} rows.">
</textarea>
In your way your code would work. Just change your code like this..! There are some logical issues in your code. Initiate the value of specificString outside the keyup() method to get first 4 and then then the value of textbox.
var recommendationText = $('.textarea');
var specificString = recommendationText.val().match(/\d+/);
$('.text1').keyup(function() {
if($(this).val() != '' && $.isNumeric($(this).val())) {
var str = $('.textarea').val().replace(specificString, $(this).val());
recommendationText.val(str);
specificString = $(this).val();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="text1">
<textarea rows="4" class="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>
Solution is much easier than you might expect.
Note: The $ in ${inputVal} is not jquery, its part of template literals. Don't get confused there.
document.getElementById('text1').onkeyup = changeTextArea;
function changeTextArea() {
let inputVal = document.getElementById('text1').value;
let text = `This is a textArea of ${inputVal} rows`;
document.getElementById("textarea").value = text;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="text1">
<textarea rows="4" id="textarea" cols="50">
This is a textarea of 4 rows.
</textarea>

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/

Copy from textarea to anther textarea but the value of the second textarea should not change

I have two textareas. I am copying data from one to another but if I change data in the first textarea then data in the second textarea is also changed which is obvious.
My requirement is like this: Suppose I have written "country" and it has been pasted to the second textarea. Now if I replace "country" with "anyother" then in the second textarea "country" should not be replaced. If I write something in the first textarea which is new(not replacement) then only that data will be pasted.
Is it possible to do?
My code till now:
function showRelated(e) {
//$('src2').html($('src1').html());
$('#src2').val( $('#src1').val() );
}
<textarea name="source" id="src1" cols="150" rows="20" onkeyup="showRelated(event)"></textarea>
<textarea name="source2" id="src2" cols="150" rows="20"></textarea>
the second text area is hidden from user.whatever the user writes will be copied to second textarea and will be transliterate.The requirement is like this if the user replace some data then also it should not effect the data which he already entered.that is why i need to maintain a copy without using database.
ok it seems this is what you want:
HTML:
<textarea id="src1"></textarea>
<textarea id="src2"></textarea>
JS:
$("#src1").keyup(function() {
var src1_val = $(this).val();
var src2_val = $("#src2").val();
var new_string = src2_val + src1_val;
$("#src2").val(new_string);
});
$('#one').on('blur', function() {
$('#two').val($('#two').val() + '\n' + $('#one').val());
});
You need to do some thing like this
$("#one").blur(function() { // triggering event
var one = $(this).val(); // place values in variable to make them easier to work with
var two = $("#two").val();
var three = one + two;
$("#two").val(three); // set the new value when the event occurs
});
This question isn't the easiest to decipher, but perhaps you want to store translated text into a second textarea?
<textarea id="one"></textarea>
<textarea id="two"></textarea>
var translate = function(input) {
// TODO: actual translation
return 'translated "' + input + '"';
}
var $one = $("#one");
var $two = $("#two");
$one.on('blur', function() {
$two.val(translate($one.val()));
});

How do I replace a specific piece of text in a textarea on a keyup event that gets the value of another input box

How do I replace a specific piece of text in a textarea on a keyup event that gets the value of another input box and replaces the specific piece of text in the textarea?
HTML looks like this -
<div>
<label>test1</label>
<input name="test_1" id="test1" type="text">
<label>Message</label>
<textarea rows="2" name="textarea_2" id="textarea2">Hello [initial text] blah blah blah</textarea>
</div>
I want to replace [initial text] with whatever is put into $('#test1').val();
Thanks
store the string to replace in var:
var lastStr = "[initial text]";
$("#test1").keyup(function() {
var val = $("textarea").val();
$("textarea").val(val.replace(lastStr, $("#test1").val()));
lastStr = $("#test1").val(); // update last str to replace.
});
demo: http://jsfiddle.net/k9uG4/1/
UPDATE:
I find the previous example its not safe, Because it replaces all Match char's in Entire area.
this example Replaces only the specific piece we want:
var lastStr = "[initial text]";
var startIndex = $("textarea").val().indexOf(lastStr);
$("#test1").keyup(function() {
var oldVal = $("textarea").val();
// get all the text before
var firstPart = oldVal.substring(0, startIndex);
// get the piece we want And replace it
var midPart = oldVal.substr(startIndex, lastStr.length).replace(lastStr, $("#test1").val());
// get all the text after
var lastPart = oldVal.substring(startIndex + lastStr.length, oldVal.length);
$("textarea").val( firstPart + midPart +lastPart );
lastStr = $("#test1").val();
});
demo: http://jsfiddle.net/k9uG4/6/

Getting text from input to replace label text in another form

reposting for simplicity. i want to have the text users enter into an input to replace the label text of another form's input. Additionally, the form is a plugin which doesn't let me attach an id to the specific label tag of the text i want to change. how can i do this, in vanilla javascript please.
the input users put text into:
<input class="charInput" id="name1" type="text" onKeyUp="change1(this)" >
the form label i want to change the text in (p.s: cant use the class(not unique to this label), cant add id):
<div id="frm_field_53_container" class="frm_form_field form-field frm_top_container">
<label class="frm_primary_label" for="field_inputactor1">
TEXT TO REPLACE
<span class="frm_required"></span>
</label></div>
Maybe it is not the best solution, but it is a solution that works in Firefox and Chrome (not tested under IE)
findLabelToChange = function() {
var div = document.getElementById("frm_field_53_container");
return div.querySelector("label");
};
customizeText = function(text) {
return text + ' <span class="frm_required"></span>';
};
change1 = function() {
var label = findLabelToChange();
var text = document.getElementById("name1").value;
label.innerHTML = customizeText(text);
};
you can see a example in this feedle
http://jsfiddle.net/HAK5X/1/
Here is a fiddle.
It is one line of code.
http://jsfiddle.net/te3jv/6/
function change1(myInput){
document.getElementById('frm_field_53_container').querySelector("label").innerHTML =myInput.value;
}
Alternatively add <span class="frm_required"></span> to the end of HTML reassignment to keep your empty (but required?) span.

Categories