Cant get my input value to appear on my functions [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want my use to enter a value and when they press Submit Calculations there should be a alert bar previewing an error message if value is null.
<form id= "form1" class = "myform" action ="register.php" method "post">
<label> Loan Amount: </label>
<input type = "text" class= "inputvalues" id = "loanAmm" placeholder = "Fill in the Details"> <br>
<input name = "submit_btn" type ="button" onclick = "checkvalues();" id = "storevalue" value = "Submit Calculations"> <br>
</form>
function checkvalues()
{
var loanAmount = document.forms["form1"]["loanAmm"].value;
if (loanAmount == null )
{
alert("Re-enter value");
return false;
}
}

When referencing elements with document.forms["form1"], "form1" is the name of the form, not the id. The same is true for document.forms["form1"]["loanAmm"] - "loanAmm" is the name of the input.
Best practice is to use the id to reference the input.
Also, use addEventListener to add the onclick handler because it separates the logic from the layout.
document.getElementById("storevalue").addEventListener("click", function() {
var loanAmount = document.getElementById("loanAmm").value;
if (loanAmount.trim() === "") {
alert("Loan amount cannot be blank");
return false;
} else {
document.getElementById("form1").submit();
}
});
<form id="form1" class="myform" action="register.php" method "post">
<label> Loan Amount: </label>
<input type="text" class="inputvalues" id="loanAmm" placeholder="Fill in the Details"> <br>
<input name="submit_btn" type="button" id="storevalue" value="Submit Calculations"> <br>
</form>

Your test should be :
if (loanAmount === '') {
alert("Re-enter value");
return false;
}
If input is empty, the value is not null but empty.

Related

Javascript Quiz with HTML + CSS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
****This code is now working.
Thankyou for your input everyone.
The initial problem was that the code would run on page load, and then the second problem was that it refreshed the page on submit
After some input from a few individuals we were able to debug it together and I learned some new things.****
function check(){
let correctAns1 = 'carname = "volvo"';
let input = document.getElementById("q1").value;
let score=0;
if(input.toLowerCase() == correctAns1) {
score++;
alert("That is correct")
alert("You have a total of " + score + " points")
}else{
alert("Incorrect")
};
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
});
<div id="testForm">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1" value><br>
<input type="submit" value="Submit">
</form>
</div>
You can keep questions, scores in localstorage in JavaScript.
This information is stored in the browser and works like cookies.
ex: value inserting in localstorage:
localStorage.setItem('myCat', 'Tom');
ex: accessing to value from localstorage:
localStorage.getItem('myCat');
You Can Look:
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I think you are troubled by that empty screen after submission, if yes, then the reason for that is "On form submit the page gets refreshed/redirected" to stop that use onsubmit = "check(); return false" or handle it with js using event.preventDefault.
Using return false:
onsubmit = "check(); return false"
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
};
check();
<div id="question1">
<form onsubmit="check(); return false"><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
Using preventDefault and javascript onsubmit:
e.preventDefault();
Source
function check() {
let correctAns1 = 'carname = "Volvo"';
let input = document.getElementById("q1").value;
let score = 0;
if (input == correctAns1) {
score++;
console.log("That is correct")
console.log(score)
} else {
console.log("Incorrect")
};
return false
};
document.getElementById("testForm").addEventListener("submit", function(e){
e.preventDefault();
check();
});
<div id="question1">
<form id="testForm" ><br><br>
<h2>Task 1</h2>
<p>Create a variable called carname and give it a value of Volvo</p>
<input type="text" id="q1"><br>
<input type="submit" value="Submit">
</form>
</div>
For storing, you can use localstorage on client-side. You can have an array/object of questions and answers and convert it into a string using JSON.stringify and store it in localstorage
localStorage.setItem('questionBook', JSON.stringify(questionBookObject));
and retrieve it using getItem and then JSON.parse it to get the object back.
const questionBookObject = localStorage.getItem('questionBook');

how to make an object that the value is coming form user input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
var person {
name; age; height;
};
that's the object and the properties. how do I input a value with user input using prompt box and external file js
Here is an example taking input from text input fields:
var person = {
name:"",
age:"",
height:""
};
document.getElementById("get_person").addEventListener("click", () => {
person.name = document.getElementById("name").value;
person.age = document.getElementById("age").value;
person.height = document.getElementById("height").value;
console.log(person);
});
<input id="name" type="text" value="name"></input>
<input id="age" type="text" value="age"></input>
<input id="height" type="text" value="height"></input>
<button id="get_person">Go</button>
Edit: Here is an example using the prompt box:
var person = {
name:"",
age:"",
height:""
};
person.name = prompt("Please enter your name");
person.age =prompt("Please enter your age");
person.height = prompt("Please enter your height");
console.log(person);

