Javascript disabling input fields - javascript

I am looking for a javascript function. which will disable the entered (filled) text field on submit. So when the user logs in back the filled text box has to remain disabled. I have tried a code, but here what happens is on clicking the sumbit the contents in the text field gets deleted.
<html>
<head>
<script>
function enableDisable(){
var disable = true;
var arglen = arguments.length;
var startIndex = 0;
var frm = document.example1;//change appropriate form name
if (arglen>0){
if (typeof arguments[0]=="boolean") {
disable=arguments[0];
if (arglen>1) startIndex=1;
}
for (var i=startIndex;i<arglen;i++){
obj = eval("frm."+arguments[i]);
if (typeof obj=="object"){
if (document.layers) {
if (disable){
obj.onfocus=new Function("this.blur()");
if (obj.type=="text") obj.onchange=new Function("this.value=this.defaultValue");
}
else {
obj.onfocus=new Function("return");
if (obj.type=="text") obj.onchange=new Function("return");
}
}
else obj.disabled=disable;
}
}
}
}
</script>
</head>
<body>
<form name="example1">
Text Field: <input type="text" name="text1">
<br>
<input type="submit" name="control1" onclick="enableDisable(this.submit,'text1','submit','select1')">
</form>
</body>
</html>
please do guide.

Make sure your submit function returns false if you don't want the page to refresh. The code you're looking for is document.getElementById('insertIdOfTextFieldHere').style.readonly = "readonly";

Related

JavaScript function/event listener not functioning properly

I'm completely new to JavaScript, and don't know why this isn't working. When I click on the input box, and type in less than 5 characters, i want a message to display. The message is simply not showing. Source code: https://jsfiddle.net/015por64/
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.textContent;
if (usernameLength.value.length < 5) {
msg = "Your username must consist of at least five characters."
};
else {
msg = "";
text.innerHTML=msg
};
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>
Few issues with your code:
you need to attach the event to #input and not the div#text.
you need to read value of #input and not textcontent
; after if is wrong because then else will give syntax error.
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.value;
if (usernameLength.length < 5) {
msg = "Your username must consist of at least five characters.";
text.innerHTML=msg;
}else {
msg = "";
text.innerHTML=msg;
};
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>
It should be the input where you have to put the blur event listener.
var input = document.getElementById("input");
And since you have no use for text outside the function, better define it inside.

Get input from textbox and write it below

I need to take the value from an input box and write it below the input box on the click of a button. I thought to use a label but if there is another way I am open to suggestions.
My code so far:
<h1>Test</h1>
<form name="greeting">
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
<script lang="javascript">
function getName() {
var inputVal = document.getElementById("name").value;
if (inputVal == "") {
document.getElementById("name").style.backgroundColor = "red";
}
else {
document.write("Hello " + document.getElementById("name"));
}
First of all, you don't want to submit a form, so change button type from "submit" (default) to "button".
Then you should not use document.write almost never, it's used in very specific cases. Use proper DOM manipulation methods like appendChild. I would use convenient insertAdjacentHTML:
function getName() {
var input = document.getElementById("name");
if (input.value == "") {
input.style.backgroundColor = "red";
} else {
input.insertAdjacentHTML('afterend', '<div>' + input.value + '</div>');
}
}
<form name="greeting">Type your name here:
<input type="Text" name="fullname" id="name" />
<button type="button" onclick="getName()">Create</button>
<br>Hello
<label id="greet">Hello</label>
</form>
First you need to stop your form from submitting. Second you should not use document.write, since it will not append the text as wanted after the input field. And last you need to validate the elements value and not the element itself.
<html>
<head>
<script>
//First put the function in the head.
function getName(){
var input = document.getElementById("name");
input.style.backgroundColor = ''; //Reseting the backgroundcolor
if (input.value == ''){ //Add the.value
input.style.backgroundColor = 'red';
}
else{
//document.write('Hello ' + input.value); //This would overwrite the whole document, removing your dom.
//Instead we write it in your greeting field.
var tE = document.getElementById('greet');
tE.innerHTML = input.value;
}
return false //Prevent the form from being submitted.
}
</script>
</head>
<body>
<h1>Test</h1>
<form name = 'greeting'>
Type your name here: <input type = "Text" name="fullname" id="name"> <button onclick="return getName()">Create</button><br>
Hello <label id="greet">Hello</label>
</form>
</body>
</html>
You need to cancel the submit event which makes the form submit, alternatively you could not wrap everything inside a form element and just use normal div that way submit button wont submit.
Demo : https://jsfiddle.net/bypr0z5a/
Note reason i attach event handler in javascript and note onclick attribute on button element is because jsfiddle works weird, on ordinary page your way of calling getName() would have worked.
byId('subBtn').onclick = function (e) {
e.preventDefault();
var i = byId('name'),
inputVal = i.value;
if (inputVal == "") {
i.style.backgroundColor = "red";
} else {
byId('greet').innerText = inputVal;
i.style.backgroundColor = "#fff";
}
}
function byId(x) {
return document.getElementById(x);
}

JavaScript Form Validation - What is wrong with this code? [duplicate]

This question already exists:
Javascript Form Validation - What is wrong with my code?
Closed 8 years ago.
I am simply adding text into the input field for practice. It seems that when I press submit, the text appears in the input field for a short second then disappears. Could someone please tell me why this is happening? How can I get the messages to stay?
<!DOCTYPE html>
<html>
<head>
<title>Title</title>
<script src="EventUtil.js"></script>
</head>
<body>
<form>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="text" name="poop1"> <br>
<input type="submit" value="submit" id="btn">
</form>
<script type="text/javascript">
EventUtil.addHandler(window,"load", function() {
var btn = document.getElementById("btn");
EventUtil.addHandler(btn,"click",function(){
var i;
for (i=0; i<document.forms[0].elements.length-1; i++){
if (document.forms[0].elements[i].value == ""){
document.forms[0].elements[i].value = "fill this poop in";
}
}
})
})
</script>
</body>
</html>
The issue is that you're submitting the form, which reloads the current page. That's why you see the values for only a moment.
To fix it, use a <button type="button"> instead of an <input type="submit">.
You should put the listener on the form's submit handler, not the submit button, as the form can be submitted without clicking the button. Either add an ID to the form, or use the document's forms collection:
var form = document.forms[0];
or
var form = document.getElementById('formID');
As noted in other answers, the form is submitting so the page refreshes. To cancel submit, return false from the listener.
Within the listener, this should reference the form:
EventUtil.addHandler(form, 'submit', function(){
var control, controls = this.elements;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if (control.type == 'input' && control.type == 'text' && control.value == '') {
control.value = 'fill this shit in';
return false;
}
}
});
Why don't you just use the required attribute on the form elements

