Make Function with querySelectAll with forEach - javascript

I want to create a javascript querySelectAll with foreach. I need to use this many times. So i want to create a function. But not working. Please help me.
<p id="o">one</p>
<p id="o">two</p>
<script>
function q(x,y) {
document.querySelectorAll(x).forEach(e => { e.y })
}
q('#o', innerHTML = 'Working');
</script>

If you want to put some code in a reusable form that you can pass around then it needs to be a function.
An expression is just going to be evaluated immediately.
innerHTML = 'Working' will assigned the string to the global variable innerHTML and then the pass the result (the string) to y.
You need it to be a function and then you need to call it.
What's more: An ID must be unique in a document. If you want to loop over a group of things then use a class.
function q(x, y) {
document.querySelectorAll(x).forEach(y)
}
q('.o', (element) => element.innerHTML = 'Working');
<p class="o">one</p>
<p class="o">two</p>

Related

jQuery attribute contains JavaScript

After hours of searching without result, I turn to you
The question is simple, with jQuery can I put JavaScript in an attribute?
example
<div id="MyDiv" data-func="
console.log('#MyDviv[data-func] called')
"></div>
The ultimate goal is: I have an object that has an action to do and I would like before I do this to call a function that checks can proceed.
Example
<div id="MyDiv" data-action="next" data-func="
()=>{
var valid = true
/* ... */
return valid===true;
}
"></div>
code in the library
$('#MyDiv').on('MyEvent',function() {
/* ... */
var buttonAct = $(this).attr('data-action');
var validator = $(this).attr('data-func');
var valid=false;
/*
code that executes the validator and puts the result in valid
*/
if (valid)
buttonNextPrev (buttonAct);
});
Solutions like eval and things like that are not allowed, I need something that works like event example onclick
As Quentin notes in their answer, there is no way of putting arbitrary JavaScript into an HTML attribute and executing it without using eval or something equivalent.
There are workarounds, however.
For instance, if you can write the functions you want ahead of time, and name them in a memorable way, and could place the names of the functions in the attributes. Here's an example of doing that:
const other = {
doThisToo: (me) => {
me.style.backgroundColor = 'white';
}
};
document.getElementById('example').addEventListener('click', function () {
this.style.color = 'red';
const fn = this.getAttribute('data-other');
if (other[fn]) {
other[fn](this);
}
});
<button id="example" data-other="doThisToo">Example</button>
Essentially, this is just putting the name of "some other function to call" in the attribute value and using that name to look up the function in an object other that has the functions as properties. One could just use globally-scoped functions as well, but I prefer to pollute the global namespace as little as possible.
solutions like eval and things like that are not allowed
Then no, it isn't possible.
Any solution that would pull text from an HTML attribute and execute it as JavaScript would be like eval (even if you did it at one-step removed from eval itself such as with the Function constructor function).

How to click a button to add a value to an array and display it