How to validate given textbox? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
This is textarea box and I want to validate it. I want to use required field validation. How can I do that?. I have tried validating textarea box using name and CSS class but I have failed to do so.
<textarea <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" maxlength="50" placeholder="Enter other item details"></textarea>
You can use below from http://www.w3schools.com/js/js_validation.asp
function validateForm() {
var x = document.forms["myForm"]["fname"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
You can simply use required=true property
<textarea required=true maxlength="50" placeholder="Enter other item details" <%#!((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).Code.Equals("OTH", StringComparison.InvariantCultureIgnoreCase) ? "style='display: none;'" : string.Empty%> id="text<%#((GPNS.BusinessLayer.SpecialItems.SpecialItem)Container.DataItem).ID%>" ></textarea>
OR
<script type="text/javascript">
$(document).ready(function () {
$("form").validate({
rules:{
textarea_name:{
required:true,
maxlength:50
}
}
});
});
</script>

Why does no DOM error appear when submitting my form using javascript [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I want to generate an error message inside the page using DOM if the user does not enter details in the form field.
It is being sent to an external php file.
When I use Javascript I get the pop-up screen, but when I try using the DOM, to bring up the error, it just goes straight to the PHP file when the text field is blank.
Here is my js:
function validate(){
function namefield()
{
if (document.form.name.value == "")
{
document.getElementById("namef").innerHTML = "Please input name";
return false;
}
return true;
}
}
The html is simply:
<p id="namef"> some text</p>
<p>Name: <input type = "text" name = "name"> </p>
I highly recommend you to use jQuery or a proper JavaScript validator library for your form. Here is a simple example of how you can validate an input field with jQuery.
HTML part:
<input type="text" id="username">
<input type="button" id="sendForm" value="send">
<p id="usernameError"></p>
jQuery part:
$(function () {
$('#sendForm').on("click", function () {
validateUserForm();
});
});
function validateUserForm()
{
var username = $('#username').val();
if (username == '') {
$('#usernameError').html('Please insert your username!');
}
else {
$('#usernameError').html('');
}
}
And here is a functional jsFiddle: https://jsfiddle.net/1bk3ufhd/
If "formname" is the value of the name attribute of the form and "name" is the value of the name attribute of the input field (as per your example):
if( document.forms["formname"].elements["name"].value == "" ){
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
document.getElementById("namef").innerHTML = "Please imput name";
return false;
}

javascript to check if user has inputted [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I have a form
<form method="post" action="sendmail.php" name="Email form">
Message ID
<input type="text" name="message_id" /><br/><br/>
Aggressive conduct
<input type="radio" name="conduct" value="aggressive contact" /><br/><br/>
Offensive conduct
<input type="radio" name="conduct" value="offensive conduct" /><br/><br/>
Rasical conduct
<input type="radio" name="conduct" value="Rasical conduct" /><br/><br/>
Intimidating conduct
<input type="radio" name="conduct" value="intimidating conduct" /><br/><br/>
<input type="submit" name="submit" value="Send Mail" />
</form>
I need some sort of validation javascript that:
Checks if user entered a message id and checked one of the radio buttons. (So message id and radio group are required fields)
Display an error message if any of the required fields is not set.
Block form submit until required fields are entered.
Can anyone help?
You will have to do a validation before submit.
Add an on submit event handler (that will be called when the form is submitted) to the form:
You can do this in two ways:
<form method="post" action="sendmail.php" name="Email form" onsubmit=validate()>
OR
in the <script> part:
window.onload = init;
function init()
{
document.forms["Email form"].onsubmit = function()
{
validate();
return false;
};
}
Now write the validate function itself (same for both options above):
function validate()
{
var form = document.forms["Email form"]; //Try avoiding space in form name.
if(form.elements["message_id"].value == "") //No value in the "message_id" box
{
alert("Enter Message Id");
//Alert is not a very good idea.
//You may want to add a span per element for the error message
//An div/span at the form level to populate the error message is also ok
//Populate this div or span with the error message
//document.getElementById("errorDivId").innerHTML = "No message id";
return false; //There is an error. Don't proceed with form submission.
}
}
UPDATE. Now it should work.
// Register onsubmit callback function (this will be called when the user submit his data).
document.forms[0].onsubmit = validate;
function validate() {
var message = document.getElementsByTagName('input')[0].value,
radioButtons = document.getElementsByTagName('input'),
oneRadioChecked = false;
// check that message is not empty
if (message.length === 0) {
alert("no message inserted");
return false;
}
// check that at least one radio has been checked
for (var i = 0; i < radioButtons.length && !oneRadioChecked; i++) {
oneRadioChecked = (radioButtons[i].type === "radio" &&radioButtons[i].checked);
}
if (!oneRadioChecked) {
alert("no radio button checked");
return false;
}
}

Categories