Reputation: 2339
I have a textarea with this content
<textarea id="testContent"> <img src="..." alt="value"> My text.... </textarea>
I know I can use javascript to select the alt value of just img tag as shown
<script>
var $textfeldVal = document.getElementById("testContent");
$img = $textfeldVal.getElementsByTagName("img")[0];
alert("ALT VALUE: "+$img.alt);
</script>
Is there a way I can use javascript to select the alt value <img>
along with the text in the textarea?
Upvotes: 0
Views: 722
Reputation: 1258
Well, if you must, you could concatenate them like this:
var $textarea = $("textarea#testContent"),
textareaValue = $textarea.val(),
// get alt value using regex, as jQuery can't find DOM nodes within a textarea
altValueMatch = textareaValue.match(/\<img.*?alt=(\"|\')(.*?)\1.*?\>/),
altValue = (Array.isArray(altValueMatch) && typeof altValueMatch[2] === "string")
? altValueMatch[2]
: null;
// remove the img tag from textareaValue and trim any trailing whitespace
textareaValue = textareaValue.replace(/\<img.*?\>/, "").trim();
var concatenated = [altValue, textareaValue].join(" ");
You really shouldn't put DOM nodes inside the textarea though, as it is only designed for plaintext.
Upvotes: 1
Reputation: 745
I'm not sure you can put an img tag inside textarea... Why not simply:
<!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>
EDIT: In response to @JnG comment: Then why not just parsing the text:
<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("\">")[1];
alert(value+" "+myText);
</script>
JSFiddle: https://jsfiddle.net/rfhvfwbz/1/
Upvotes: 1