Getting info from HTML set in a variable in Javascript - javascript

I have something like this:
function (foo) {
}
Foo contains some HTML. For example:
<div>
<div>
<div class="myclass>
<div>
Hello World
</div>
</div>
</div>
</div>
I need to extract that info off the variable somehow.
I have tried:
function (foo) {
$('.myclass > script').text()
}
I probably need some way to select foo instead. Any help?

If you want to do this in jQuery then you need to convert the string of HTML held in foo in to a jQuery object which you can interrogate with jQuery methods to retrieve the data you need. For example:
function getText(foo) {
return $(foo).find('.myclass').text();
}
let input = '<div><div><div class="myclass"><div> Hello World</div></div></div></div>';
console.log(getText(input));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

How to pass variable to child function from HTML page

I want to pass a value from HTML page to child function from parent function.
HTML Page:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">Send/div>
</div>
</div>
Parent Function Call:
$('.send_message').click(function (e) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
});
$('.message_input').keyup(function (e) {
if (e.which === 13) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
}
});
here getMessageText1 is child function.
Child Function:
getMessageText1 = function () {
var result="";
var id = Parent_FUNC_INPUT;
$.ajax({
url:"func.php",
type: 'POST',
data: ({id:id}),
async: false,
success:function(data) {
result = data;
}
});
I want to populate [[id]] variable in child function from parent function.
First, I'll do my best to clean up the HTML:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
</div>
<div class="text">Send</div>
</div>
Using proper indentation will make things far easier to read. And while we're on the subject, you may want to use dashes - instead of underscores _ in your class names, as that's the common convention.
On to your question, it seems like what you want to do is simply pass an argument to getMessageText1 from within (as you refer to it) a "parent" function bound to an event listener.
So you'd define this "child" function with a single parameter:
function getMessageText1(Parent_FUNC_INPUT) {
...
var id = Parent_FUNC_INPUT;
...
}
And then you can just call it with getMessageText1(value) where value is whatever you want to pass in.
One more note: for readability's sake I recommend you do not name your functions the way you have. Having two functions getMessageText and getMessageText1 will just be a source of confusion later on. Instead, think of something more descriptive, ala getMessageTextFromID.
Hopefully I answered the question you meant to ask. Let me know.

Combine $ and _ to pluck by data values?

I have a list of jquery elements with a data attribute.
Now I want to get a list of these data attributes.
As the data-attribute is some kind of an object property, I thought this might work with underscores pluck method.
Is this even possible?
See this short example:
var divs = $("div");
// now do something
// expected result: [1, 2, 3]
<script src="https://cdnjs.com/libraries/underscore.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
Solution
Based on #romeo-sierra this is the way I wrote it down (as I already have jquery objects). Underscores pluck is superfluous
var foos = $("div").map(function() {
return $(this).data("foo");
}).toArray();
console.log(foos);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
Vanilla JS can accomplish this just fine, no jQuery nor any other library needed:
const foos = [...document.querySelectorAll('[data-foo]')]
.map(elm => elm.dataset.foo);
console.log(foos);
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
ES5 version:
var foos = Array.prototype.map.call(document.querySelectorAll('[data-foo]'), function(elm) {
return elm.dataset.foo;
});
console.log(foos);
<div data-foo="1">a</div>
<div data-foo="2">b</div>
<div data-foo="3">c</div>
<div>x</div>
How about the following, that uses pure jQuery? (since you already are using it)
var arr = [];
$('div[data-foo]').each(function(){
arr.push($(this).data("foo")); // should return the value
});
console.log(arr);
Check this fiddle out.
You definitely have to lookup for a specific data attribute.
You can't just drain the whole page for elements data attribute and obtain a complete list like that.
But if you know what you look for...
See below
var attribute = "foormidable";
$("*").each(function(){
var match = $(this).attr("data-"+attribute);
if(typeof(match)!="undefined"){
console.log(match);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foorm="1">a</div>
<div data-foormidable="2">b</div>
<div data-foolahlayouuu="3">c</div>
<div>x</div>
OR using .data()
var attribute = "foormidable";
$("*").each(function(){
var match = $(this).data(attribute);
if(typeof(match)!="undefined"){
console.log(match);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div data-foorm="1">a</div>
<div data-foormidable="2">b</div>
<div data-foolahlayouuu="3">c</div>
<div>x</div>
That last one will get the value of THE OBJECT... Be it dynamic via JS code.
That is real different from the on load markup attribute value.
;)

How to select elements from a handelbars template?

We have a div within our webpage:
<div id="person-details">
<div></div>
...
</div>
We select the relevant elements from this div using the following jQuery code:
var person = $("#person-details");
var children = release.find("div");
var fullname = children.first();
We use a render function to perform an ajax request to get a handlebars template that we're storing in an external file:
function _render() {
var templateScript;
template.getTemplate(filename).done(function(template) {
templateScript = Handlebars.compile(template);
fullname.html(templateScript(context));
});
}
The template looks like the following:
<div>
<div>
<p>{{name}}</p>
</div>
<div>
<p>{{value}}</p>
</div>
</div>
After the render function has been called, we want to select any of the elements from within the template. For example we have tried using:
fullname.children('div');
but as the content has been dynamically generated we aren't able to get the nodes from within the DOM.
Is it even possible to select elements from within a generated handlebars template like this?
Thanks to #DanielShillcock for highlighting render() being asynchronous. Here is a solution:
function _render() {
var templateScript;
template.getTemplate(filename).done(function(template) {
templateScript = Handlebars.compile(template);
selector.html(templateScript(attribute));
value = selector.find("div");
});
}

How to display value of a ViewBag in my view with a JS function?

I want to display the data from a ViewBag in my View with Javascript. Here is my code.
View
<span id='test'></span>
Javascript
function myFunction()
{
$('#test').text('#ViewBag.Test');
}
When myFunction() is called I get the text #ViewBag.Test but not his value. How can I fix this ?
You need to place your JavaScript which takes the #ViewBag.Test value in a page which is interpreted by the Razor view engine. My guess is that this is currently not the case.
If you want to keep your javascript codebase separate from the view (which is entirely reasonable) you can use a global variable:
// in the view:
var testText = '#ViewBag.Test';
// in external js
function myFunction() {
$('#test').text(window.testText);
}
Alternatively, you can use a data-* attribute:
<span id='test' data-text="#ViewBag.Test"></span>
// in external js
function myFunction() {
$('#test').text(function() {
return $(this).data('text');
});
}
What you should be ideally doing is passing the data to the view with a view model. Have a property to store that value you want to pass. For example. Let's think about a page to show the customer details and you want to get the last name in your javascript variable.
Your GET action method
public ActionResult View(int id)
{
var vm=new CustomerViewModel();
vm.LastName="Scott"; // You may read this from any where(DAL/Session etc)
return View(vm);
}
and in your view which is strongly typed to your view model.
#model CustomerViewModel
<div>
Some Html content goes here
</div>
<script type="text/javascript">
var lastName="#Model.LastName";
//Now you can use lastName variable
</script>
EDIT : (As per the question edit) To show the content on some event (ex : some button click), Store the value somewhere initially and then read it as needed and set it wherever you want.
#model CustomerViewModel
<div>
<span id="content"></span>
#Html.HiddenFor(s=>s.LastName)
<input type="button" id="btnShow" value="Show content" />
</div>
<script type="text/javascript">
$(function(){
$("btnShow").click(function(e){
$("#content").html($("#LastName").val());
});
});
</script>
Firstly make sure your ViewBag.Test does got a value, then use a div tag instead of a span and add the following code:
<script type="text/javascript">
$(document).ready(function () {
StartRead();
});
function StartRead() {
document.getElementById("test").innerHTML = '#ViewBag.Test';
}
</script>

Get next textarea outside div without id

I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.
The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>
If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');

Categories