I have a form that I want to validate before the user is able to submit it. To do this I have written a basic js file that checks a value is not left blank. In the event that this is the case I want the background colour of the text field to update to be red. I have looked around online and am struggling to get this working. Here is what I have so far:
HTML Form:
<script language="javascript" src="validateForm.js"></script>
<form name="contact form">
<input type="text" name="name"></td>
<input type="button" value="Send" onsubmit="return validateForm()" method="post">
</form>
Javascript:
function validateForm()
{
var result = true;
var form = document.forms["contact form"];
// Name
var name = form["name"].value;
if ( name == null || name == "" )
{
form["name"].style.backgroundColor = red;
result = false;
}
return result;
}
Please could someone help me get this working?
Use red as string ( you missed the quote) jsfiddle
form["name"].style.backgroundColor = "red"; // not red
Related
I'm making an uploading system using php and I thought I would make an username blank space and an option for choosing an image. I already did an error message something like this, But the problem is, I want to make it more specific.
<script>
var form = document.getElementById('FormID');
form.noValidate = true;
form.addEventListener('submit', function(event) {
if (!event.target.checkValidity()) {
event.preventDefault();
document.getElementById('errorMessageDiv').classList.remove("hidden");
}
}, false);
</script>
The div for it
<div id="errorMessageDiv" class="hidden" >Please, Fill up the form</div>
The css
<style type = "text/css">
.hidden {
display: none;
}
</style>
The problem is, I want to make it more specific. For example, For the username it would say "username required" and for choosing an image, "An image is required" If the user didn't choose or fill up the username. This is also my full form:
<form method="post" enctype="multipart/form-data" id="FormID">
<label>User Name</label>
<input id = "name" type="text" name="user_name" class="form-control" required = "" >
<label>Select image to upload</label>
<input id = "image" type="file" onchange ="unlock()" name="profile" class="form-control2" accept="*/image" required = "">
<button type="submit" id="submit" name="btn-add">Upload</button>
<div id="errorMessageDiv" class="hidden" >Please, Fill up the form</div>
</form>
I'm making it for safari as well, So far I want to make the error messages in a div form.
Along with this in script
document.getElementById('errorMessageDiv').classList.remove("hidden");
You can edit the text based on the situation
errorMessage = validateForm();
document.getElementById('errorMessageDiv').innnerHTML = errorMessage;
function validateForm() {
var form = document.getElementById("FormID");
var inputs = form.getElementsByTagName("input");
var fields = ["#name", "#image"];
for(var i =0; i < fields.length ; i++){
if(form.getElementById(fields[i]).value != "")
errorMessage = + errorMessage + fields[i];
}
errorMessage = errorMessage + " is empty!";
return errorMessage;
}
Something similar as it suits your needs.
Your question is similar to (sorry can't comment)
HTML/Javascript change div content
and this link
Check all elements in form with Javascript
Trying to keep a button disabled until the form fields are filled in and I cannot seem to accomplish this. I've created a small example with a single field but the principle will be the same with a larger form.
Can anyone help?
Code:
function checkForm() {
var name = document.getElementById("name").value;
var cansubmit = true;
if (name.value.length == 0) {
cansubmit = false;
}
if (cansubmit == false) {
document.getElementById("submitbutton").disabled = true;
}
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton">Test me</button>
There are a couple of mistakes in your sample:
var name is assigned to the value string of the name element, then you check the value property of that - the string has no value property.
the id of the submit button is myButton so use that id to get it by id (when setting the disabled attribute).
You can disable the submitbutton until the length of the name input is greater than 0.
And disabling the button initially sounds like a good idea, right?
See corrected example below:
function checkForm()
{
var name = document.getElementById("name").value;
var cansubmit = (name.length > 0);
document.getElementById("myButton").disabled = !cansubmit;
};
<input type="text" id="name" onkeyup="checkForm()" />
<button type="button" id="myButton" disabled="disabled">Test me</button>
You might also want to consider handling change via methods other than keypress - e.g. mouseup, etc... I tried adding onchange="checkForm()" and it works but only on blur (focus-change)...
To the point, if i input value "20" in input field then show message "Thank you".
Here's my HTML Code:
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="submit" value="submit">
</form>
Here's my JS Code:
$(document).ready(function(){
var money = 20;
/* not sure if this is written correctly, but this is supposed to
check whether the hidden input element value is equal to var money */
if ($("input[id='nominal']").val() == money ) {
var h = document.createElement("H1") // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t); // Append the text to <h1>
};
});
i've created one script to fulfill what I need, but not working! what's wrong?
My JDFIDDLE LINK
You have to create an event to listening for changes, in this case changed. And you can make your code a bit smaller too. ;)
$(function() {
$("#nominal").change(function() {
if( $(this).val() == 20 )
$(this).after("<h1>Thank You</h1>");
});
});
Full working exaple with removing the message when value changes again and strict check can be seen here.
$(document).ready(function(){
var money = 20;
$("#nominal").change(function() { // take change event of input box
if ($(this).val() == money ) { // use $(this) to take value
var h = document.createElement("H1"); // Create a <h1> element
var t = document.createTextNode("Thank You"); // Create a text node
h.appendChild(t);
$('form').append(h); // append created h1 element in form/html
} else {
$('form').find("h1").remove();
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form method="post" action="">
<input type="text" id="nominal" value="">
<input type="button" value="submit" name="submit" id="submit">
</form>
I'm having trouble getting the match to bind to the oninput property of my text input. Basically I want my submit button to be enabled only when the regular expression is matched. If the regex isn't matched, a message should be displayed when the cursor is over the submit button. As it stands, typing abc doesn't enable the submit button as I want it to. Can anyone tell me what I'm doing wrong? Thank you.
<div id="message">
</div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt = $("#txt").value();
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
// disable buttons with custom jquery function
jQuery.fn.extend({
disable: function(state) {
return this.each(function() {
this.disabled = state;
});
}
});
$('input[type="submit"]).disable(true);
var match = function(){
if (txt.match(PATTERN)){
$("#enter").disable(false)
}
else if ($("#enter").hover()){
function(){
$("#message").text(REQUIREMENTS);
}
}
</script>
Your code would be rewrite using plain/vanille JavaScript.
So your code is more clean and better performance:
<div id="message"></div>
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<input type="submit" id="enter" value="enter" disabled />
</form>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = false;
} else if (isHover(enter)) {
enter.disabled = true;
message.innerHTML = REQUIREMENTS;
} else {
enter.disabled = true;
}
}
function isHover(e) {
return (e.parentElement.querySelector(':hover') === e);
}
</script>
If you wanted to say that you want handle the events in different moments, your code should be the following.
Note: the buttons when are disabled doesn't fired events so, the solution is wrapper in a div element which fired the events. Your code JavaScript is more simple, although the code HTML is a bit more dirty.
<form method="POST">
<input type="text" id="txt" oninput="match()" />
<div style="display: inline-block; position: relative">
<input type="submit" id="enter" value="enter" disabled />
<div id="buttonMouseCatcher" onmouseover="showText(true)" onmouseout="showText(false)" style="position:absolute; z-index: 1;
top: 0px; bottom: 0px; left: 0px; right: 0px;">
</div>
</div>
<script>
var txt;
var enter = document.getElementById('enter');
var message = document.getElementById('message');
var PATTERN = /abc/;
var REQUIREMENTS = "valid entries must contain the string 'abc'";
function match() {
txt = document.getElementById('txt').value;
if (PATTERN.test(txt)) {
enter.disabled = '';
} else {
enter.disabled = true;
}
}
function showText(option) {
message.innerHTML = option ? REQUIREMENTS : "";
}
</script>
Two problems here:
The variable txt is defined once outside the function match, so the value is fixed to whatever the input with id txt has when the script/page is loaded.
You should move var txt = $("#txt").val(); into the match function.
Notice I changed the function value() to val().
Problems identified:
jQuery events don't happen on disabled inputs: see Event on a disabled input
I can't fix jQuery, but I can simulate a disabled button without it actually being disabled. There's other hacks you could do to get around this as well, for example, by overlaying a transparent element which actually captures the hover event while the button is disabled.
Various syntactical errors: format your code and read the console messages
.hover()){ function() { ... } } is invalid. It should be .hover(function() { ... })
else doesn't need to be followed by an if if there's no condition
.hover( handlerIn, handlerOut ) actually takes 2 arguments, each of type Function
$('input[type="submit"]) is missing a close '
Problems identified by #Will
The jQuery function to get the value of selected input elements is val()
val() should be called each time since you want the latest updated value, not the value when the page first loaded
Design issues
You don't revalidate once you enable input. If I enter "abc" and then delete the "c", the submit button stays enabled
You never hide the help message after you're done hovering. It just stays there since you set the text but never remove it.
https://jsfiddle.net/Lh4r1qhv/12/
<div id="message" style="visibility: hidden;">valid entries must contain the string 'abc'</div>
<form method="POST">
<input type="text" id="txt" />
<input type="submit" id="enter" value="enter" style="color: grey;" />
</form>
<script>
var PATTERN = /abc/;
$("#enter").hover(
function() {
$("#message").css('visibility', $("#txt").val().match(PATTERN) ? 'hidden' : 'visible');
},
$.prototype.css.bind($("#message"), 'visibility', 'hidden')
);
$('form').submit(function() {
return !!$("#txt").val().match(PATTERN);
});
$('#txt').on('input', function() {
$("#enter").css('color', $("#txt").val().match(PATTERN) ? 'black' : 'grey');
});
</script>
I have four input boxes. If the user fills the first box and clicks a button then it should autofill the remaining input boxes with the value user input in the first box. Can it be done using javascript? Or I should say prefill the textboxes with the last data entered by the user?
On button click, call this function
function fillValuesInTextBoxes()
{
var text = document.getElementById("firsttextbox").value;
document.getElementById("secondtextbox").value = text;
document.getElementById("thirdtextbox").value = text;
document.getElementById("fourthtextbox").value = text;
}
Yes, it's possible. For example:
<form id="sampleForm">
<input type="text" id="fromInput" />
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="text" class="autofiller"/>
<input type="button"value="Fill" id="filler" >
<input type="button"value="Fill without jQuery" id="filler2" onClick="fillValuesNoJQuery()">
</form>
with the javascript
function fillValues() {
var value = $("#fromInput").val();
var fields= $(".autofiller");
fields.each(function (i) {
$(this).val(value);
});
}
$("#filler").click(fillValues);
assuming you have jQuery aviable.
You can see it working here: http://jsfiddle.net/ramsesoriginal/yYRkM/
Although I would like to note that you shouldn't include jQuery just for this functionality... if you already have it, it's great, but else just go with a:
fillValuesNoJQuery = function () {
var value = document.getElementById("fromInput").value;
var oForm = document.getElementById("sampleForm");
var i = 0;
while (el = oForm.elements[i++]) if (el.className == 'autofiller') el.value= value ;
}
You can see that in action too: http://jsfiddle.net/ramsesoriginal/yYRkM/
or if input:checkbox
document.getElementById("checkbox-identifier").checked=true; //or ="checked"