JavaScript - Can't get the input field - javascript

This is my code for my login page:
http://pastebin.com/RGVrW0Hi
It's the field right under the body tag.
All the way down there is a scipt tag with my function. I'm trying to check if the user has typed something inside the "Navn" field, if not it should return false.
I have tried it in a smaller page that look like this:
http://pastebin.com/d1vzyDvd
Can anyone point me in the right direction?

If you want to get any field by name use
var value = document.getElementsByName("navn")[0].value;
// By Id
var value = document.getElementsById("navn").value;

Use document.getElementsByName("navn").value[0] instead of document.famular.navn.value to get the value of an input field by its name.
function validerform125() {
if (document.getElementsByName("navn")[0].value == "") {
alert("NEEEJ!!!");
return false;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<form name="famular" action="vanillahost.html" method="post" onsubmit="return validerform125()">
Navn
<input name="navn" type="text">
<br/>Email
<input name="email" type="email">
<br/>
<div>
<input type="submit" name="send" value="send">
</div>
</form>
You add [0] to document.getElementsByName("navn") because getElementsByName returns a NodeList object which represents a collection of elements with the specified name (In your case: "Navn"). By adding [0] you are basically returning the first element found.

better if you can include jquery in your html, will give you a nicer interface to interact with html elements.
In java-script you can try the following code
<body>
<div>
<form name="famular" action="vanillahost.html" method="post" onsubmit="return validerform125()">
Navn <input name="navn" type="text"><br/>
Email <input name="email" type="email"><br/>
<div>
<input type="submit" name="send" value="send">
</div>
</form>
</div>
</body>
<script>
function validerform125() {
var x = document.forms["famular"]["navn"].value;
if (x == null || x == "") {
alert("Name must be filled out");
return false;
}
}
</script>

Related

Restricting user to leave input field blank using javascript getElementsByClassName method

Created a form. I just want to make form validation. Used javascript to do the job here. Inside jS code created a function named check. In that function if some user leaves the input field blank then the function returns false and in that way I think, can restrict user, but not happening. My question is addressing both getElement..() method and as well as form validation.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname').value;
//checks the inpur field and it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>
The problem is that getElementsByClassName returns an array, so you should use either document.getElementsByClassName('fname')[0].value or document.querySelector('.fname').value (querySelector returns only first found entity)
Here is my complete code after execution.
function check(){
//fname is the value provided into the input field
var fname = document.getElementsByClassName('fname')[0].value;
//var fname = document.querySelector('.fname').value;
//checks the input field and if it is blank then return false
if (fname == '') {
return false;
}
else {
//if the input field is provided then will pass the validity
return true;
}
}
<div class="form">
<!-- created the class here and named form-->
<form class="" action="output.html.php" method="post" onsubmit="return check()">
<!-- called the check function-->
<input class="fname" type="text" name="name" value="" placeholder="Name">
<button type="submit" name="button">Send</button>
</form>
</div>

Convert input text to lowercase on submitting a form

I have a form in which there is one text field is provided with a submit button.On clicking submit button,it redirects to second php page from first php page.
index.php
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert()" />
</form
<script type="text/javascript">
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search").value;
document.writeln(str.toLowerCase());
}
</script>
On submitting the form,i want the url to become like submit.php?search=text
I want this text to be in lower case,although if text entered is uppercase.
Please guide me how to make this text lower case,I am using the above script for converting it to lower case.But its not converting the text in lower case in URL.
Please guide me on this..
There was a few errors, you were missing the right angle bracket on </form> and you were trying to write the value rather than setting the field value, try this...
<form action="submit.php" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form>
<script type="text/javascript">
function convert() {
alert("hi");
var str;
var srch=document.getElementById("search");
str = srch.value;
srch.value=str.toLowerCase();
}
</script>
You can do this only using javascript with a few extra stuff:
1) Give your <form> an id
<form action="submit.php" method="get" id="form1">
2) Make your <input> type as button. The reason for this is because we want to make sure the convert() function is executed first, and after that we will submit the form.
<input type="button" value="submit" onclick="convert()" />
3) Finally javascript to:
function convert()
{
alert("hi");
var str ;
str = document.getElementById("search");
str.value = (str.value.toLowerCase());
//get the form id and submit it
var form = document.getElementById("form1");
form.submit();
}
Fiddle
You are use form element so you can get any elements inside form element access by name, Here Our form name is form1 and inside this form inputbox name="search" and access this value by this way, document.form1.search.value.toLowerCase();
Check this Demo jsFiddle
JavaScript
function convert() {
alert("hi");
var str = document.form1.search.value.toLowerCase();
document.writeln(str);
//console.log(str);
}
HTML
<form name="form1" method="get">
<input type="text" name="search" id="search" />
<input type="submit" value="submit" onclick="convert();" />
</form >
try like this:
alert("hi");
document.getElementById("search").value = document.getElementById("search").value.toLowerCase();
return true;
Fiddle Live

JQuery: How to check the value of a form field

