Get content of div including input values - javascript

I'm replacing some specific character by inputs via regexp.
Div looks like that:
1) <div>Text text text text <input> text text <input> text</div>
2) <div>text Text <input> text <input> text text Text</div>
Is it possible to get whole text including input values from a div (with id 'body' in my case)?
jQuery code:
var body = data.body.replace(/\.\.\./g, "<input class='bodyy' type='text' size='2' />");
$("#body").html(body);
Fiddle: https://jsfiddle.net/uepf87fc/

You can parse it yourself with a function, here's an example:
function getTextWithInputValues(id) {
var element = document.getElementById(id);
if (!element) {
return null;
}
var elementText = element.innerHTML; // Get the entire text from your element
var elementInputs = element.getElementsByTagName('input'); // fetch all inputs from your element
// replace all input fields with their respective values
Object.getOwnPropertyNames(elementInputs).forEach(
(input) => {
var inputText = elementInputs[input].outerHTML;
if (elementText.search(inputText) > 0) {
elementText = elementText.replace(inputText, elementInputs[input].value);
}
}
);
return elementText;
}
You can test it right here by opening a console, paste this code in, then type in something in the search box on the top of the page (don't click search, just type in something), then when you call the function in the console like getTextWithInputValues('search') it will output something like
<svg ......</svg>
your-text-here
<button .....</button>
Hope this helps.

Even though you asked for REGEX, I don't believe it is by any means needed.
This will return the data in an array. With the first index being the body text, and each input field value thereafter.
var values = [];
values.push($('#body').text());
var inputs = $('#body input');
for(var i = 0; i < $(inputs).length; i++)
{
var currentElement = $(inputs)[i];
values.push($(currentElement).val());
}
console.log(values);

Related

Get the position of clicked word in textbox (Javascript)

I have a textbox with multiple sentences, and when I click on a word, I need to get the position of the word in this textbox.
The code actually just get the whole text from the textarea and writes it in another text area. I am struggling to get specific position of the character (or word) I clicked on.
What it should do is to copy just the text before clicked word/character.
var themaintextarea = document.getElementById('textarea');
themaintextarea.addEventListener('click', replace_sentence);
function replace_sentence(e){
var themaintext = document.getElementById("textarea").innerHTML;
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
alert(sometext);
}
<textarea id="curent_sentence"></textarea>
<div id="textarea" contenteditable>I <span>like</span> apples. I <span>like</span> apples.
<br>
I <span>like</span> apples.</div>
EDITED : Heres the fiddle to select the word before the word clicked on. Note: no spans are used in this. https://jsfiddle.net/Lnkav5ca/5/
I think i understood what you're looking for. https://jsfiddle.net/Lnkav5ca/1/ I put all the clickable words in a class and add event listeners to that class. So when the word is clicked on it gets inserted into the text box.
var themaintextarea = document.getElementsByClassName('clickable');
for (var i = 0; i < themaintextarea.length; i++) {
themaintextarea[i].addEventListener('click', replace_sentence);
}
function replace_sentence(e){
console.log(e);
var themaintext = e.target.innerHTML
//alert(thereplace);
document.getElementById("curent_sentence").value = themaintext;
theselection = window.getSelection();
var therange = theselection.getRangeAt(0);
var sometext = therange.toString().trim();
//alert(sometext);
}

javascript: deleting tags of a selected element in a text

I put a tag to a selected element in my textarea and every tag take an id. And I store the element an a table.
But, I want to delete some tags(I have to type of tag "ref" et "point"). And I try this function but, it doesn't work:
function deleteTag(textField, tag)
{
var scrollTop = textField.scrollTop; //For the scroll of the text
var start = textField.selectionStart; //beginning of the selected text
var end = textField.selectionEnd; //End of the selected text
var modif=textField.value.substring(start,end); //The text to modify
// Remove the tag
if(modif.match('[^<]'+tag+'id="(\\d+)">') && modif.match('</'+tag+'[>$]'))
{
var regex;
if(tag=="ref")
{
regex=new RegExp('<'+tag+' id="(\\d+)">');
var opt=modif.match(regex)[1];
document.getElementById("refList").remove(opt-1);
}
regex=new RegExp('<'+tag+'[^>]+>');
modif=modif.replace(regex, "");
modif=modif.replace('</'+tag+'>', "");
}
textField.value=textSup+modif+textInf; //We modify the text inside the text area
textField.scrollTop=scrollTop;
}
And the button have this code:
<button onclick="deleteTag(textAreaId, 'ref')"> Effacer
By the way I'm beginner in javascript
if(modif.match('[^<]'+tag+'id="(\\d+)">') && modif.match('</'+tag+'[>$]'))
maybe you need an extra space in the regex:
if(modif.match('[^<]'+tag+' id="(\\d+)">') && modif.match('</'+tag+'[>$]'))

replacing html tag inside textarea with text

code :
<script src="Scripts/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
var $this = $("#Test_txtarea");
var txtval = $this.val();
$this.find("img").each(function () {
var imgbytes = $(this).attr("name"); // extract bytes from selected img src
$(this).replaceWith(imgbytes);
});
$("#NewVal").html(txtval);
});
</script>
html
<textarea ID="Test_txtarea" >Hi <img src='test.png' name='test' > kifak <img src='test2.png' name='test1' > Mnih <img src='test3.png' name='test3' ></textarea>
<span id="NewVal" ></span>
what i am trying to do is basically trying to replace each img tag by it's name so the final textarea value will be like this : Hi test kifak test1 Mnih test3
this is the jsfiddle : http://jsfiddle.net/Ga7bJ/2/
the .find("img") always return 0 as length.how can i fix this code ?
Though it is not complete answer or at least not going to be "Copy paste" answer, there is few things you need to do here:
The content of Textarea is VAL of it and not InnerHTML. So, you have to pick that content as value and than create a hidden div and put it as HTML. Once you did it, you can now find the HTML tags in it using find rather easily.
Once you find tag you can find the name using attr() function
Once you have name, than you again go back to val() of textarea, and do regex replace or using HTML you can replace as well I guess, but not sure.
Look at this jsFiddle. What is does is:
It gets the value from your Test_txtarea and sets that as the html of a hidden div.
The hidden div wil render the images within the textarea.
After they have been rendered, I find these images,
- get the source,
- remove all characters after the .
- replace the entire html of the image with the src.
After all that has been done you are left with a div with the value you wanted.
All what is done next is the html from the div is copied to the value of your textarea.
function replaceImageWithSrc(value){
var div = $("#invisible");
div.html(value);
var images = div.find("img");
images.each(function(index){
var src = $(this).attr("src").split(".")[0];
this.outerHTML = src;
});
return div.html();
}
$(document).ready(function () {
var txtArea = $("#Test_txtarea");
var txtval = txtArea.val();
txtval = replaceImageWithSrc(txtval);
txtArea.val(txtval);
});
The following code works for me. Basically, I get the value of the text area and append it to an off-screen div. Now that I have valid markup nesting, I can iterate the child-nodes as normal.
function byId(e){return document.getElementById(e)}
function newEl(t){return document.createElement(t)}
function test()
{
var div = newEl('div');
div.innerHTML = byId('Test_txtarea').value;
var msg = '';
var i, n = div.childNodes.length;
for (i=0; i<n; i++)
{
if (div.childNodes[i].nodeName == "IMG")
msg += div.childNodes[i].name;
else if (div.childNodes[i].nodeName == "#text")
msg += div.childNodes[i].data;
}
byId('NewVal').innerHTML = msg;
}

