Getting the alt value and text of an <img> tag and placing it into a textarea

I have a textarea that contains the following content:

<textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea>

I am aware that I can use javascript to specifically target and retrieve the alt value of the img element as follows:

<script>
    var $textfeldVal = document.getElementById("testContent");
    $img = $textfeldVal.getElementsByTagName("img")[0];
    alert("ALT VALUE: "+$img.alt);
</script>

My question is, is there a way to use javascript to select both the alt value of the img tag and the text within the textarea?

Answer №1

To combine them, you can use the following method:

let $inputArea = $("input#contentTest"),
    inputValue = $inputArea.val(),
    // retrieve alt value by using regex since jQuery cannot detect DOM elements within an input field
    altValueMatch = inputValue.match(/\<img.*?alt=(\"|\')(.*?)\1.*?\>/),
    altValue = (Array.isArray(altValueMatch) && typeof altValueMatch[2] === "string")
        ? altValueMatch[2]
        : null;

// eliminate the img tag from inputValue and remove any extra spaces
inputValue = inputValue.replace(/\<img.*?\>/, "").trim();

let combinedText = [altValue, inputValue].join(" ");

It's not recommended to insert DOM nodes inside an input field as it is meant for plain text.

Answer №2

It's uncertain whether an img tag can be placed inside a textarea. Why not try this instead:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>

        <div>
            <img id="imageDiv" src="..." alt="value">
            <div id="textDiv" contentEditable="true"> My text.... </div>
        </div>


        <script>
            var imageDiv = document.getElementById("imageDiv");
            var textDiv = document.getElementById("textDiv");
            alert("ALT VALUE: "+imageDiv.alt+"  "+textDiv.innerHTML);
        </script>

    </body>
</html>

UPDATE: Regarding @JnG's comment: Would it be easier to parse the text like so:

<textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea>

<script>
    var text = document.getElementById("testContent").innerHTML;
    var tmp = text.split("alt=\"")[1];
    var value = tmp.split("\"")[0];
    var myText = tmp.split("\"&gt;")[1];
    alert(value+" "+myText);
</script>

Check out the JSFiddle demo: https://jsfiddle.net/rfhvfwbz/1/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

tips for choosing a specific dropdown menu item

I'm having an issue with a function that I want to apply to all my dropdown lists. The problem arises when I try to select an option from the second dropdown list - instead of displaying the correct value, it shows the value from the first group in th ...

What are some creative ways to utilize postMessage instead of relying on nextTick or setTimeout with a zero millisecond delay?

I just came across a theory that postMessage in Google Chrome is similar to nextTick. This idea somewhat confused me because I was under the impression that postMessage was primarily used for communication between web workers. Experimenting with expressio ...

Troubleshooting Proxy.php issues in conjunction with AJAX Solr

Attempting to access a Solr 4.5.0 instance located on a private server, http://12.34.56.789:8983/ The application resides at this web server address, http://www.mywebapp.com To facilitate accessing the JSON object within the Solr instance, I decided to ...

Is there a way to extract the MIME type from a base64 string?

My base64 String appears as "UklGRkAdEQBXQVZFZm10IBIAAAABAAEAg...". I am attempting to download this file using my browser. Therefore, I convert it to a blob with the following function: b65toBlob: function(b64Data, sliceSize = 512) { ...

I seem to be overlooking something. The calculation is not displaying in the designated field

Having trouble with my area calculator - the area field is not updating as expected when I enter numbers in each field. Any advice on what might be missing? function calculateArea() { var form = document.getElementById("calc"); var sLength = parseFl ...

Removing a Button from a Form Using JavaScript

Here is a snippet of my HTML code: <form id="form"> <input id="deleteNumber" name="del" type="hidden" /> <input id="addAddress" name="addAddress" type="hidden" /> ... ... ... <a href="javascript:deleteAddress();" class="deleteItem" ...

The loading indicator is not appearing inside the designated box

I have successfully implemented a loader using jQuery and CSS to display a gray background during an AJAX call. However, I am encountering an issue where the loader and background are being displayed across the entire page instead of just within a specific ...

TypeScript multi-dimensional array type declaration

I currently have an array that looks like this: handlers: string[][] For example, it contains: [["click", "inc"], ["mousedown", "dec"]] Now, I want to restructure it to look like this: [[{ handler: "click" ...

Creating a prompt within a while loop

Issue with the code is that it should only progress if the user inputs "rock", "paper" or "scissors". However, after re-entering any input the second time, it still moves on despite passing the condition in the while loop. For instance, entering "asdf" p ...

Establishing a secondary setTimeout function does not trigger the execution of JQUERY and AJAX

// Custom Cart Code for Database Quantity Update $('.input-text').on('keydown ' , function(){ var tr_parent = $(this).closest("tr"); setTimeout(function () { $(tr_parent).css('opacity', '0.3'); }, 4000); var i ...

Trigger a jQuery modal by clicking on a cell within a table

As a novice in jquery, I am facing a challenge. I have a table with a column showing the total number of employees in a department. When a user clicks on this column, it should open up a jquery modal displaying a list of employees like EmpA, EmpB, and Em ...

There seems to be a problem with the JavaScript function as the indexOf property is undefined

function filteredArray(arr, elem) { let newArr = []; Iterating through each element of the multidimensional array. for (let i=0;i<arr.length;i++){ for (let j=0;j<arr[i].length;j++){ If the value matches the argument passed, assi ...

Implementing a Reset Button to Clear Checkboxes with PHP or JavaScript

I'm looking for help with setting up a button to reset the checkboxes on my preferences page. UPDATEL: Here's more information: The solutions provided should only affect checkboxes that are currently selected, not those enabled onLoad. This is ...

Node.js 'BLOB containing [object File]'

I am currently attempting to retrieve a BLOB from a request. The request object is created using FormData in Angular. const buffer = fs.readFileSync(fileFromRequest); The above code is resulting in an error: Error: ENOENT: no such file or directory, ope ...

Showing validation for arrays with multiple inputs using Ajax in the Laravel framework

Could someone please provide guidance on how to use ajax to display the JSON response of form validation messages in Laravel? Below are some of my form inputs: {!! Form::text('stories[0][subject]', null, [ 'class' => 'form-con ...

How can I utilize ng-repeat in AngularJS to iterate through an array of objects containing nested arrays within a field?

Here is the structure of an array I am working with: 0: {ID: null, name: "test", city: "Austin", UserColors: [{color: "blue"},{hobby:"beach"} ... ]} }... I am currently attempting to ng-repeat over this initial array in my code. However, when I tr ...

Error Encountered in Jhipster Application During Initial Launch

Struggling with running a newly generated Jshipster 3 application using gulp serve after successful generation. My setup includes Ubuntu 16.04 and npm 3.9, but I keep encountering an error when attempting to execute gulp serve: check out this screenshot ...

Fluctuating CSS appearance during content loading and asynchronous CSS loading

As I work on loading a new page and a CSS file for it using AJAX, I encounter an issue. Once all the CSS files are added to the page, I set the opacity to 1, expecting the page to display with the CSS applied immediately. However, it initially appears wit ...

What steps can I take to generate 12 random div elements using jQuery out of a pool of 30?

Currently, all the words are displaying, but I would like the script to randomly select 12 out of the 30 words var randomdivs = $("wordstyle").get().sort(function(){ return Math.round(Math.random())-0.5; }).slice(0,12) $(randomdivs).show(); The follo ...

Is there a way to make JavaScript function properly with PHP-generated content?

I have a PHP file that loads a variety of forms depending on an identifier passed through a GET request. Everything is functioning properly, except for my JavaScript/jQuery code. Is there a way I can refresh the JavaScript to make it work with the form? ...