I have a form with many buttons all of which print a value in the relevant textbox. the problem is the value is a fairly long text string and I would like to create a shorter variable eg. 'text' and make that variable equal to eg. 'some long sentence that I only want to type once'. any idea how I can edit this code to make this possible
function setInput(button, setValue) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = setValue;
<html>
<input type='submit' name='submit_a' value="a"
onclick="setInput(this,'make_me_a_variable'); return false;">
</html>
var textLookup = {
btnName1: "Long text",
btnName2: "Longer text"
};
// inside your function
var buttonText = ...,
inputText = textLookup[buttonText];
// do stuff with inputText;
Instead of defining the event handler in the HTML code, you could also create the event handler with javascript. You need to do that in another event handler for document.onload. When you do it earlier, the input HTML element might not have been parsed and created yet, so no event handler for it can be added.
<script>
// store your text in a variable
var inputText = 'make_me_a_variable';
// define some code which is executed when the page is loaded:
document.addEventListener("load",function(event){
// get the input by the id property I added to the HTML below.
var input = document.getElementById('submit_a');
// add an event handler for the click event (replaces the onclick HTML property)
input.addEventListener("click",function(event) {
setInput(this, inputText);
return false;
});
});
</script>
[...]
<input id="submit_a" type='submit' name='submit_a' value="a" >
You can create a variable and assign your long text to the variable and use it where ever you want.
Modified code
var longText = 'long text here'.
function setInput(button) {
var buttonVal = button.value,
textbox = document.getElementById('input_' + buttonVal);
textbox.value = longText ;
}
Html:
<input type='submit' name='submit_a' value="a"
onclick="setInput(this); return false;">
Related
My starting html looks like this:
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
and i have a variable that captures the html:
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
Then I have an onchange operator that performs a couple functions when the first row has text in it. the .onchange is picked up fine the first time and the subsequent functions are run. I end up with an additional row:
for (n = 1; n < inputLength+1 ; ++n) {
var test2 = document.getElementById(dude+n);
test2.onchange = forFunction
}
function forFunction() {
for (m = 1; m < inputLength+1 ; ++m) {
var test = document.getElementById(dude+m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder="+dude+(m+1)+" id="+dude+(m+1)+" name="+dude+(m+1)+"><br>";
document.getElementById('group_names').innerHTML = updateHTML(txt);
//function updateHTML(txt)
}
}
}
var html = "<label> Names: </label><br><input type=\"text\" class=\"form-control name\" placeholder=\"name1\" id=\"name1\" name =\"name1\"><br>"
function updateHTML(txt) {
html = html + txt;
return html;
}
The issue is that after all that completes i end up with two input rows as desired: name1 and name2. However, when i enter text in those fields for a second time, the .onchange is not picked up. but the elements are there in the html when i inspect and view the html.
Also, when i
console.log(inputFormDiv.getElementsByTagName('input').length);
the length of the inputs increases from 1 to 2 after i first run functions (upon the first time i change the value in my input field) so that is getting recognized correctly, just not the .onchange.
thoughts?
The onchange will only work if added to the attribute on the html and the user clicks out of a textbox e.g:
<input onchange="forFunction()" type="text" class="form-control name" placeholder="name1" id="name1" name ="name1">
To add the onchange event in JavaScript code. Add the change event to the addEventListener e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('change', forFunction, false)
However if you want the event to fire whilst the user is types a key then use the keypress event. e.g:
var test2 = document.getElementById(dude+n);
test2.addEventListener('keypress', forFunction, false
A basic example: https://jsfiddle.net/xrL6y012/1/
Instead of .innerHTML = html + text do .insertAdjacentHTML('beforeend', text), that way you keep the original html (and events binding).
Edit: https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentHTML
I had the same problem, it seems like modifying the HTML will never work, regardless of how you do it (.innerHTML or .insertAdjacentHTML()).
The only way that worked for me is to append a child instead of editing the HTML, like so:
const span = document.createElement('span');
span.innerHTML = 'text and <b> html stuff </b>';
initialElement.appendChild(span);
And if you actually need to insert just pure text, then this works:
initialElement.append('just text');
Hope that helps.
I want to get the value of a text input. I would like to do this by using id and getElementById :
here HTML code :
<form>
<fieldset>
<legend>Input ordinate :</legend>
<input type="text" id="ordinateId" name="input"/>
<input type="button" id="startbuttonId" value="Start particle"/>
</fieldset>
</form>
and Javascript :
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
var value = document.getElementById("ordinateId").value;
console.log(value);
button.onclick = function() {
console.log(value);
}
</script>
but into the console, nothing appears for value. Where is the problem ?
Thanks
The problem is that you are checking for the input's value before it is set(on document load). Just move the variable declaration within the click function like so:
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
JSFiddle
You need to get the value again when the event fires. Just move your var value
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
With your current script you are assigning value only once, which I am assuming is an empty string. You need to put the assignment inside the function so it gets the current value of the input when it is clicked.
<script type="text/javascript">
var button = document.getElementById("startbuttonId");
button.onclick = function() {
var value = document.getElementById("ordinateId").value;
console.log(value);
}
</script>
I have project for my php class where I have to enter First name, last name, email, and phone number and output returns the exact values. (but I will only put the 'first name' code for editing).
I have a function in of html that gets called from 'onsubmit' inside
<script>
function validate3(){
alert ("1validate3 called");
var elemFnameSpan = document.createElement("span");
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
elemFnameBrParent.insertBefore(elemFnameSpan,elemFnameBr);
elemFnameSpan.id = "idFnameErr";
elemFnameSpan.style.color="red";
elemFnameSpan.innerHTML="";
var elemFname=document.getElementById("idFname");
var elemFnameValue = elemFname.value;
var errorFlag=false;
if (elemFnameValue == null || elemFnameValue ==""){
elemFnameSpan.innerHTML ="required field";
return false;
}
else{
elemFnameSpan.innerHTML="";
}
if(errorFlag==true){
return false;
}
return true;
}
</script>
<form onsubmit="return validate3()" action = "ContactInfo.php">
First Name<span style="color:red">*</span>
<input type="text" name = "Fname" size = "10" id="idFname" onchange="eraseFnameErr()"/>
<br id="idFnameBr" >
<input type="submit" name="submit" value="Submit" /><br>
The function creates a node 'elemFnameSpan' before of id 'idFnameBr'. If the textinput for first name is empty, elemFnameSpan.innerHTML outputs "required field", and false on 'onsubmit' . My problem is that the output doesn't refresh everytime the submit button is called, so 'required field' outputs get extended next to each other.
I am having difficulty resolving this situation and tried to remove the previous child node everytime the new function is called, but that didn't work either for me yet.
Once you append any DOM node, it never removed unless you do it explicitly.
I can suggest two ways to achieve your goal.
First, you can save the node in a global variable.
var elemFnameSpan;
function validate3(){
alert ("1validate3 called");
if (!elemFnameSpan) {
elemFnameSpan = document.createElement("span");
}
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
Or, set id to elemFnameSpan and find it every time the form is submitted.
function validate3(){
alert ("1validate3 called");
var elemFnameSpan = document.getElementById('whatever_you_want');
if (!elemFnameSpan) {
elemFnameSpan = document.createElement("span");
elemFnameSpan.setAttribute('id', 'whatever_you_want');
}
var elemFnameBr = document.getElementById("idFnameBr");
var elemFnameBrParent = elemFnameBr.parentNode;
You need to check if you have already created the span element, if you have grab it by using getElementById, if you havent then create it.
//This is an "if" shortcut, if getElementById returns null
//the code in right side will execute and the return value
//will be put in eleFnameSpan
var eleFnameSpan = document.getElementById("idFnameErr") || document.createElement("span");
var elemFnameBr = document.getElementById("idFnameBr");
//Check parentNode on elemFnameBr if it is null/undefined then it hasnt
//been added to the dom yet
if(!elemFnameBr.parentNode){
//No need to store the parentNode (unless needing it else were in code)
elemFnameBr.parentNode.insertBefore(elemFnameSpan,elemFnameBr);
elemFnameSpan.id = "idFnameErr";
elemFnameSpan.style.color="red";
elemFnameSpan.innerHTML="";
}
The rest of the code can stay the same
What is happening is you are just creating a new span on each click, and since on each click you add a new span and edit that one instead of the original one you keep getting new message stacked next to each other.
Given this html...
<input id="txtbox-page" maxlength="4" />
how can I create a button or a link that executes a javascript function, where its parameter is the input box value?
I have to call a function, that is already in production, that has this format:
javascript:pageClient('?p=2');
where the number 2, has to be the value of the input box.
HTML
<button id="pageClientSubmitter">Click me</button>
JS
var pageClientSubmitter = document.getElementById('pageClientSubmitter');
pageClientSubmitter.onclick = function () {
var val = document.getElementById('txtbox-page').value;
pageClient('?p=' + val);
}
Demo
HTML:
<a id="mylink" href="foo.bar">Link</a>
JS:
var box = document.getElementById('txtbox-page');
document.getElementById('mylink').addEventListener('click', function(){
// Use `box` here
pageClient('?p=' + +box.value);
}, false);
The second + is optional. I used it to convert to number in order to avoid injection attacks.
You could do something along these lines:
function GetTxtBoxValue() {
var txtBoxPage = document.getElementByID("txtbox-page");
pageClient('?p='+txtBoxPage.value);
}
Then bind that function to your form submission.
I am brand new in WebDevelopment and I came across the following issue.
I have an html file where a textbox is defined as well as a "View all Contents" button
The user can enter a value in the textbox and submit the data
Then repeat this action multiple times
Every time a new value is entered this value should be stored to a
Javascript array
The user will be able to view the contents of the Javascript array
when clicking on the button "View all Contents".
So my problem is how these values are stored dynamically in Javascript and printed when the user is finished.
Your answer is very much appreciated.
Best Regards
Olga
A very trivial example: http://jsfiddle.net/pimvdb/unEMp/.
<input type="text" id="textbox">
<br>
<input type="button" id="add" value="Add">
<br>
<input type="button" id="view" value="View all Contents">
with:
var arr = []; // the array
document.getElementById('add').onclick = function() {
arr.push(document.getElementById('textbox').value); // add textbox value to array
document.getElementById('textbox').value = ''; // clear textbox value
};
document.getElementById('view').onclick = function() {
alert(arr.join(', ')); // alert array contents as a string; elements are delimited by ', '
};
First you'll want to create your array in the global scope - this means outside of a method body, somewhere in the <script></script> body:
var myArray = new Array();
Next, you'll want to append the array with a new value each time the user clicks a button:
function myButtonClick(){
var myTb = document.getElementById("textBox1");
myArray.push(myTb.value);
myTb.value = ""; // reset the textbox
}
Next, you'll want another button handler for the click on "View All":
function myViewAllButtonClick(){
// will create a string of myArray's values, seperated by new line character
var msg = myArray.join("\n");
// will show the user all of the values in a modal alert
alert(msg);
}
Your HTML might look like:
<input type="text" id="textBox1" />
<input type="button" id="button1" value="Add Value" onclick="myButtonClick();"/>
<input type="button" id="button2" value="Show All" onclick="myViewAllButtonClick();"/>
When you get the hang of things, you can get rid of the "Add Value" button all together and use:
<input type="text" id="textBox1" onchange="onTextChanged(this)"/>
With a handler like:
function onTextChanged(e){
if(e.value == "") return;
myArray.push(e.value);
e.value = "";
}
The onTextChanged handler will fire when the user changes text in the textbox (it won't fire though until the textbox loses focus, which may make it bad for this example, but still a good JS skill to learn/understand).
Happy coding - good luck!
B
JavaScript array could be dynamicaly changed:
var array = [];
function foo() {
array.push('foo');
}
function boo() {
array.push('boo');
}
i put together a small example: http://jsbin.com/izumeb/3
<p><input type="text" id="txt"></input><button onclick="addToAll();">add to selection</button></p>
<p><button onclick="showAll();">show all</button></p>
<p id="all"></p>
and JS
<script>
var values = [];
function addToAll() {
var txt = document.getElementById("txt");
values.push(txt.value);
txt.value = "";
}
function showAll() {
var all = document.getElementById("all");
var str = "";
for (var i=0;i<values.length;++i) {
str += values[i] + "<br/>";
}
all.innerHTML = str;
}
</script>