jquery make alert equal to an array of names - javascript

This code above looks to see if my check boxes are checked or unchecked. IF they are unchecked then it logs in the console the names of the checkboxes that are unchecked. I want to take those names and put them in the alert box and am struggling to access the element.name outside the each loop. Anyone have any ideas?
// when page is ready
jQuery("#user_price_accept").submit(function(event) {
// on form submit
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
var test2 = '';
test.each((i, element) => {
console.log(element.name)
test2 = element.name;
})
return test2;
if (test.length > 0) {
alert(test2);
}
});

jQuery has a handy .map() method which you can use to transform a collection of elements into an array of data.
You could then join that array into a string and alert it
jQuery("#user_price_accept").on("submit", function(event) {
event.preventDefault()
const test = jQuery(this).find('input[type=checkbox]:not(:checked)')
const names = test.map((_, el) => el.name).get() // get() returns the underlying array
if (names.length) {
alert(names.join(", "))
}
})

First, you're returning before the alert. That will stop execution of anything in the same bracket that occurs after that.
Second, you're reassigning test2 inside of your loop. Even if you can access it outside of the loop, all you're going to get is the name of the last element. Try using test2 += ', ' + element.name
Third, this bit here:
if (test.length > 0) {
alert(test2);
}
looks like you are checking the length of an unchanged list. Except the test you defined above is another jQuery object (which I'm not sure has a length built-in, but I digress). Still unchanged though. If this is what you are looking for, that's fine, but I would put the test.each((... inside of the if statment

You are missing concatenation of name and every time test2 gets replaced with a new name. Also returning test2 in function will go outside of function and alert code will not be executed. I have modified few lines
test2 += element.name; // names are added in test 2
return test2; // remove this line or handle after alert code
// when page is ready
jQuery("#user_price_accept").submit(function(event) {
// on form submit
event.preventDefault();
var test = jQuery(this).find('input[type=checkbox]:not(:checked)')
var test2 = '';
test.each((i, element) => {
console.log(element.name)
test2 += "," + element.name;
})
//return test2;
if (test.length > 0) {
alert(test2);
}
});

Related

Camelize function output not displayed, no error thrown

I have a very basic HTML, user enters something like -webkit-transition and the function returns something like WebkitTransition.
<div id='app'>Change input to camelCase</div>
<input id='getInput' />
<button id='submit' />get result</button>
<span id="output">Result: </span>
The relevant JS is this:
// initializing the input field value var let inputed = getInput.value;
// this is the function, it should take the input.value as argument
function whatComesOut (str) {
return str
.split('-')
.map(
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
)
.join('');
}
// updating the input value on change, this logs the correct input value
getInput.addEventListener('change', function(e){
let inputed = e.target.value;
console.log(inputed);
})
// on click I want to display the returned value from the function in the span element
submit.addEventListener('click', function(){
console.log(inputed);
output.innerHTML += whatComesOut(inputed);
})
But, nothing is happening, no errors in the console either.
A link to codepen
https://codepen.io/damPop/pen/PxYvJr?editors=0010
The question is, how do i get the return value from the whatComesOut function displayed in the span element? Do i need the pass the event object somewhere?
The issue here is that unlike in the event listener on getInput, the value of inputed is not declared in the submit event listener, so it uses the static value that was assigned on line 5. If you add const inputed = getInput.value; right before output.innerHTML += whatComesOut(inputed); this will work.
You need to make the variable inputed global instead of local to only the event listener function.
Also, change the type of your button to "button" so it does not submit the form and refresh the page.
// initializing the input field value var let inputed = getInput.value;
let inputed;
// this is the function, it should take the input.value as argument
function whatComesOut (str) {
return str.split('-').map(
(word, index) => index == 0 ? word : word[0].toUpperCase() + word.slice(1)
).join('');
}
// updating the input value on change, this logs the correct input value
getInput.addEventListener('change', function(e){
inputed = e.target.value;
console.log(inputed);
})
// on click I want to display the returned value from the function in the span element
submit.addEventListener('click', function(){
console.log(inputed);
output.innerHTML += whatComesOut(inputed);
})
You've declared a global variable inputted And which was redeclare in one of The Event,
So this makes the initialization strict within the Event ( local scope ). The initialization to the local scope variable made no changes to the global variable.
var global = 'it's global now'
function func() { var local = 'its local variable'}
The global scope variable is accessible within the local scope and you could make changes to it since It wasn't a constant declaration.
Remove the let in line 19, erase line 26 and remove string concatenation to avoid repetition in line 28 it should work.
getInput.addEventListener('change', function(e){
inputed = e.target.value;
})
submit.addEventListener('click', function(){
output.innerHTML = camelise(inputed);
})

Creating and overwriting variables dynamic per user input

In the following code, the user is able to create variables utilizing the window object via an input type text element. I've written a function that console logs the name of the variable followed by the value of 0 in which the variable is initialized. This only occurs when the following key string literal, "-nr " precedes the desired name for the created variable.
The goal of this exercise is to increment any created variable value by 1 when the variable name is reentered into the input element. My attempt at doing so is by first writing the first function, varCreate to declare and initialize variables to 0, push them into an array, and console log the variable name followed by its value. The next function which I have a problem with (varPlus) is meant to add 1 to the value of each value when a particular name is entered into the input element however, it adds a few more than 1 even when I utilize a for loop to evaluate if the string literal value of the input element value property is equivalent to each element of the array varArray.
const _in = document.getElementById('in');
var varArray = [];
function varCreate(e) {
let _key = e.key;
if(_key === "Enter") {
if(_in.value.substring(0, 4) == "-nr ") {
window[_in.value.substring(4).replace(/\s/g, "_")] = 0;
varArray.push(_in.value.substring(4).replace(/\s/g, "_"));
console.log("var: " + varArray[varArray.length - 1] + "\nvalue: " + window[varArray[varArray.length - 1]]);
_in.value = "";
}
}
}
function varPlus(e1) {
let _key1 = e1.key;
if(_key1 === "Enter") {
checker = new RegExp(_in.value.replace(/\s/g, "_"), "gi");
for(var i = 0; i < varArray.length; i++) {
if(checker.test(varArray[i])) {
window[varArray[i]] += 1;
console.log("var: " + varArray[i] + "\nvalue: " + window[varArray[i]]);
}
}
delete window["checker"];
}
}
_in.addEventListener('keydown', varCreate);
_in.addEventListener('keydown', varPlus);
<input id='in' type='text' />
The end result when attempting to utilize varPlus is that it'll console log all variable names and values which somehow increment in value when it should only be console logging only the variable name which I'm trying to access via user input followed by its value. I would greatly appreciate it if anyone can shed some light on how I'm encountering these errors.
First of all it is really helpful if you try and make your code executable :)
Now for the user generated variables you could do something like this:
// DOM Elements
const input_variable = document.getElementById("input_variable");
const button_createVariable = document.getElementById("button_createVariable");
// Variables
let userVariables = {};
// Event listeners
window.addEventListener("keyup", event => {if(event.key == "Enter") parseVariable()});
button_createVariable.addEventListener("click", parseVariable);
function parseVariable() {
// Get the variable name and remove all spaces
let variableName = input_variable.value.substring(0, input_variable.value.indexOf("=")).replace(/\s+/g, '');
// Get the variable value and remove all spaces
let variableValue = input_variable.value.substring(input_variable.value.indexOf("=") + 1, input_variable.value.length).replace(/\s+/g, '');
// Add the variable to the object
userVariables[variableName] = variableValue;
// Clear the input
input_variable.value = "";
// Log the object into the console
console.log(userVariables);
}
<input id='input_variable' type='text'/><button id="button_createVariable">Create</button>
WARNING You of course still need to verify the user input. At this state it will accept everything as input. But now you can loop through the object and count up (or whatever) if already exists.
Oh yes btw, the syntax is simply: <name> = <value> eg. foo = 10.. unimportant detail :P

Can I access a variable's name as a string after passing it as an argument to another function?

Perhaps a slightly dim question but I'm trying to design something where I'm using javascript / jquery to change the layout of a website and I'd like to see the values of both a variable name and it's current value in another div.
I was just doing $test.append('example string' + exampleVar) a lot so I thought I would make a function called test().
So far I have:
function test (test) {
$test = $('.test');
$test.append(test+"<br>");
}
and then would pass it a variable name as an argument but I can't find any way of making it display the name as a string. I know about making it as an object to access the key and value but that doesn't really seem to work here?
Bit of a long-winded way to do it, but here's an example using an object:
function tester(options) {
var keys = Object.keys(options);
console.log(keys[0] + ': ' + options[keys[0]]); // test: My value
}
tester({ test: 'My value' });
DEMO
You could use a feature of javascript where obj["prop"] is the same as obj.prop
So instead of passing the variable as a variable and hoping to get its name, you use the name as a string to get the variable's value.
If you aren't using namespaces/variables and want to a global/root variable, pass window, eg:
function test(obj, val) {
console.log(val + ": " + obj[val]);
}
var val1 = 1;
var val2 = 2;
test(window, "val1");
test(window, "val2");
(obviously you don't get the name of 'obj' - but maybe it's a start)
if you only have root/global variables (as in the example provided in the question) then you could remove obj:
function test(val) {
console.log(val + ": " + window[val]);
}
var val1 = 1;
var val2 = 2;
test("val1");
test("val2");
It seems what you want to do something like this:
var argumentName = /([^\s,]+)/g;
// fu is a function
// fu.toString look like: function myFunction (param[, param]*) { code }
function getParamNames(fu) {
var f = fu.toString();
return f.slice(f.indexOf('(')+1,f.indexOf(')')).match(argumentName);
}
Then you might want to create an helper which will take every functions:
// I choosed the console as an output, but you can set anything
function displayParameters(fu) {
var _params = getParamNames(fu);
if(_params!==null) {
for(var i=0;i<_params.length; i++) {
console.log(_params[i]);
}
} else { console.log('no parameters'); }
}
And, you will need to call: displayParameters(test);
In a function you will be using a parameter. So in that case the "variable name" will always be the name of the parameter. In this case getting the string value will always be test. I would assume this is not what you want. You were correct that the best way to do this is to use an object and iterate over the key, values. You would do this like:
var test = {
"test" : "value"
};
function test (test) {
var k, $test = $('.test');
for(k in test){
$test.append(k + "<br>");
}
}
Also, I do not think there is a way to get the variable string name. So the above would be the way to get the name of a variable.

If Statement and Function (Basic) keep track on divs innerHTML?

Ok so I have a function set up already and it gets added in the div as numbers and letters
"var elCamLocation = $( "TEST" )"
Right!
Now I want to use a function to keep track on what is in the innerHTML of the "TEST" div and if the contents of the div changes to "0.00x2.00z0.00" then I want it to do something for example lets just say change url to keep it simple.
Here is what I have..
var Numbs = getElementById("TEST").innerHTML;
function TE()
{
if(Numbs = "0.00x2.00z0.00")
{
window.location.assign("http://google.com")
}
};
But it isn't working the window.location.assign("http://google.com")isn't triggering at all
any idea's?
= is for assignment. You should test for equality using the === operator.
if(Numbs === "0.00x2.00z0.00")
{
//etc.
}

javascript - basic onclick event question

I have a dynamic table populated from an array.
When building the table I have the following inside of a loop:
var tdRecord = trRecord.insertCell(trRow.cells.length);
var tdRecordId = dataArray[j][0];
tdRecord.onclick = function() { alert(tdRecordId); }
The problem is that alert will only alert the last set tdRecordId in the array. If I click on any of the other td rows they all alert the same number.
Anyone know how I can fix this?
This should work:
(function( id ) {
tdRecord.onclick = function() {
alert( id );
};
}( tdRecordID ));
You seem to be running your code inside a loop. In that case, all click handlers will point to the same tdRecordId value. If you want to capture the value of the current iteration, you have to use a function wrapper which will do that for you.
tdRecord.onclick = function () { alert('123'); };
You could use jQuery's data feature: http://jsfiddle.net/zRXS6/.
$(function(){
var number = 1;
var div1 = $('<div>a</div>');
div1.data('number', number);
div1.click(function() {window.alert($(this).data('number'))});
number = 2;
var div2 = $('<div>b</div>');
div2.data('number', number);
div2.click(function() {window.alert($(this).data('number'))});
$('body').append(div1).append(div2);
});
tdRecord.onclick = "alert(" + tdRecordId + ")";
Set it as a literal, rather then a dynamic. :)
In what you're doing, it will always refer to the variable, rather then the current value.
So as the variable changes, what the function alerts will change.
In this, it actually inserts the value, rather then the variable itself, so it will stay the same instead of changing.

Categories

Resources