I have 4 fields that can be filled in by end user. I would like to send the contents of these in an email but I don't want blank spaces in the email. What I am looking for is a way to ignore those empty field and only return those that have value. I have this piece of code but it only ever returns the last value :
var Textbox = Browser.getValue("myTextBox");
var Field1 = Browser.getValue("myField1");
var Field2 = Browser.getValue("myField2");
var Field3 = Browser.getValue("myField3");
var Field4 = Browser.getValue("myField4));
if (Field1 != "" ){
Browser.setValue(TextBox), (Field1 += "\n" + Textbox));
}
if (Field2 != ""){
Browser.setValue(Textbox), (Field2 += "\n" + Textbox));
}
if (Field3 != ""){
Browser.setValue(Textbox), (Field3 += "\n" + Textbox));
}
if (Field4 != ""){
Browser.setValue(Textbox), (Field4 += "\n" + Textbox));
}
Can anyone help me? I basically need that the Textbox after each statement in updated and used in the next using just Javascript.
Thank you in advance
You seem to be trying to do something like the following. It goes over all the controls in the form and gets all the values that aren't the initial value and writes them to the textarea on new lines.
<script>
// Collect all the non–default values in the form and write
// on new lines to the text area
function consolidateValues(form) {
// Get the textarea to write values to
var textArea = form.myTextBox;
// Get all controls in the form
var control, controls = form.elements;
// Variable to hold the consolidated value
var text = [];
// Collect all the values, skipping the first control
for (var i=1, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.value != control.defaultValue) {
text.push(control.value);
}
}
// write the value to the text area
textArea.value = text.join('\n');
// Stop form from submitting
return false;
}
</script>
<form onsubmit="return consolidateValues(this)">
<textarea name="myTextBox" size="100" rows="10"></textarea>
<br>
<input name="myField1">
<br>
<input name="myField2">
<br>
<input name="myField3">
<br>
<input name="myField4">
<br>
<input type="submit"> <input type="reset">
</form>
Related
I'm attempting a simple form validation where if the input field is empty, the user will see a message asking to fill out any fields that are empty.
I'm able to loop and find which fields are empty and display a message, but the message will only display the last input field that was looped. How do I get the message to display all input fields that are empty?
HTML:
<label>Name</label>
<input class=formInput" name="name" />
<label>Email</label>
<input class=formInput" name="email" />
<label>Message</label>
<textarea class=formInput" name="message" />
<span id="fail-message"></span>
JS:
let inputFields = document.getElementsByClassName('formInput');
for (var i = 0; i < inputFields.length; i++) {
if (inputFields[i].value === '') {
document.querySelector('#fail-message').innerHTML =
'Please fill out ' +
inputFields[i].getAttribute('name') +
' field(s)';
}
}
This currently outputs "Please fill out message field(s)"
Assuming all is empty, I'd like it to output "Please fill out name, email and message field(s)"
The code you have overwrites the innerHTML completely every time it finds an empty field. What you should do instead is keep an array of all the empty fields, then only write the innerHTML once after the loop, with the list of fields it found.
let inputFields = document.getElementsByClassName('formInput');
const emptyFieldNames = [];
for (var i = 0; i < inputFields.length; i++) {
if (inputFields[i].value === '') {
emptyFieldNames.push(inputFields[i].getAttribute('name'));
}
}
if (emptyFieldNames.length > 0) {
document.querySelector('#fail-message').innerHTML = 'Please fill out the following fields: ' + emptyFieldNames.join(', ');
}
You overwrite the innerHTML of the message span in every iteration. You should concatenate the new error to it or use separate spans.
You would have to build an array containing the fields name that are not valid ... right now, you "overwrite" the innerHTML of the #fail-message element with the latest field (aka, it is INSIDE your loop to be rewritten each time the condition is met in the loop).
Add the names of the field in array (do not rewrite the whole array) and then use "yourArray.join()" to output all the names in the innerHTML of the correct element, like you do inside your loop.
You are replacing the value in the span element everytime you go through the loop. So only the last empty form element will be shown as fail message. Instead, you have to concatenate each string and then show it together.
Here is the complete code that will work for you:
<html>
<head>
<script>
function myFunction() {
let inputFields = document.getElementsByClassName('formInput');
let message ='';
for (var i = 0; i < inputFields.length; i++) {
console.log(inputFields[i].value);
if (inputFields[i].value === '') {
message = message + inputFields[i].getAttribute('name') + ', ';
}
}
let n = message.lastIndexOf(",");
message = message.substring(0,n);
document.querySelector('#fail-message').innerHTML =
'Please fill out ' +
message +
' field(s)';
}
</script>
</head>
<body>
<label>Name</label>
<input class="formInput" name="name" />
<label>Email</label>
<input class="formInput" name="email" />
<label>Message</label>
<textarea class="formInput" name="message"> </textarea>
<button onclick="myFunction()">Submit</button>
<span id="fail-message"></span>
</body>
</html>
I want couple of things happen simultaneously on keypress() event, I got two pages, default.html where there is a input text box and another page.html with another input text box, Now what I need is that the moment a key is pressed to type a letter in to the input text box on default.html, keypress() fires (I need this on keypress, not on keyup or keydown) and the 'letter' is captured
var c = String.fromCharCode(e.which);
and at same time page is redirected
document.location= "page.html"; return false;
to 'page.html' showing the 'letter' in the input text field which was typed on previous page.
I have got incomplete code..
$(document).keypress(function(){
var c = String.fromCharCode(e.which);
document.location= "page.html";
return false;
}
});
don't know how to use var c here to show the value into the text field on next page(page.html).
javascript code on page.html...please correct and help with this code..
I picked it up from another post..I can see that the value typed on
default.html page shows up in the address bar of page.html
but does not show in the input text box, I know for sure I
am doing it incorrectly. The code is mentioned below.
input field on default.html - <input id="search" type="text" name="searchbar">
input field on page.html - <input id="search2" type="text" name="searchbar2">
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (document.location.search.split('?').length > 1) {
var params = document.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"];
$("#search1").html(data);
}
});
</script>
You can send the character in the query string like this:
document.location = "page.html?c=" + c;
Then, you can read it in JavaScript on page.html with
document.location.search
Have text box a and if it is filled in make sure text box b is filled in also when doing a submit and vice a versa if box b is filled in make sure a has data also in it. Can this be looped to check many text boxes that if the row a of text boxes has data check 2nd row of text boxes also have data in the ones that row a has. All the text boxes in row a don't need to be filled in. Thanks.
Your question is a bit hard to understand; it'd be helpful if you could better explain what you actually want. You don't need to have any conditions; just do the following:
<script>
function checkForm() {
if (!isEmpty(document.myForm.checkA.value)
&& !isEmpty(document.myForm.checkB.value))
return true;
else
return false;
}
function isEmpty(text) {
return text.length == 0 || !text.match(/[^\s]/))
}
</script>
<form name="myForm" onSubmit="return checkForm();">
<input name="textA" type="text" />
<input name="textB" type="text" />
<input type="submit" value="Submit!" />
</form>
This should be straightforward if you use an array to hold references to your text boxes. For example (off the top of my head so this is not going to be 100% right), let's say you have 5 across and 3 down:
var col = new Array(5);
var row = new Array(3);
col[0] = document.myForm.checkA1;
col[1] = document.myForm.checkB1;
// etc
row[0] = col;
col = new Array(5);
col[0] = document.myForm.checkA2;
col[1] = document.myForm.checkB2;
// etc
row[1] = col;
col = new Array(5);
col[0] = document.myForm.checkA3;
col[1] = document.myForm.checkB3;
// etc
row[2] = col;
You can now loop over the array in row[0] and if you find, e.g., that row[0][2] has text you just need to verify that row[1][2] also has text.
I am a beginner at Javascript, this is my first Javascript that isn't just 'cut/paste/hack'. I created an calculator that updates the output as input is typed, I can get all my 'answerboxes' to clear when the input box is blurred then focused, but if I backspace the value out of the input box the 'answerboxes' still show the 'answers' based on the last char. value that was backspaced.
In my 'validiateTheInput' funct. I can declare an 'if = "3"' to clear them and it works when a '3' is the value (which would not work in the end :) ), but I can't seem to catch it if the field appears blank do to user backspacing the value from the box.
Am I obsessing over something stupid, or am I just missing something?
Heres the whole thing (with some basic HTML ommitted):
There is also a bit of overkill in the validation function because I was experimenting with trying to catch the 'blank input' do to backspacing.
//jQuery keyup to grab input
$(document).ready(function() {
$('#totalFeet').keyup(function() {
validiateTheInput();
});
});
//clear calculated values
function clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField) {
answerbox.value = "";
answerbox1.value = "";
answerbox2.value = "";
totalFeetField.value = "";
};
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = document.getElementById('totalFeet');
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
// feel like I should be able to catch it here with the length prop.
if (totalFeetField.value.length == 0) {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// if input is usable, do the good stuff...
if (totalFeetField.value != "" && !isNaN(totalFeetField.value)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField.value)) {
alert("The Total Sq. Footage Value must be a number!")
document.getElementById('totalFeet').value = "";
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField.value == '3') {
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField.value == 'undefined' || totalFeetField.value === null || totalFeetField.value === '') clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 5.95; // set multiplier
document.getElementById('answerbox').value = answer.toFixed(2);
}
// calc the second box
function calcSecondBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 18.95; // set multiplier
document.getElementById('answerbox1').value = answer.toFixed(2);
}
// calc the third box
function calcThirdBox() {
var totalFeetField = document.getElementById('totalFeet');
var answer = totalFeetField.value * 25.95; // set multiplier
document.getElementById('answerbox2').value = answer.toFixed(2);
}
HTML:
<div id="calculator">
<form name="calculate">
<label for="total">Total Value to Calculate:</label>     
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes(totalFeet, answerbox, answerbox1, answerbox2);"><br /><br />
<label for="answerbox">Total Value X $5.95:    $</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"><br /><br />
<label for="answerbox1">Total Value X $18.95:   $</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"><br /><br />
<label for="answerbox2">Total Value X $25.95:   $</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15">
</form>
</div>
The problem is that you're not storing the element objects in variables - you're storing their values:
var answerbox = document.getElementById('answerbox').value;
var answerbox1 = document.getElementById('answerbox1').value;
var answerbox2 = document.getElementById('answerbox2').value;
...so later, when you call the following function, passing these variables as an argument:
clearBoxes(answerbox, answerbox1, answerbox2, totalFeetField);
...you're not passing the elements. You can fix it by removing .value off each line in your variable assignments.
Working demo: http://jsfiddle.net/AndyE/Mq6uN/
Side note and shameless plug: if you want something a little more robust than keyup for detecting input, check out this blog post.
You are passing the value of answerbox, answerbox1 etc to the clearBoxes function, not the elements themselves.
Here's a full jQuery approach:
//jQuery keyup to grab input
$(document).ready(function () {
$('input[id$=totalFeet]').keyup(function () {
validiateTheInput();
});
function clearBoxes() {
$('input[id$=answerbox]').val("");
$('input[id$=answerbox1]').val("");
$('input[id$=answerbox2]').val("");
}
//validate input, then go to callAll (calc the output and display it)
function validiateTheInput() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answerbox = $('input[id$=answerbox]').val();
var answerbox1 = $('input[id$=answerbox1]').val();
var answerbox2 = $('input[id$=answerbox2]').val();
// feel like I should be able to catch it here with the length prop.
if (totalFeetField == "") {
clearBoxes();
}
// if input is usable, do the good stuff...
if (totalFeetField != "" && !isNaN(totalFeetField)) {
callAll(); // call the function that calcs the boxes, etc.
}
// if input is NaN then alert and clear boxes (clears because a convenient blur event happens)
else if (isNaN(totalFeetField)) {
alert("The Total Sq. Footage Value must be a number!")
$('input[id$=totalFeet]').val("");
}
// clears the input box (I wish) if you backspace the val. to nothing
else if (totalFeetField == '3') {
clearBoxes();
}
// extra effort trying to catch that empty box :(
else if (typeof totalFeetField == 'undefined' || totalFeetField === null || totalFeetField === '')
clearBoxes();
}
//group all box calc functions for easy inline call
function callAll() {
calcFirstBox();
calcSecondBox();
calcThirdBox();
}
// calculate box fields based on input box
function calcFirstBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 5.95; // set multiplier
$('input[id$=answerbox]').val(answer.toFixed(2));
}
// calc the second box
function calcSecondBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 18.95; // set multiplier
$('input[id$=answerbox1]').val(answer.toFixed(2));
}
// calc the third box
function calcThirdBox() {
var totalFeetField = $('input[id$=totalFeet]').val();
var answer = totalFeetField * 25.95; // set multiplier
$('input[id$=answerbox2]').val(answer.toFixed(2));
}
});
Also, here's the HTML
<form name="calculate" action="">
<label for="total">Total Value to Calculate:</label>     
<input id="totalFeet" type="text" name="total" size="15" onfocus="clearBoxes();"/><br /><br />
<label for="answerbox">Total Value X $5.95:    $</label>
<input id="answerbox" onfocus="this.blur();" type="text" name="answerbox" size="15"/><br /><br />
<label for="answerbox1">Total Value X $18.95:   $</label>
<input id="answerbox1" onfocus="this.blur();" type="text" name="answerbox1" size="15"/><br /><br />
<label for="answerbox2">Total Value X $25.95:   $</label>
<input id="answerbox2" onfocus="this.blur();" type="text" name="answerbox2" size="15"/>
</form>
Sometimes mixing jQuery and plain javascript doesn't work too well. This code should work in clearing your textboxes when the first textbox is empty. It also works on number validation.
I have several textfields which will populate a text area.
I managed to populate it with a javascript function. On the onblur event of a textfield, the value of the textfield is passed and the textarea is field with this value.
However, my problem is the following:
If I modify a previously filled textfield, the textarea will simply append it again.
What I need is some functionality that if:
1: If I give focus to the textfield which is already been filled and I don't modify it, it will not be appended (I implemented this with an if statement and substring.
2: If I modify a previously filled textfield, the text area DOES NOT append it again at the end of the string BUT it replaces the part of the textarea with just that text field new value.
Take for instance the following 2 textfields:
<input type="text" id="txtName" name="txtName" />
<input type="text" id="txtSurname" name="txtSurname" />
If I fill up these textfields with John and Doe respectively, the textarea value will become:
txtName=John,txtSurname="Doe"
I managed to implement this.
What I need is that if I edit txtName from John to Alex, the textarea value will be as follows:
txtName=Alex,txtSurname=Doe
and not like is currently being displayed, i.e.
txtName=John,txtSurname=Doe,txtName=Alex
Should I achieve this by using an array which will store all the textfields values?
Any help would be greatly appreciated.
Many thanks in advance.
the following code should work for you. I have wrapped the textboxes inside a div. and also registered a onkeyup event on both the textboxes.
The javascript code iterates through each textboxe inside the div, and prints its name and value in the textarea.
HTML
<div id="textBoxContainer">
<input type="text" id="txtName" onkeyup="UpdateTextArea();" name="txtName" />
<input type="text" id="txtSurname" onkeyup="UpdateTextArea();" name="txtSurname" />
</div>
<textarea id="textAreaResult"></textarea>
Javascript
<script type="text/javascript">
function UpdateTextArea() {
var textBoxContainerDiv = document.getElementById("textBoxContainer");
var textboxes = textBoxContainerDiv.getElementsByTagName("input");
var finalResult = "";
var textAreaFinalResult = document.getElementById("textAreaResult");
for (var i = 0; i < textboxes.length; i++) {
finalResult = finalResult + textboxes[i].id + "=" + textboxes[i].value + ",";
}
textAreaFinalResult.value = finalResult;
}
</script>
Hope this Helps! :)
For the record, I feel like this code is an ugly hack, but it should do the trick...
var fieldName = "txtName"; //your field name
var newValue = "Alex"; //your new value
var value = document.getElementById("my-textarea").value;
value = "," + value; //add a comma so we can ensure we don't replace the wrong value where the fieldname is a substring of another fieldname
if(value.indexOf("," + fieldName + "=") > 0) //see if a value is already defined
{
var index = value.indexOf("," + fieldName + "=") + fieldName.length + 2;
var start = value.substring(0, index); //get the portion before the value
var end = value.substring(index); //get everything else
if(end.indexOf(",") > 0)
{
end = end.substring(end.indexOf(",")); //remove the value by reducing the end to the location of the next comma
}else{
end = ""; //if there isn't another comma it was the last value in the list, so set the new end to nothing
}
value = start + newValue + end;
value = value.substring(1); //remove the starting comma we gave it
document.getElementById("my-textarea").value = value;
}else{
//append it to the end as you are already doing
}