Camelize function output not displayed, no error thrown - javascript

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);
})

Related

Why does innerHTML work in this one instance, but not in this other one?

So I'm learning about asynchronous programming through callbacks and wrote this code that calculates the next number in a Fibonacci sequence, when I then had trouble setting the value of an HTML element with innerHTML. The text simply would not show up on the screen even though I thought I did everything right. This is the code here that doesn't work:
window.onload = function() {
const print = (fibSeq) => {
let text = document.getElementById('text').innerHTML
text = fibSeq
}
const calcFib = (callback) => {
let seq = [0, 1]
seq.push(seq[seq.length - 1] + seq[seq.length - 2])
callback(seq)
}
calcFib(print)
}
I was confused, but then I started tweaking it and found if I just moved innerHTML down one line, the code worked. The code below shows the change, but I don't understand why the code above doesn't work when this one does.
The 'text' variable is set to the element Id and the innerHTML in both examples, yet it only works in one of them. Does anyone understand why? I don't want to move past this without understanding how exactly it was fixed.
window.onload = function() {
const print = (fibSeq) => {
let text = document.getElementById('text')
text.innerHTML = fibSeq
}
const calcFib = (callback) => {
let seq = [0, 1]
seq.push(seq[seq.length - 1] + seq[seq.length - 2])
callback(seq)
}
calcFib(print)
}
Let's imagine we have some html that looks like this:
<div id="text">hello world</div>
now, let's look at your two pieces of code
// the value of our variable 'text' is set to 'hello world'
let text = document.getElementById('text').innerHTML
// now the value of our variable 'text' is changed to the value of 'fibSeq'
text = fibSeq
In the above code block, you are never setting the value of innerHTML, just reading it to get the initial value of text. Now, your second, working code block:
// the value of our variable 'text' is set to our div with an id of 'text' (our dom node)
let text = document.getElementById('text')
// now we update the innerHTML of our dom node to the value of 'fibSeq'
text.innerHTML = fibSeq
Hope that clears things up :)
document.getElementById('text') is an object which passes by reference, so text is the object in the second example.
document.getElementById('text').innerHTML is a string which passes by value, so text is a copy of the data in the first example.
The problem is not about "innerHTML", but rather the difference between a DOM element and the content of the element.
For the code:
let text = document.getElementById('text').innerHTML
text = fibSeq
It means to assign the content of element 'text' to a variable 'text' (the two 'text' are different things), then the variable 'text' is re-assigned to another value from function parameter 'fibSeq'.
For your second code:
let text = document.getElementById('text')
text.innerHTML = fibSeq
It means to designate a variable 'text' to a DOM element 'text' (the two 'text' are the same thing - an element), then pass the value of the function parameter 'fibSeq' to the element. It also takes another important step - it renders the HTML tags in the string of 'fibSeq'.
Hope it helps.

jquery make alert equal to an array of names

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);
}
});

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

How to capture old value and set it back on cancel using javascript

I have a text field from which I am calling a function on onChange event. I am throwing a confirm window here when the value in that textfield is changed. If cancel is clicked( in confirm window), the old value must get set back into the text field. If proceed or ok is clicked, the new value should be retained.
I have been trying this for a long time but am unable to retain the old value.
Eg:
Before onchange, val in text field ='first';
onChange event, val changed to 'second', confirm window opens, if ok selected text field should have second and if cancel is selected 'first' should be present in the text field.
function onChangeOfValue(input){
//var oldValue = document.getElementById(input).value;
document.getElementById(input).onchange = function(){
var newValue = this.value;
alert("newVal is--->"+newValue);
if(document.getElementById(input) != null && document.getElementById(input) != ''
&& !confirm("Do you want to continue?")){
// this.input=oldValue;
return false;
}
}
}
Note that form controls have a defaultValue property that is the default value (surprisingly). You can use this property to store the previous value of the input, or to return the value to the previous value.
So putting together the suggestions you've been given, the following function is passed a reference to the element and asks the user if they want to keep the current value. If they answer yes, then the defaultValue of the input is set to the current value. If the users says no (i.e. cancel), then the value is reset to the defaultValue.
Note that this approach will overwrite the original value of the input, so if you reset the form, the input's value will be reset to the current defaultValue.
<script>
function onChangeOfValue(element) {
var oldValue = element.defaultValue;
var newValue = element.value;
if (window.confirm('do you really want to change the value to ' + newValue + '?')) {
element.defaultValue = newValue;
} else {
element.value = element.defaultValue;
}
}
</script>
<input onchange="onChangeOfValue(this);">
This approach will work for any number of inputs in the same page and form.
I would use a closure to keep track of the last value:
(function(){
var oldValue = document.getElementById(input).value;
document.getElementById(input).onchange = function(){
var newValue = this.value;
alert("newVal is--->"+newValue);
if(document.getElementById(input) != null
&& document.getElementById(input) != ''
&& !confirm("Do you want to continue?")){
this.value = oldValue;
return false;
} else {
oldValue = this.value;
}
};
})();

OnBlur Assignment to Function in Javascript

I have a code like this;
<script type="text/javascript">
var ID= document.getElementById('customfield_10033');
var IDNumber= document.getElementById('customfield_10033').value;
ID.onblur=function(IDNumber)
{
if ((IDNumber!="") && (IDNumber.length!=11)){
alert("Your ID number should 11 digits.");
}
But when i enter ID number with 11 digits, shows me alert function. But it shouldn't.
I think i doing wrong assign Onblur property to function.. ID.onblur=function(IDNumber)
How can i fix this code?
You define IDNumber when you assign the event handler (so it will probably be holding whatever you set the default value of the field to be), but you almost certainly want to define it when the blur event occurs.
Move
var IDNumber= document.getElementById('customfield_10033').value;
Inside your event handler function.
(Since you already have a reference to the element it would be more efficient to do var IDNumber = ID.value; too)
You should have something like this instead:
ID.onblur = function(IDNumber)
{
var IDNumber = ID.value;
if (IDNumber !== "" && IDNumber.length !== 11)
{
alert("Your ID number should 11 digits.");
}
}
By assigning the value into variable, you place static data, not a pointer to the value so you have to read the "live" value every time.
You forgot to close the if-statement. Try this:
if ((IDNumber!="") && (IDNumber.length!=11)) {
alert("Your ID number should 11 digits.");
}
Regards,
Thomas

Categories

Resources