Changing Border Color When Incorrect Input With Javascript

I'm working on a form that is supposed to validate the input in several textboxes when the user clicks the "submit" button. If any of the required boxes are left blank or have an incorrect type of input or format, the border of those textboxes is supposed to turn red and return to the normal color when the requirements are met.
For example, a phone number is either supposed to be 7 or 10 digits long, if the user enters a six digit number like (123456), the border around this field should turn red, when the user enters one more number, like (1234567), the border should go back to it's regular color immediately, without the user having to click the "submit" button again.
How my code is written, the border does turn red when the user enters too few numbers, however, the submit button must be clicked for the border to go back to its original color. Is there a way to change the color back without the button being clicked a second time?
Here is my code:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validateForm() {
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
</html>
Once a user submits the form with invalid data, you can attach onkeyup event listener into a input field, and everythime a user types something into the field, the form will be validated
document.getElementById("phone").onkeyup = validateForm;
I wrote once a user submits the form on purpose, since you do not want to fool your visitor by knowing that he typed only one character and he is getting validation error. (he is about to type 5 more characters)
EDIT:
<html>
<head>
<title>Project 4</title>
<style type="text/css">
.error {
border:2px solid red;
}
</style>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
Phone Number:<input type="text" id="phone">
<br>
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
//at first, we define a variable stating that an event listener has been attached onto the field
var validatePhoneOnKeyUpAttached = false;
function validateForm() {
//then, we attach the event listened to the field after the submit, if it has not been done so far
if(!validatePhoneOnKeyUpAttached) {
document.getElementById("phone").onkeyup = checkPhone;
validatePhoneOnKeyUpAttached = true;
}
return checkPhone();
}
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if(phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").style.borderColor="transparent";//and you want to remove invalid style
return true;
}
else if(phoneNum.length < 7 || phoneNum.length > 10) {
//document.getElementById("phone").className = document.getElementById("phone").className + " error";
//document.getElementById("phone").className = document.getElementById("phone").className.replace(" error", "");
document.getElementById("phone").style.borderColor="red";
return false;
}
}
</script>
</body>
You can simply add onkeyup handler for input field:
<input type="text" id="phone" onkeyup="checkPhone()" />
and also make checkPhone function remove error class if input is valid:
function checkPhone() {
var phone = document.forms["myForm"]["phone"].value;
var phoneNum = phone.replace(/[^\d]/g, '');
if (phoneNum.length > 6 && phoneNum.length < 11) {
document.getElementById("phone").className = '';
return true;
}
else if (phoneNum.length < 7 || phoneNum.length > 10) {
document.getElementById("phone").className = 'error';
return false;
}
}
Demo: http://jsfiddle.net/bcxLz4wh/
Use the blur event of your input like this:
<input type="text" id="phone" onblur="validateForm();">
The blur event runs when you control loses the focus. If you need something more immediate you will need to use the keyup event.

Fill data in input boxes automatically

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"

Categories

Resources