I have a simple form, with one issue.
In explorer, if nothing is inserted, the placeholder is passed as input of the field.
Here is JSbin: http://jsbin.com/EvohEkO/1/
I would like to make a simple comparision, when form is submitted, to check if the value of the field is equal to "First name", and if yes make the value empty ""
Just this i need.
Someone can help me please?
<form onsubmit="return checkform()">
<input name="test" placeholder="placeholdertext" id="test" />
<input type="submit" value="submitbutton"/>
</form>
in js
you should import jquery latest version this is the link: http://code.jquery.com/jquery-1.10.2.min.js
function checkform(){
var fieldvalue = $.trim($('#test').val());
if(!fieldvalue || fieldvalue=="placeholdertext"){
alert('there is no input');
return false;
}else{
alert('enjoy your form!');
return true;
}
}
This is somewhat easier..
$(document).ready(function(){
$("#form").submit(function(){
$('#form input:text, textarea').each(function() {
if($(this).val()==$(this).attr('placeholder'))
$(this).val(" ");
});
});
});
Just put your field value in hidden type input like this :-
<input id="hdnfield" name="hdnfield" value="<Your Field Value>" />
To check the value of a form field use the val() function on the input element
var input_value = jQuery('Input Element Selector').val();
As I looked to your form, the elements do not have any id attribute, I recommend that you add one to each of them, also change the submit input to button the you have more control on the javascript. so your form will look like :
<form id="form" action="form.php" method="post">
<input id="fname" type="text" placeholder="First name" name="fname"><br>
<label for="fname" id="fnamelabel"></label>
<input id="lname"type="text" placeholder="Last name" name="lname"><br>
<textarea id="message" placeholder="Contact us!" cols="30" rows="5" name="message"></textarea><br>
<br>
<input type="button" value="Submit">
</form>
so your jQuery will look like:
jQuery(document).ready(function(){
jQuery('input[type="button"]').click(function(){
var fname = jQuery('#fname').val();
var lname = jQuery('#lname').val();
var message = jQuery('#message').val();
...... Do whatever you need & then change the input values
...... if all validation has passed the use jQuery('#form').submit(); to submit the form otherwise reset the form:
jQuery('#fname').val("");
jQuery('#lname').val("");
jQuery('#message').val("");
});
});
here is a working version:
jsfiddle working link
You can do it like the following!
<form>
<input type="text" id="first_name" name="first_name"/>
<input type="submit" id="submit" value="submit"/>
</form>
<script type="type/javascript"/>
jQuery.noConflict();
(function ($) {
$(function () {
$("#submit").click(function () {
if ($("#first_name").val() == "first name") {
$(this).val("");
}
});
});
})(jQuery);
</script>

Validate a form using JavaScript

I am a beginner and I have written a code for validating the form as:
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
alert("First name must be filled out");
return false;
}}
<!-- html part-->
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
First name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><br>
The problem with this code is pressing submit button triggers the validateForm function. How to call the function when the object losses focus?
This is the exact solution to my problem. Where the user gets some kind of notification when the object losses focus:
<script>
function validate(){
var y = document.getElementById("errorResponse");
var x=document.forms["myForm"]["fname"].value;
if (x==null || x==""){
y.innerHTML = "Error";
}
}
</script>
The HTML form is:
<form name="myForm">
First name: <input type="text" name="fname" onBlur = "validate()">
<div id = "errorResponse"></div>
<input type="submit" value="Submit">
</form>
The div can be designed in CSS to red color to get user attention and many more tricks can be played.
replace your input element's code by following
<input type="text" onblur="return validateForm();" name="fname">
i guess thats what you are looking for
<html>
<head>
<script type="text/javascript">
function validateForm(oForm){
var els = oForm.elements;
for(var i = 0; i < els.length; i++){
if('string' === typeof(els[i].getAttribute('data-message'))){
return valEl(els[i]);
}
}
}
function valEl(el){
var method = el.getAttribute('data-valMethod');
if('req' === method && (el.value === null || el.value === '')){
alert(el.getAttribute('data-message'));
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="#" onsubmit="return validateForm(this)" method="post">
First name:
<input data-message="First name must be filled out" data-valMethod="req" onchange="return valEl(this)"; name="fname"><br />
<input type="submit" value="Submit">
</form>
</body>
</html>​​​​​​​​​​​​​​​​​​​
I have Split it in one function that can validate the elements on "onchange" and another one that fires the validations for each element on form.onsubmit(), if there's the required data-message attribute on a form element.
Since HTML5 the Data-* attributes are very handy for these things :-)
This way you can avoid having to store the name of the form and elements in the validation script, since you pass references to the elements themselfes instead. Which is always a good thing.
From here you can expand the valEl-function to accommodate other types of validation.
Only limitation so far is that there can be only one type of validation per element, but that should be easy enough to get around.
Happy coding.
/G
PS http://jsfiddle.net/ePPnn/11/ for sample code

Why my form doesn't validate correctly?

I'm trying to validate a form, but doesn't work :\ , When I submit the form goes to mail.php even if the required fields are missing, but I set onsubmit to validate() so it should check, but doesn't work. What's the problem with my code? I can't find it.
HTML:
<form action="mail.php" onsubmit="return validate()" method="post" class="contact-form" id="contactForm">
<div id="errors"></div>
<label for="author">Name:</label><br/><br/>
<input type="text" name="author" id="message" /><br/><br/>
<label for="author">Message:</label><br/><br/>
<textarea name="message" id="message"></textarea><br/><br/>
<input type="submit" class="button" value="Send Message"/>
</form>
Javascript:
<script type="text/javascript">
function error(message){
return "<p class=\"error\">"+message+"</p>";
}
function validate(){
var form = document.getElementById("contactForm");
var author = document.getElementById("author");
var message = document.getElementById("messsage");
var errors = document.getElementById("errors");
alert(author.value);
if(message.value == '' || author.value == ''){
errors.innerHTML = error("Please fill in all fields.");
return false;
} else {
return true;
}
}
</script>
id=author on your first input element.
Also check out jQuery it will save you time in the long run
You have two elements with the id message and none with author.
The Markup Validator would have picked this up for you.
var message = document.getElementById("messsage");
message has an extra "s".
<input type="text" name="author" id="message" />
You need to change "message" to "author"
This is wrong:
<input type="text" name="author" id="message" />
Need to set name and id to the same values (you're using id="message" for the next field, so there's a clash.
Also both your label tags have for="author"; the second one is wrong.
I guess your problem here is too much copy+paste. ;)

Categories