For example, i have the next code:
var sale = {};
sale.MainContent = function(p) {
alert("this handler is main-content");
}
and also I have the next html div:
<div id="content-data" data-handler="MainContent">{"name":"John"}</div>
I try do do next things - parsing the content of div in jquery, like this:
var cd=$("#content-data");
var obj = jQuery.parseJSON(cd.text());
And when i get the attribute fo data-handler:
var hname=cd.attr("data-handler");
So, the next step - call the function with name hname = 'MainContent' in sale object like this(?):
sale.hname(obj);
How i can call the function name in variable?
You can do this -
sale[hname](obj);
Related
I have this part of my html (more than one of same type):
<div class="this-product">
<img src="images/bag2.jpeg" alt="">
<span class="product-name">iPhone</span>
<span class="product-price">345445</span>
</div>
And this part of my javascript code meant to get the innerHTML of the span tags and assign them values as shown:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
var productName = document.getElementsByClassName('product-name')[0].innerHTML;
var productPrice = document.getElementsByClassName('product-price')[0].innerHTML;
var cartProductname = event.currentTarget.productName;
var cartProductprice = event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
Everything works well and every variable above has its value shown well apart from cartProductname and cartProductprice which display as undefined and also vscode tells me that productName is declared but not read. Where could I be wrong?
If I understand your question correctly, you could call querySelector on each product item element that you are iterating like so:
var productList = document.querySelectorAll('.this-product');
productList.forEach(function (element) {
element.addEventListener('click', function (event) {
// Update these two lines like so:
var productName = element.querySelector('.product-name').innerHTML;
var productPrice = element.querySelector('.product-price').innerHTML;
var cartProductname = productName; // event.currentTarget.productName;
var cartProductprice = productPrice; // event.currentTarget.productPrice;
var cartContent = '<div class="cart-product"><span class="block">'+cartProductname+'</span><span class="block">'+cartProductprice+'</span></div><div class="cart-result">Total = </div><br>'
document.getElementById('dashboard-cart').innerHTML += cartContent;
});
});
You can use event.currentTarget.querySelector('.product-name') to get element inside of another element
I am currently doing a school project and i need to stimulate a server side application. What i am substituting it with is "Local Storage" but i have an issue. I am able to have the text in my "Text box" stack on top of each other once user have submitted their question. Once they reload, the data will still be displayed. But i do not know how to stack on top of it AGAIN after they reload. Below is my testing code
<!doctype html>
<html>
<head>
<body onload="display()">
<input type="text" id="Name"></input>
<input type="submit" id="submit" onclick="SavetoStorage()"></input>
<p id ="hoho">
</p>
<script>
var name;
var groupOfName = ["Hello", "Chicken", "Pork","Beef"];
function SavetoStorage() {
var name = document.getElementById("Name").value;
groupOfName[groupOfName.length] = name;
var newone = groupOfName;
document.getElementById("hoho").innerHTML = newone;
localStorage.groupOfName = newone;
}
function display() {
var groupOfName = localStorage.groupOfName;
document.getElementById("hoho").innerHTML = groupOfName;
}
</script>
</head>
</body>
</html>
You need to be dynamically loading the groupOfName variable like so:
var tmp = localStorage.groupOfName; //this is a string
var groupOfName = Array.from(tmp); //turn it into an array
Hopefully this helps to point you in the right direction
You can use the setItem method from localstorage.
It uses 2 parameters:
a key and a value
so you can do something like this:
var inputValue = document.getElementById("Name").value;
localStorage.setItem("name", inputValue);
The above code sets the key "name" and that key holds the inputValue
So now you can retrieve the value by calling another local storage method called getItem:
var retrieveValue = localStorage.getItem("name");
The above code retrieves the item, and what does that item holds? the value from the input, so now you can add it to your html as you wish
So that's the basics but as you only have 1 input the value will be getting overwrited, and LocalStorage doesn't supports arrays but there's a workaround so you can use arrays, it goes something like this:
//this first part converts your array to string
localStorage.setItem("names", JSON.stringify(names));
//The second part returns your item and coverts it to an array again
var storedNames = JSON.parse(localStorage.getItem("names"));
My goal is to write content in a textarea and display exactly what I am writing without have to refresh the page each letter that I type shows immediately well it is not working for some reason.
HTML:
<textarea id="Q&A" name="txtarea" rows="4" cols="50"></textarea>
<div id="out"></div>
Js:
function generate() {
var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse(text);
text = writer.render();
document.getElementById("out").innerHTML = text
}
document.getElementById("Q&A").addEventListener("input", function () {
generate(this.value);
});
When I try to update the div with the id of out to what I am typing using JavaScript, it does not work.
I don't know what the commonmark.Parser() does in your code. But the issue i see is, When you are calling the generate method, you are passing the value of the input field. But in your generate method signature, you don't have a parameter to accept that.
Add a parameter to your generate() method to accept the value passed in.
function generate(text) {
//do something else on text with your commonmark
document.getElementById("out").innerHTML = text;
}
Here is a working sample.
and you forgot to pass the argument parsed to the render function:
You had: text = writer.render(); I changed it to text = writer.render(parsed);
I figured it out i forgot to have text pasted in as a argument in the generate function and I forgot to pas parsed into the render function
Here is the final code:
function generate(text) {
var reader = new commonmark.Parser();
var writer = new commonmark.HtmlRenderer();
var parsed = reader.parse(text);
text = writer.render(parsed);
document.getElementById("out").innerHTML = text
}
document.getElementById("Q&A").addEventListener("input", function () {
generate(this.value);
});
I have a list in one file html called "filed1":
<ul>
<li>Nombre:<a class="boton" onclick=move() title="Caja">Caja</a><br>
<FONT SIZE=2>Fecha: 21/12/1994</font></font></li>
</ul>
Now I want to change a string in other html "filed2":
<a id="logo-header2">
<h1>
<span class="site-name" id="element">Details</span><br>
</h1>
</a>
Using Java Script:
function move() {
mywindow = window.open("file2.html");
mywindow.document.getElementById("element").innerHTML="Changed");
}
But there is an error which says that mywindow.document.getElementById("element") is NULL, why? The id element exists in the other window. Is there another way to change the string?
The problem is that you are trying to retrieve the DOM element before the window is loaded.
Try following
mywindow.onload = function() {
mywindow.document.getElementById("element").innerHTML="Changed";
}
Like #nikhil mentioned, mywindow is undefined when you're calling it, and you'll need to place your code into something triggered by the onload event.
Another approach you can try is perhaps passing the string as a variable in the url, like so:
function move(){
window.open("file2.html?str=Changed");
}
And then in file2.html, try something that runs on page load:
window.onload = function(){
var str = $_GET('str');
document.getElementById("element").innerHTML = str;
};
function $_GET(q){
var $_GET = {};
if(document.location.toString().indexOf('?') !== -1){
var query = document.location
.toString()
.replace(/^.*?\?/, '')//Get the query string
.replace(/#.*$/, '')//and remove any existing hash string
.split('&');
for(var i=0, l=query.length; i<l; i++){
var aux = decodeURIComponent(query[i]).split('=');
$_GET[aux[0]] = aux[1];
}
}
return $_GET[q];
}
The $_GET function I included is just for getting query string parameters, and function much like $_GET[] in php.
In my HTML page i have a button which on click fetches the elements in the page and passes them on to the server.
<button type="button" class="btn btn-default" id="filter_btn" onclick="on_submit()">Submit</button>
the function call is handled by my js code like this below.
function on_submit()
{
var $start_date=document.getElementById("datepicker1").value;
var $end_date=document.getElementById("datepicker2").value;
var $vid1 = $('#vid1');
var $vid2 = $('#vid2');
var $vid1_name = $('#vid1').text();
var $vid2_name = $('#vid2').text();
var $metric = $('#metric').val();
var $frequency = $('#freq').val();
$.get('../content_focus',{type:"getData",vid1_name:$vid1_name, vid2_name:$vid2_name, vid1:$vid1, vid2:$vid2, start_date:$start_date, end_date:$end_date, metric:$metric, frequency:$frequency}, function(responseData){
alert('im done');
});
}
Now the borwer console throws an error stating "'click' called on an object that does not implement interface HTMLElement."
And none of my print statements or alert statements get executed i would like some help with this
It seems to be the problem is with,
var $vid1 = $('#vid1');
var $vid2 = $('#vid2');
$vid1 and $vid2 are HTML elements.
If you want to pass the html use,
var $vid1 = $('#vid1').outerHTML();
var $vid2 = $('#vid2').outerHTML();