Javascript: Assigning User Input as a Variable - javascript

I'm just learning HTML, CSS, and Javascript and having a tough time grasping the JS. I've been working on this simple issue now for literally 6 hours. I've checked plenty of posts on SO, W3, re-read relevant chapters in Jon Duckett's book, and tried every combination I could think of in the code.
What I need to do is take a username from an input field and run it through a function to change it in some way. I've seen other's posts with similar questions but haven't been able to create a solution yet. The issue that keeps happening is that when I place what should be the user input back to the page it uses the actual words name.toUpperCase() rather than the value I've given the variable name. I tried converting the name to uppercase in its own statement and then assigning that a variable, but that didn't work either. It seems like my js is never giving "name" a value to begin with.
JS:
var name = document.getElementById('nameEntry');
var compliment = document.getElementById('compliment');
var input = document.getElementById('submitjs');
input.onclick = transformName;
function transformName () {
var elcompliment = document.getElementById('compliment');
elcompliment.textContent = 'name.toUpperCase( )' + ' YOU ROCK!';
};
HTML:
<div class="jsform">
<h2> Enter your name and see it change!</h2>
<input type="text" name="nameEntry" id="nameEntry" />
<input type="submit" name="submitjs" value="submit" id="submitjs"/>
<div>
<p id="compliment">Great Job!</p>
</div>
</div>

Since you are retrieving input value using element's id, there is no need for form.
function transformName () {
var name = document.getElementById('nameEntry').value;
var compliment = document.getElementById('compliment');
compliment.innerHTML = name.toUpperCase( ) + ' YOU ROCK!';
};
<div class="jsform">
<h2> Enter your name and see it change!</h2>
<input type="text" name="nameEntry" id="nameEntry" />
<input type="button" onclick="transformName()" value="Transform me"/>
<div>
<p id="compliment">Great Job!</p>
</div>
</div>

The name variable currently refers to DOM element. The value property returns the data entered in the input element.
The value property sets or returns the value of the value attribute of a text field.
var name = document.getElementById('nameEntry').value;
var compliment = document.getElementById('compliment');
var input = document.getElementById('submitjs');
input.onclick = transformName;
function transformName () {
var name = document.getElementById('nameEntry').value;
var elcompliment = document.getElementById('compliment');
elcompliment.innerHTML = name.toUpperCase()+' YOU ROCK!';
};
<div class="jsform">
<h2> Enter your name and see it change!</h2>
<input type="text" name="nameEntry" id="nameEntry" />
<input type="submit" name="submitjs" value="submit" id="submitjs" />
<div>
<p id="compliment">Great Job!</p>
</div>
</div>

Related

How to display values from google script object in html <p>?

HTML code
I want to display object values in this form in <p or easier solutions
<div class="control-form-id">
<label for="id">Id:</label>
<input type="text" name="id" id="id" required>
<button type="button" onclick="JSinHTML();" id="search" >Search</button>
</div>
<div class="serial">
<label for="serial">Serial number:</label>
<p id="serial">result</p>
</div>
<script>
function JSinHTML(){
let id_form ={}
id_form.input = document.getElementById("id").value
alert(id_form.input);
google.script.run.main(id_form);
document.getElementById("id").value = "";
}
</script>
GOOGLE SCRIPT code
function findId returns row number by typed id
function main(JSinHtml){
let numberRow = findId(JSinHtml.input);
Logger.log("input in main " + JSinHtml.input);
let toHtml = {};
toHtml.id = sheet_spis.getRange(numberRow, column_id).getValue();
toHtml.serial_number = sheet_spis.getRange(numberRow, column_serialnr).getValue();
toHtml.size = sheet_spis.getRange(numberRow, column_size).getValue();
toHtml.type = sheet_spis.getRange(numberRow, column_type).getValue();
Logger.log(toHtml); //I want to display separately this values in few <p>
}
In your situation, how about the following modification?
HTML & Javascript side:
From
google.script.run.main(id_form);
To:
google.script.run.withSuccessHandler(e => {
document.getElementById("serial").innerHTML = e.serial_number;
}).main(id_form);
Google Apps Script side:
From
Logger.log(toHtml); //I want to display separately this values in few <p>
To:
Logger.log(toHtml);
return toHtml;
Note:
From <p id="serial">result</p>, I guessed that you might have wanted to put the value of serial_number. So, I proposed it. If you want to show the whole object of toHtml, please modify document.getElementById("serial").innerHTML = e.serial_number; to document.getElementById("serial").innerHTML = JSON.stringify(e);.
Reference:
withSuccessHandler(function)