Disable input after submit and count array element

function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
var elem = [];
for (var i = 0; i < tags.length; ++i){
//store array elements
elem.push(tags[i]);
if(elem.length < 2){
$("#tags").prop('disabled',false);
}
else{
$("#tags").prop('disabled',true);
}
}
}
As for html, it is small div with button. When I type tags in input textfield, it will be appended to div area. When tags are more than 2, input textfield will be disabled to prevent more tags from being added. After submit the form, div showed the same number of tags but input textfield won't stay disabled. So how to make input textfield stay disabled if tags are more than 2 in div?
Appreciate the insight or help. I have been searching for online answers but seem not to find what I need the input text disable after submit.
You should probably check the length after the array is populated, and you're creating an elem array that is exactly the same as the tags array you have :
function limitofTags(){
var tags = $('div').find('.tag').map(function(){
return $(this).text();
}).get();
$("#tags").prop('disabled', tags.length >= 2);
}

Within a div containing both text and an HTML element, how to change only the text and not the element, using JQuery?

I am using a plugin that renders a div style "button", whose html looks like this:
<div id="div-id">
"Button Label"
<input type="file" . . . >
</div>
How do I dynamically change the "Button Label" text with jQuery, while leaving the input intact?
I've tried using .text() but that replaces the input as well.
(Note: I have no control over the HTML that the plugin renders so I'm stuck with this structure).
Thanks!
Here's one solution. Save the children of the div, set the text, and then append the chilrden back to it.
var $children = $myDiv.children();
$myDiv.text("New Button Label").append($children);
Example.
$("#div-id").html(function(i,oldhtml){
return oldhtml.replace("Button Label","New label");
});
You can directly access the text node in plain javascript with code like this:
function getFirstTextNode(el) {
var children = el.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].nodeType == 3) {
return(children[i]);
}
}
}
var textNode = getFirstTextNode(document.getElementById("div-id"));
textNode.nodeValue = "New Label ";
You could iterate through each node, and look for text nodes with matching content. Once found, only work on that node.
function isTextNode(node) {
return node.nodeType == 3;
}
function hasText(node, text) {
return node.nodeValue.trim() == text;
}
var nodes = $("#root").contents().filter(function() {
return isTextNode(this) && hasText(this, '"Button Label"');
});
nodes.replaceWith("New Label");
Here's an example.

Categories