I'm using a function that if the user left any input empty then it should print an error msg, otherwise it should be submitted.
I was testing this below code for the name input only and it works that if I left the input empty it will show an error, otherwise it will do submit.
let submitFORM = document.forms[0][4].addEventListener("click", val);
let name = document.forms[0][0];
let error = document.getElementById("error");
function val() {
if (!name.value) {
error.innerHTML = "Error";
return false;
} else {
document.forms[0].submit();
}
}
But since I have multiple inputs, I would like to check on all of them, what I did here I add a for loop and store all the messages that like if the user left three inputs empty then it would print three statements of the error ..
Otherwise, if the user filled all the inputs, then it should submit it ..
but the issue is I miss something that because if I fill one of the inputs only it will do submit! what should I do to stop doing submitting unless all the values aren't empty?
let submitFORM = document.forms[0][4].addEventListener("click", val);
let name = document.forms[0][0];
let error = document.getElementById("error");
function val() {
let allinputs = document.forms[0].querySelectorAll('input');
let item = "";
let i;
let stat = true;
for(i = 0; i < t.length - 1; i++){
if(!t[i].value){
item += "your " + t[i].getAttribute('name') + " shouldn't be blank !";
stat = false;
}else{
stat = true;
document.forms[0].submit();
}
}
error.innerHTML = item;
}
It's because, you are calling submit inside for loop, submit will be called on first valid input.
You can refactor like this:
const invalidInputs = allInputs.map(input => !input.value);
invalidInputs.forEach((input) => {
item += "your " + input.getAttribute('name') + " shouldn't be blank !";
});
if (invalidInputs.length === 0) {
document.forms[0].submit();
}
HTML has the required attribute to accomplish this. If you set any input to be required, modern browsers won't let you submit the form if those fields are empty.
<input type="text" name="name" required="required">
Is there any specific reason why you want to do it from javascript?
If you still want to use your solution, you need to adjust the "submit" part to be out of the loop, something like this:
let submitFORM = document.forms[0][4].addEventListener("click", val);
let name = document.forms[0][0];
let error = document.getElementById("error");
function val() {
let allinputs = document.forms[0].querySelectorAll('input');
let item = "";
let shouldSubmit = true;
for(let i = 0; i < allinputs.length - 1; i++){
if(!allinputs[i].value){
item += "your " + allinputs[i].getAttribute('name') + " shouldn't be blank !";
shouldSubmit = false;
}
}
if (shouldSubmit) {
document.forms[0].submit();
}
error.innerHTML = item;
}
From what i see, you submit too soon, you should first test every input in your for loop, set a boolean to false as soon as you find a missing value. And only then, outside the loop, check if this boolean is set to true and submit if it is.
Maybe try to check all the input fields in a single if statement.
if(!t[0].value && !t[1].value && !t[2].value){}
Something like this
Related
Trying to make a web page that will get each letter a user inputs and output it in a phonetic alphabet. For example (user types: Hello)(Output: Hotel , Echo , Lima, Lima, Oscar). This is what I have so far just need some guidance on how to get the value of each letter and compare it to like an Array to get the output.
//define UI variables
const userInput = document.querySelector('#input');
const phoneticAlphabet = ["Alpha"," Bravo","Charlie"];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
console.log(userInput.value);
if (userInput.value === '') {
alert('Add Input');
}
e.preventDefault();
}
I presume that you would like to replace non-convertible characters from the input. For the same, I am using regular expression. I have also added the response in a "p" tag. And the code runs on clicking "Submit".
Update:
Extended my array for all alphabets :)
Update 2:
Thanks #CharlieBatista for pointing out. Now, the input accepts uppercase characters as well.
//define UI variables
const form = document.phoneticForm;
const userInput = document.querySelector('#input');
const output = document.querySelector('#output');
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
//load all event listeners
loadEventListeners();
function loadEventListeners() {
//add submit event
form.addEventListener('submit', submitInput);
}
//submit user input
function submitInput(e) {
e.preventDefault();
var value = userInput.value;
if (value === '') {
alert('Add Input');
} else {
value = value.replace(/[^a-zA-Z]/gi,'');
userInput.value = value;
value = value.toLowerCase();
var outputArr = [];
for(var i = 0; i < value.length; i++){
outputArr.push(phoneticAlphabet[value.charCodeAt(i)-97]);
}
output.innerHTML = outputArr.join(', ');
}
}
<form name="phoneticForm">
<input type="text" id="input">
<input type="submit">
</form>
<p id="output"></p>
You can use the key property on the keydown event of the field to get the character that was pressed.
Then check if the key is a printable key using key.length === 1 (see this answer).
If the key is printable, convert it to uppercase, then to its character code using String.prototype.charCodeAt() and then subtract 65 from it (character A). This will give you the index in your array.
If this index is within the bounds of the array, access the array and print the character.
const phoneticAlphabet = ['Alpha','Bravo','Charlie','Delta','Echo','Foxtrot','Golf','Hotel','India','Juliet','Kilo','Lima','Mike','November','Oscar','Papa','Quebec','Romeo','Sierra','Tango','Uniform','Victor','Whiskey','X-ray','Yankee','Zulu'];
document.querySelector('#input').addEventListener('keydown', e => {
const isPrintable = e.key.length === 1;
console.clear();
if (isPrintable) {
const idx = e.key.toUpperCase().charCodeAt(0) - 65;
if (idx >= 0 && idx < phoneticAlphabet.length) {
const phoneme = phoneticAlphabet[idx];
console.log(phoneme);
}
}
});
<input type="text" id="input">
I'm trying to take user input from within an HTML file, convert it, and output it back to the page using <input> rather than prompt.
Here's what I have so far.
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
btext
}
I've tested this using the prompt command and it works, but when I go to use
document.getElementById
OR
document.form_name._input_name.value
and then return that neither seems to work.
Can anyone advise?
If you're triggering this function from a DOM event you have to return btext.
function bhedTester() {
var alpha = "ABC";
var bhed = "JYI";
var btext = "";
var i = 0;
while (i < norm.length) {
var ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext
}
To write to a div you will have to do:
document.getElementById("yourDiv").innerHTML= bhedTester();
And after that you will need to return a string from the function you wrote.
Right now it is not returning anything.
So your code should look like:
function bhedTester() {
alpha = "ABC";
bhed = "JYI";
btext = "";
i = 0;
while (i < norm.length) {
ind = alphabet.indexOf(norm.charAt(i));
btext = btext + bhed.charAt(ind);
i++;
}
return btext;
}
Since I don't know your norm and alphabet can't give you an exact solution.
You need to listen for when either the text is changed in the input or when the button is clicked. Your code just runs when the page loads. It does not magically run when you type text. You need to alter it to run when the user changes the text. So you need to use addEventListener to bind the event.
//bind the change event
document.getElementById("foo").addEventListener("change", function(){
var textbox = this, //reference the textbox
value = this.value; //get what the user typed
document.getElementById("bar").innerHTML = value; //set the value
});
<input type="text" id="foo" />
<div id="bar" />
Now if you want to run it when the user is typing, than use the keyup event.
I am trying to output only articles if authorsId = authorId.
Beside that the whole function works exactly as I want, here it is:
The general idea is to limit access to only own articles.
So, my question is: how do I limit the results to show only articles written by the owner of the page we are on (authorsId = authorId).
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
alert(authorsid) // authors of each article - it returns the proper values
alert(authorid) // author of the page we are on - it returns the proper value
var count = 0;
rel.options[x] = new Option(title, id, authorid); // lign that returns results
title = '';
id = '';
authorid = '';
}
}
I suspect the problem is when you try performing a conditional statement (if/then/else) that you are comparing a number to a string (or a string to a number). This is like comparing if (1 == "1" ) for example (note the double quotes is only on one side because the left would be numeric, the right side of the equation would be a string).
I added a test which should force both values to be strings, then compares them. If it still gives you problems, make sure there are no spaces/tabs added to one variable, but missing in the other variable.
Also, I changed your "alert" to output to the console (CTRL+SHIFT+J if you are using firefox). The problem using alert is sometimes remote data is not available when needed but your alert button creates a pause while the data is being read. So... if you use alert, your code works, then you remove alert, your code could reveal new errors (since remote data was not served on time). It may not be an issue now, but could be an issue for you going forward.
Best of luck!
function ArticlesListReturn(returned) {
xml = returned.documentElement;
var rel = document.getElementById('related_category_articles');
rel.options.length = 0;
var status = getXMLData('status');
var title = '';
var id = '';
var authorid = '';
if (status == 0) {
alert("%%LNG_jsArticleListError%%" + errormsg);
} else {
var authorid = document.getElementById("authorid").value; // Serge
// authorsid = getNextXMLData('authors',x);
for (var x = 0; x < xml.getElementsByTagName('titles').length; x++) {
title = getNextXMLData('titles', x);
id = getNextXMLData('ids', x);
authorsid = getNextXMLData('authors', x);
console.log("authorsid = "+authorsid); // authors of each article - it returns the proper values
console.log("authorid = "+authorid); // author of the page we are on - it returns the proper value
if( authorsid.toString() == authorid.toString() )
{
rel.options
var count = 0;
console.log( authorsid.toString()+" equals "+authorid.toString() );
rel.options[rel.options.length] = new Option(title, id, authorid); // lign that returns results
}
else
{
console.log( authorsid.toString()+" NOT equals "+authorid.toString() );
}
title = '';
id = '';
authorid = '';
}
Did you check the console for messages? Did it correctly show authorid and authorsid?
I have edited the script and made a couple of additions...
The console will tell you if the conditional check worked or not (meaning you will get a message for each record). See the "if/else" and the extra "console.log" parts I added?
rel.options[x] changed to equal rel.options[rel.options.length]. I am curious on why you set rel.options.length=0 when I would instead have done rel.options=new Array();
I am writing an online loan calculator for practice. The data processing is all done on the client-side, however, JSFiddle wants me to use POST. Why is this? Could this be related to the fact that when the calculate button is clicked locally, the form just clears? The code in a JSFiddle: http://jsfiddle.net/TJonS/CuzSM/
Also, why isn't this calculating on click of the button? I have tried debugging multiple times, but Chrome is showing no errors.
Javascript:
function calculate(){
//get the elements
var amount = document.getElementById("amount");
var rate = document.getElementById("rate");
var duration = document.getElementById("duration");
//get the values of the elements
var a = parseFloat(amount.value);
var r = parseFloat(rate.value);
var d = parseFloat(duration.value);
//grab the outputable (readable(ha ha:))) variables
var principal = a;
var interest = r/100/12;
var time = d *12;
//now the calculation variables
var x = Math.pow(1+interest, payments);
var monthlypay = (principal*x*interest)/(x-1);
//if the result is a finite number, then display it. Else we're messed up!
if (isFinite(monthlypay)) {
//fill in outputs
payment.innerHTML = monthlypay.toFixed(2);
total.innerHTML = (monthlypay * payments).toFixed(2);
totalinterest.innerHTML = ((monthlypay*payments)-principal).toFixed(2);
//save the variables
save(amount.value, rate.value,duration.value, a.value, r.value, d.value, principal.value, total.value, totalinterest.value)
}
//else just make the outputs blank as can be.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
}
just put
return false;
at the bottom of your calculate function, to stop the default onClick behavior(of the button) performing a form post.
also...
is your if statement "if (isFinite(monthlypay)) {" actually getting focus?
this seems to be wiping the values every time.
else {
payment.innerHTML = "";
total.innerHTML = "";
totalinterest.innerHTML = "";
}
check your "isFinite(monthlypay)" function is returning true. (most probably never)
Button without post on click:
<input type="button" onclick="dosomething();" value="my button text" />
I am using a series of check boxes all are with different name that is checkbox1....checkbox40. I am generating a series of sting with '1' and '0' that is if check box is checked than sting will be concatenated with '1' else it will be concatenated with '0'. I have successfully implemented idea for PHP but as now I am using Ajax I want to develop same code for java script. My PHP code for that is
if (isset($_POST[submit]))
{
for ($i=1; $i<41; $i++)
{
$walue = "restriction".$i;
if(isset($_POST[$walue])) {$val .="1";} else {$val .="0";}
}
}
echo "Equivalent String: ".$val."<p>";
for implementing it using Javascript I have called a function on submit event of form.
My form id is theForm and my checkboxes name is restriction1....restriction40. Please give me hint to implement the idea.
So.. something like this?
getCheckedString = function () {
var chunks = [];
var checkboxes = $("#theForm").children('input[type=checkbox]').each(function () {
chunks[chunks.length] = $(this).is(':checked') ? '1' : '0';
});
return chunks.join('');
}
This will gather up all of the checkboxes in the order they are on the form, put a '1' or '0' in the array, then return the array joined into a string. It's not specific to a particular name, so if there are other checkboxes in the form let me know and I'll alter my answer.
If you have only named checkboxes, you would do:
function getCheckedString1() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var boxes = document.getElementsByName("restriction" + i); // returns an array
if (boxes[0]) {
val += boxes[0].checked ? "1" : "0";
}
}
// alert(val);
return val;
}
However, it is easier and the usual praxis to identify the referenced HTML elements with ID's. So, you would enhance your HTML:
<input type="checkbox" name="restriction1" id="restriction1" ...
<input type="checkbox" name="restriction2" id="restriction2" ...
and then use:
function getCheckedString2() {
var val = "";
for (var i = 1; i <= 40; ++i) {
var box = document.getElementById("restriction" + i); // returns the unique element
if (box) {
val += box.checked ? "1" : "0";
}
}
// alert(val);
return val;
}