I am currently stuck on trying to use an onclick button to push a value into an array.
let display = document.getElementById('screen');
let results = [];
display.innerHTML = results[0];
$(document).ready(() => {
$('.one').click(function() {
results.push(1);
});
})
I am trying to push 1 into the array when the button is pushed, then display it. However, my current code does not push the function.
It does work, but the line that shows the results must be inside of the click callback. As it is now, the display gets updated just once, before the click happens.
Also, JQuery deprecated "shortcut" event methods (.click()) a while back and recommends the use of .on().
Lastly, innerHTML has performance and security implications, so don't use innerHTML when the string in question doesn't contain any HTML. Instead, use .textContent. But, because you are already using JQuery, you can use .text().
// If you are going to use JQuery, then use it.
// Here, we can get the element with an id of "screen"
// into a JQuery wrapped set object very easily.
// Naming the variable that will hold that JQuery object
// with a $ is a standard convention to remind you that
// the variable holds a JQuery object and not a standard
// DOM object.
let $display = $('#screen');
let results = [];
// And, with JQuery, if you just pass a function directly
// to JQuery, that function is automatically understood to
// be a document.ready callback
$(() => {
$('.one').on("click" ,function() {
results.push(1);
$display.text(results[0]); // This must be in the callback to show the most up to date information
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="button" class="one" value="push">
<div id="screen"></div>

Can't execute function in javascript

I've looked a lot in this website for an answer and honestly I've seen many close answers to my problem but still can't make it work.
I want to use a input textbox value and put it in javascript function then use javascript to calculate what I've given to the textbox for me and then put the answer to another paragraph in my html document (in this case I want to use kmh=ms*3.6 with return to do the calculation)
So this is my function code:
function msToKM() {document.getElementById('mstokm').innerHTML='<input type="text" name="mstokm" id="mstokmh" value="10"/>m/s<br><br><button type="button" class="buttons" onclick="convMSKM()" style="padding: 10px 10px;">Equals to!</button>';}
function convMSKM () {mstokm= document.getElementById('mstokmh'); mstokmA(mstokm);}
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
And I'm specificly having a problem with this part of the code:
function mstokmA(ms) {return kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}
because it's not executing the last part of it.
I can provide the html codes as well if needed.
How can I fix this?
Here's a demo how to do it
Well with onclick event i am selecting value of input field and than printing result in console. you can place it to any element you want instead of printing to console.
function handle(){
let val = document.getElementById('userIn').value;
console.log(3.6*val)
}
<input type='text' value='' id='userIn'/>
<button onclick='handle()'>calculate</button>
The return statement causes the function to stop executing, so what is happening is that you are returning value and it never gets to set that value inside the element. You can do something like this:
mstokmA(ms) {
document.getElementById('AmstokmA').innerHTML = ms*3.6;
}
OR more like you were trying to do:
mstokmA(ms) {
var kmh = ms*3.6; // set value inside variable
document.getElementById('AmstokmA').innerHTML = kmh; // append that value to the element
}
I prefer the first option.
I hope it helps ;).
Note: there is no need to return in this case.
Leave the return statement where it it, but replace "return" with "let".
Example:
function mstokmA(ms) {let kmh= ms*3.6; document.getElementById('AmstokmA').innerHTML=kmh;}

Hide Collection of jQuery elements in Array Using Hide()/Show()

Seemingly-easy problem here: I'm trying to create a streamlined way to hide/show a collection of DOM elements using some jQuery/vanilla JS. This was from a refactor where several fragmented functions were re-done as better encapsulated versions of their former selves.
What these functions are trying to do take elements from an array (by ID), use map to convert them to jQuery objects, and then hide or show them.
Using jQuery 1.11 in an Angular project, but the angular aspect doesn't seem to interfere with this case, since it won't work in a jsFiddle either.
main problem: When I run the function (usually using a click event), I don't get any sort of error from console and I don't get any sort of result in the DOM either. Any ideas? I'm sure it's a simple thing I'm missing, but I need other eyes on it.
Here's a jsFiddle with the below code loaded in, ready for fixin'. Thanks!
http://jsfiddle.net/sLgqvdku/
function showItem(item) {
return item.show();
}
function hideItem(item) {
return item.hide();
}
function showItemsWithIDs(ids) {
ids.map($).forEach(showItem);
}
function hideItemsWithIDs(ids) {
ids.map($).forEach(hideItem);
}
var itemsHiddenToFocusTribute = ['#form', '#ask', "#submitButton", "#sidebar", "#AmountCtrl", "#giftbutton"];
It appears that only the first element in the array is actually being converted into a jQuery object in your code.
Here's what's happening: vanilla-JS .map passes three arguments to the specified callback function: the current element, the index, and the array.
If the callback function takes only one argument, the second and third are ignored. However, jQuery's $ actually allows two arguments: a selector, and a context (container element). So your code is passing (as the second argument) the array index as a context, resulting in an empty jQuery object -- except for the first element in itemsHiddenToFocusTribute, which has index 0 which is interpreted as no context at all.
You can fix this with an anonymous function that only passes the selector string to $:
function hideItemsWithIDs(ids) {
ids.map(function (i) {
return $(i);
}).forEach(hideItem);
}
http://jsfiddle.net/mblase75/e23qgad5/
However, a more jQuery-friendly way would be to create a single jQuery object of all the desired elements and loop through them using .each:
function hideItem(i,item) {
return $(item).hide();
}
function hideItemsWithIDs(ids) {
$(ids.join()).each(hideItem);
}
http://jsfiddle.net/mblase75/mm2L4xn1/
This is probably more efficient, too, since you're calling $ just once instead of array.length times.
All you're wanting is to send each id through the foreach loop? Then I'd just use each like so:
$(ids).each(function(index, id) {
hideItem(id);
});
You don't need to use map($) to convert them to jQuery objects, just put the object inside the dollar sign function call, like so: $(ids).
Also make sure you pass the actual id to showItem and hideItem when you call them, like so: hideItem(id). You also need to make sure that you use a jQuery object in your hideItem and showItem functions. I changed your code to this:
function showItem(item) {
return $(item).show();
}
function hideItem(item) {
return $(item).hide();
}
function showItemsWithIDs(ids) {
$(ids).each(function(index, id) {
showItem(id);
});
}
function hideItemsWithIDs(ids) {
$(ids).each(function(index, id) {
hideItem(id);
});
}
var itemsHiddenToFocusTribute = ['#form', '#ask', "#submitButton", "#sidebar", "#AmountCtrl", "#giftbutton"];
$('#clicker').click(function(){
hideItemsWithIDs(itemsHiddenToFocusTribute);
});
And here's the updated Fiddle

How do you add a input element to a variable

I input a number into a textbox.
I want to know how do you cast this number to a declared variable:
For Example:
<body>
Please Enter value number 1: <input type = "text" id = "value1"></input>
<button onclick = "Display()">Display</button>
<p id = "Paragraph"></p>
<script>
The Question is here:
var a = document.getElementById("value1").value;
The statement above is what i want to know to do.
function Display()
{
document.write(a);
}
</script>
</body>
I am new to javascript, and i'm trying to learn so sorry if the question is a bit basic but im struggling to get this right.
I guess you mean something like this:
function Display()
{
var a = document.getElementById("value1").value;
document.getElementById( 'Paragraph' ).innerHTML = a;
}
With your code the variable a is just assigned, when the script is executed the first time. It is not a pointer to the value, but just grabs the value once. So if you want to use it, when clicking the button, you have to get it inside the executed function.
Don't use document.write() like this. If you want to display something at runtime innerHTML is a better choice!
Assign a inside your function:
function Display()
{
var a = document.getElementById("value1").value;
console.log(a);
}
Also, <input /> tags do not require a closing </input> tag.

Categories

Resources