Is there a way to get a value of a javascript variable in a HTML element?

I know this sounds stupid and pointless but I am trying to make a website which finds an email address from the entered initial and surname of a person for my workplace. It just has 2 text input fields, one for the initial and one for the surname. My JavaScript joins these with the layout of the email and sets it as the variable "email". How would I set this to a button's href tag using "mailto:"? I tried using onmouseover="this.href = 'mailto:'+email;" yet it just returns undefined;‎
function buildEmail() {
var initial = document.getElementById("initial").value;
var surname = document.getElementById("surname").value;
var email = initial + surname + "#[emaildomain.com]"
}
<h1>Enter the first initial</h1>
<br>
<input type="text" id="initial" />
<br>
<h2>Enter the surname</h2>
<br>
<input type="text" id="surname" />
<br>
<button>
<a onClick=myFunction() onmouseover="this.href = 'mailto:'+email">Click to send email</a>
</button>
Edited after code was provided by OP.
You're running into conflicts because email is both the name of your element and the name of your variable. Try changing one of them.
Also, your email variable is going out of scope once the buildEmail function ends (outside the function, that variable doesn't exist). One commenter recommended setting a property on window, which would be accessible globally.
The issue you have is you have the buildEmail which is not called. And the fact when it is called, the variable email is a scoped to the function so it is not global.
Just call the function onmousedown and set the href so the click will cause the mailto to fire.
function buildEmail(event) {
var initial = document.getElementById("initial").value;
var surname = document.getElementById("surname").value;
var email = initial + surname + "#example.com"
event.target.href = "mailto:" + email;
}
<center><h1>Enter the first initial</h1>
<br>
<input type="text" id="initial" />
<br>
<h2>Enter the surname</h2>
<br>
<input type="text" id="surname" />
<br>
<button><a onmousedown="buildEmail(event)">Click to send email</a></button>
The scope of things are very important.. the variables you declare in buildEmail are only "seen" by that function.. if you want those variables to be accessible to another function.. in browsers.. window can be used
function buildEmail() {
window.initial = document.getElementById("initial").value;
window.surname = document.getElementById("surname").value;
window.email = initial + surname + "#[emaildomain.com]"
}

Need help using increments and displaying in a textbox

We need to have a textbox where you enter a number, hit a button, and it increments by 1, while staying in the same text box. Here is the code I have so far:
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
JavaScript:
function btnIncrement_onclick() {
// get textbox and assign to a variable
var countTextbox = document.getElementById("txtCounter");
var txtCounterData = txtCounter.value;
var countTextbox.value = 0++;
}
If someone could explain to me how to do it not just give me the answer. I don't know why I'm having such a hard time with this.
Try the following simple code :
function btnIncrement_onclick()
{
//asign the textbox to variable
var textbox = document.getElementById("txtCounter");
//Get the value of textbox and add 1 then update the textbox
textbox.value = parseInt(textbox.value)+1;
}
<form action=#>
<p>
Current Count...<input type="text" id="txtCounter" value="0">
</p>
<p>
<input type="button" value="Increment Count" id="btnIncrement" onclick="btnIncrement_onclick()">
<input type="reset">
</p>
</form>
<noscript>This website requires JavaScript to be enabled.</noscript>
Hope this helps.
In your HTML:
In your html you had a onclick="btnIncrement_onclick()" and that means every click will triggers your function.
In your JS:
function btnIncrement_onclick() {
// Named as countTextbox you input. sou we can use it later.
var countTextbox = document.getElementById("txtCounter");
// Get the current value attribute of it, initialy 0.
var txtCounterData = txtCounter.value;
// The line above is not being used. but you can check it with a console.log like this:
console.log(txtCounterData);
// Now you are calling again your input and changing his value attribute. this ++ means a increment. so we are increasing +1;
countTextbox.value++;
}
You should read more about increment and operators and DOM (the way whe select the tag by id, and again selected his attribute).
Sorry didn't found a good source in english.

multiple div with same template

I have a 'users page'. I would like to give a textbox for entering the no. of users. On click of submit 'n' no of user forms need to be presented to user.
User1
first name -
last name -
User2
first name -
last name -
.
.
.
UserN
first name -
last name -
I don't know the value of 'N' upfront. So it won't be a good idea to write multiple 'divs' in my html.
Requirement:Rather I want to have a user template div. And copy the template 'n' times depending on the value of 'n' in the textbox. But I would also want all the 'divs' to have different ids like 'user1', 'user2' etc.
I cannot figure out a way to do this apart from populating my html with too many 'divs'. Would need help achiving the Requirement specified.
Looking for a template like:-
<div id="user-template" class="hidden">
<label class="lbl"><b>Handle:</b></label><input type="text" id="first_name" value=""/>
</div>
And wanted to have id="user-template" change for all new divs.
You can try something like this:
You can make a template and append it to the DOM for the number entered in the input field.
$(document).ready(function() {
$("#createForms").click(function() {
var numOfForms = $("#numOfForms").val();
var template = $('#hidden-template').html();
for (var i = 0; i < numOfForms; i++) {
$('#targetDiv').append("<p>User" + (i + 1) + ":</p>");
$('#targetDiv').append(template);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="numOfForms"></input>
<input type="button" id="createForms" value="Get Fields"></input>
<div id="targetDiv"></div>
<script id="hidden-template" type="text/x-custom-template">
<div id="user-template" class="hidden">
<p>First Name:
<input type="text" name="firstName"></input>
</p>
<p>Last Name:
<input type="text" name="lastName"></input>
</p>
<br>
</div>
</script>
A simple way is to write a function that takes the n value and returns the actual dom that you can append to some parent element on your page. A simple example below:
function createNDivs(n) {
if(!n) return;
var fragment =document.createDocumentFragment();
for(var i=0;i<n;i++) {
var div = document.createElement('div');
fragment.appendChild(div);
}
return fragment;
}

Expanding HTML forms using Javascript

I have a simple HTML form that asks a user to input their name, SKU, quantity, and comments. This is for a simple inventory request system.
<html>
<body>
<form id="myForm" method="post">
<input type="submit">
<br>Name: <input type="text" name="form[name]">
<br>SKU: <input type="text" name="form[SKU1]">
<br>Quantity: <input type="text" name="form[quantity1]">
<br>Comment: <input type="text" name="form[comment1]">
</form>
Add item
<script>
var num = 2; //The first option to be added is number 2
function addOption() {
var theForm = document.getElementById("myForm");
var newOption = document.createElement("input");
newOption.name = "form[SKU"+num+"]"; // form[varX]
newOption.type = "text";
theForm.appendChild(newOption); //How can I add a newline here?
optionNumber++;
}
</script>
</body>
</html>
Currently I can only get it working where it will add a single form value. I would like to recreate the entire myForm except for the name field with a single click.
Your post is very old, so presumably you've found an answer by now. However, there are some things amiss with your code.
In the JavaScript code you have
var num = 2;
This is the number that is incremented to keep track of how many "line-items" you will have on the form. In the function addOption(), though, instead of incrementing num you have
optionNumber++;
You never use optionNumber anywhere else. Your code works once, when you add the first item, but since you increment the wrong variable, you are effectively always adding option 2.
Oh, and adding the newline: you need to append a <br> element.

Categories

Resources