Javascript disabling input field - javascript

Haven't been around in a while. Got a hot project I'm working on and I can't seem to figure out how to disable an input text field. The situation is that I have a form that is filled out and then when it is submitted I leave the form where it is but disable the input fields so it can't be changed. So the user can continue to see what they have submitted.
<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>

I think you want the text field to be a read only field.
there is a difference between a disabled text field and a read only text field.
READONLY and DISABLED both remove the functionality of the input field, but to different degrees. READONLY locks the field: the user cannot change the value. DISABLED does the same thing but takes it further: the user cannot use the field in any way, not to highlight the text for copying, not to select the checkbox, not to submit the form. In fact, a disabled field is not even sent if the form is submitted.
So you should look into this post for more info regarding the same.
http://www.htmlcodetutorial.com/forms/_INPUT_DISABLED.html

Related

queryselector is returning incorrect value for input field

Code:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function displayquestion(a, ignore){
var b = a-1;
var currentInput = '';
var questions = document.getElementsByClassName("questionholder");
var showRequired = document.getElementById("requiredMessage");
if (document.querySelector('input.input' + b) !== null) {
var currentInput = document.querySelector('input.input' + b).value;
}
// Check if question should ignore inputs
if (ignore == 1) { // yes, ignore the inputs so move on to next question
console.log("path 1");
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
} else { //no, don't ignore the inputs
if (currentInput == '') { // the input is blank so show error
console.log("path 2");
showRequired.style.display = "block";
} else { // the input is not blank so move on to next question
console.log("currentInput = " + currentInput);
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
}
}
}
</script>
</head>
<body>
<div id="requiredMessage" style="display:none"><p>This field is required.</p></div>
<form id="TheForm" style="display:block;">
<div data-toggle="buttons" class="questionholder multiplechoice" id="question10" style="display:block">
<h5>Do you have a surname?</h5>
<input class="input10" type="radio" id="yes" name="sn" value="yes"><label for="relPPTsnyes"><p class="radioChoice">Yes / Oui</p></label>
<input class="input10" type="radio" id="no" name="sn" value="no"><label for="relPPTsnno"><p class="radioChoice">No / Non</p></label><br>
<a class="text2button radio" onclick="displayquestion(11)">Next</a>
</div>
</form>
</body>
</html>
I have issues with my javascript function, which works as intended with input text fields, but does not with radio buttons.
In short, I have a div that contains a pair of radio buttons and a next button. When the user click next, the function displayquestion(a) fires.
The function checks currentInput to see if the input is blank. If it is blank, it shows an error message. If it is not blank, it hides the div.
With radio buttons however, currentInput is always returning "yes" whether nothing is selected, no is selected or yes is selected. Since it isn't blank, it hides the div.
The intended result should be that the error message displays until the user makes a selection. only when the user clicks next, it should hide the div.
So my question is, what is causing my issue and how can it be fixed?
jsfiddle
use :checked
var currentInput = document.querySelectorAll('input.input' + b + ':checked").value;
Radios and Checkboxes always return their value.
The first thing you must do is check if one of them is selected, then get the value of the selected one.
const inputs = document.querySelectorAll('input[type=checkbox]') // or type=radio
for (const input of inputs)
{
if (input.checked)
{
console.log(input.value)
}
}
Also, querySelector() can return the selected one directly, without the need to loop the node list.
const input = document.querySelector('input[type=checkbox]:checked') // or type=radio
if (input)
{
console.log(input.value)
}
you not checking whether the radio is checked or not.As a result document.querySelector returns the first radio with value = "yes" use :checked is querySelector
if (document.querySelector('input.input' + b + ':checked') !== null) {
currentInput = document.querySelector('input.input' + b + ':checked').value;
console.log(currentInput)
}
My solution:
if (document.querySelector('input.input' + b).type == "radio") { //this is a radio input
if (document.querySelector('input[type=radio]:checked')) { //a radio option is selected
showNext();
} else { // no radio option is selected so show error
showRequired.style.display = "block";
}
} else { // not a radio input
}

JavaScript validate at least one radio is checked

I'm building a tabbed for using a mixture of JavaScript and CSS. So far I have validation on my text inputs that ensure a user can't progress unless data has been input.
I have got it working so that my script detected unchecked radios, but the problem is that I want the user to only select one. At the moment even when one gets selected the script won't let you progress because it's seeing the other three as unchecked. How could I add a rule to look at the radios and set valid = true if one is selected - if more or less than 1 then fail?
my function:
function validateForm() {
// This function deals with validation of the form fields
var x, y, i, valid = true;
x = document.getElementsByClassName("tab");
y = x[currentTab].getElementsByTagName("input");
// A loop that checks every input field in the current tab:
for (i = 0; i < y.length; i++) {
// If a field is empty...
if (y[i].type === "text") {
if (y[i].value == "") {
// add an "invalid" class to the field:
y[i].classList.add('invalid');
// and set the current valid status to false:
valid = false;
} else if (!y[i].value == "") {
y[i].classList.remove('invalid');
valid = true;
}
}
if (y[i].type === 'radio') {
//y[i].classList.remove('invalid');
//valid = true;
if (!y[i].checked) {
y[i].classList.add('invalid');
valid = false;
} else {
y[i].classList.remove('invalid');
valid = true;
}
}
}
// If the valid status is true, mark the step as finished and valid:
if (valid) {
document.getElementsByClassName("step")[currentTab].className += " finish";
}
return valid; // return the valid status
}
Do I need to split the validation down into further functions to separate validating different field types?
I think that radio buttons are the way to go. Especially from a UI point of view. Why would you let the user pick more than one item only to tell them later they can't?
Having said that, you can do what you're trying to do with something like this:
function validateForm() {
var checkBoxHolders = document.querySelectorAll(".checkboxholder");
var valid = true;
for (var i = 0; i < checkBoxHolders.length; i++) {
var numChecked = checkBoxHolders[i].querySelectorAll("input[type='checkbox']:checked").length;
if (numChecked === 1) {
checkBoxHolders[i].classList.remove('invalid');
} else {
checkBoxHolders[i].classList.add('invalid');
}
valid = valid && numChecked === 1;
}
document.getElementById('valid').innerHTML = 'I am valid: ' + valid;
}
.invalid {
background-color: orange;
}
<input type="text" id='foo'>
<input type="text" id='bar'>
<div class='checkboxholder'>
First group
<input type="checkbox" id='check1'>
<input type="checkbox" id='check2'>
</div>
<div class='checkboxholder'>
Second group
<input type="checkbox" id='check3'>
<input type="checkbox" id='check4'>
</div>
<button type='button' onclick='validateForm()'>Validate me</button>
<div id='valid'>
</div>
With jQuery, it'd be something like:
if (jQuery('input[name=RadiosGroupName]:checked').length === 0) {
valid = false;
}

Temporarily disable an input field if second input field is filled

I'm attempting to disable an input while the user is filling another input. I've managed to disable one of the two inputs while the other input is being filled in.
The problem is that I want the disabled input to ONLY be disabled WHILE the other input is being typed in.
So if the user changes their mind on the 1st input, they can delete what is in the current input which makes the 2nd input available and the 1st disabled.
JS
var inp1 = document.getElementById("input1");
inp1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("input2").disabled = true;
}
}
HTML
<input type="text" id="input1">
<input type="text" id="input2">
First, I would use input rather than change. Then, you need to set disabled back to false if the input is blank. Your check for whether it's blank is redundant, you just neither either side of your ||, not both. (I'd also use addEventListener rather than assigning to an .onxyz property, so that it plays nicely with others. :-) )
So:
var inp1 = document.getElementById("input1");
inp1.addEventListener("input", function () {
document.getElementById("input2").disabled = this.value != "";
});
<input type="text" id="input1">
<input type="text" id="input2">
...and then of course if you want it to be mutual, the same for input2.
You can achieve this using focus and blur. Below it is done with JQuery.
$(function() {
$('#input1').focus(function(){
$('#input2').prop('disabled', 'disabled');
}).blur(function(){
$('#input2').prop('disabled', '');
});
$('#input2').focus(function(){
$('#input1').prop('disabled', 'disabled');
}).blur(function(){
$('#input1').prop('disabled', '');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input1">
<input type="text" id="input2">
How about using keyup?
Like this;
var inp1 = document.getElementById("input1");
var inp2 = document.getElementById("input2");
inp1.onkeyup = function() { inputValidation(this, inp2); }
inp2.onkeyup = function() { inputValidation(this, inp1); }
function inputValidation(origin, lock) {
var response = hasValue(origin.value);
lock.disabled = response;
}
function hasValue(value) {
return value != "" && value.length > 0;
}
https://jsfiddle.net/8o3wwp6s/
Don't make it harder than it is, this is simple.
var one = document.getElementById('one');
var two = document.getElementById('two');
//checks instantly
var checker = setInterval(function() {
if(two.value !== '') {
one.disabled = true;
} else {
//when its clear, it enabled again
one.disabled = false;
}
if(one.value !== '') {
two.disabled = true
} else {
two.disabled = false;
}
}, 30);
<input id="one">
<input id="two">

Make Javascript instantly/immediately be interchangeable depending on user input

In a js code, i created 3 buttons --- button 1...button 2...button 3
and 3 input fields --- input field 1...input field 2...input field 3
From the beginning of the script all buttons are disabled
button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values
button 2 will only be activated when input field 1 and 3 have numerated values
button 3 will only be activated when input field 2 and 3 have numerated values.
My problem is when i entered a numerated value for input field 1 and 2, button 1 will not activate (in-clickable) even though it was suppose to
And lets say i redid my code and got my whole code backwards so, at the beginning of my script all the buttons were not disabled (you could click on them). Then i made a simple conditional statement like so
input field 1 = if1
input field 2 - if2
if (if1.length = 0 || isNaN(if1) && if2.length = 0 || isNaN(if2) ) {
document.getElementById("button 1").disable = true;
}
Button 1 will not immediately disable until the user clicks on the button. And if the user were to re-enter the appropriate value type in input field 1, button 1 will not activate (be-clickable) because apparently its permanently disabled.
So down to summary, I'm asking if there is a way to make JavaScript be instantly interactive. Such as a web browser search bar. The moment you type something, you immediately get a list of possible questions and when you don't type anything in them the list disappears and the browser regains its original state.
Any Advice/help shall be greatly appreciated
Due to Life and its problems my code some how got deleted. Thus the lack of code and bunch of words. Sorry.
Generic solution (using attributes)
You can check the answer below which is using oninput event and the attributes to handle your situation effectively.
I have added a data-target attribute to link the elements together to fit with your requirement.
For an instance, to match the rule button 1 will only be activated (you can click on it) when input field 1 and 2 have numerated values, data-target of button1 is id of textbox 1 & 2.
Working snippet:
function checkInput() {
var dataTarget = 'data-target';
var elm = event.target;
var targetAttrs = getAttr(elm, dataTarget);
if(targetAttrs) {
var targetButtons = targetAttrs.split(',');
for(var i = 0; i < targetButtons.length; i++) {
var button = document.getElementById(targetButtons[i]);
targetAttrs = getAttr(button, dataTarget);
if(targetAttrs) {
var targetTextBoxes = targetAttrs.split(',');
var valid = true;
for(var j = 0; j < targetTextBoxes.length; j++) {
var textBox = document.getElementById(targetTextBoxes[j]);
if(textBox) {
valid = isValidNumber(textBox.value);
}
if(!valid) {
break;
}
}
button.disabled = !valid;
}
}
}
}
function isValidNumber(val) {
return (val && val.length > 0 && !isNaN(val));
}
function getAttr(elm, name){
var val;
if(elm) {
var attrs = elm.attributes;
for(var i = 0; i < attrs.length; i++) {
if(attrs[i].name === name) {
val = attrs[i].value;
break;
}
}
}
return val;
}
<div>
<input type="text" id="textBox1" oninput="checkInput()" data-target="button1,button2" />
</div>
<br/>
<div>
<input type="text" id="textBox2" oninput="checkInput()" data-target="button1,button3" />
</div>
<br/>
<div>
<input type="text" id="textBox3" oninput="checkInput()" data-target="button2,button3" />
</div>
<br/>
<input type="button" id="button1" value="Submit" data-target="textBox1,textBox2" disabled />
<input type="button" id="button2" value="Submit" data-target="textBox1,textBox3" disabled />
<input type="button" id="button3" value="Submit" data-target="textBox2,textBox3" disabled />
Note: With this code, when you add more elements, you don't need to change/add any Javascript code. Just add the elements and attributes
var field1 = document.getElementById('if1');
var field2 = document.getElementById('if2');
var field3 = document.getElementById('if3');
var button1 = document.getElementById('button1');
var button2 = document.getElementById('button2');
var button3 = document.getElementById('button3');
field1.addEventListener('input', function(){
if(this.value!= '' && field2.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button2.disabled = false;
else
button2.disabled = true;
});
field2.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button1.disabled = false;
else
button1.disabled = true;
if(this.value!= '' && field3.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
field3.addEventListener('input', function(){
if(this.value!= '' && field1.value!='')
button2.disabled = false;
else
button2.disabled = true;
if(this.value!= '' && field2.value!='')
button3.disabled = false;
else
button3.disabled = true;
});
<input type="text" id="if1">
<input type="text" id="if2">
<input type="text" id="if3">
<br>
<button type="button" id="button1" disabled="true">Button1</button>
<button type="button" id="button2" disabled="true">Button2</button>
<button type="button" id="button3" disabled="true">Button3</button>
Here is how you do it
Disabling a html button
document.getElementById("Button").disabled = true;
Enabling a html button
document.getElementById("Button").disabled = false;
Demo Here
Edited
Try this...
You apply addEventListener to that DOM object:
document.getElementById("IDTeam").addEventListener("change", function() {//call function here});
For IE
document.getElementById("IDTeam").attachEvent("onchange", function() {//call function here} );

Disabled a input when another input is filled in

How to Disabled a input (with javascript) when another input is filled in
Exemple :
http://www.pct.com.tn/index.php?option=com_searchproduct&view=searchproduct&ctg=M&Itemid=48&lang=fr#b
Thanks
Monitor for on input with javascript and compare the value.
window.onload = function(){
var boxOne = document.getElementById('inputOne');
var boxTwo = document.getElementById('inputTwo');
boxOne.oninput = function(){
if(this.value != ""){
//if there is a value
//change the background color (optional)
boxTwo.style.backgroundColor = '#999';
boxTwo.disabled = true;
}
else{
//if there isn't a value
boxTwo.disabled = false;
//change the background color (optional)
boxTwo.style.backgroundColor = "transparent";
}
};
};
<input type="text" id="inputOne" placeholder="type to disable other">
<input type="text" id="inputTwo">
You can acheive this by using jquery for keydown event. I have done some sample code based on my understanding to your question. Assume you have two text boxes, on entering a text to any of textbox will lock the other
<input type = 'text' id='firstTextBox'/>
<input type = 'text' id='secondTextBox'/>
<script>
$("input").keydown(function(){
if($("#firstTextBox").val()!= '')
{
$('#secondTextBox').attr('disable', 'disable');
}
else if($("#secondTextBox").val()!= '')
{
$('#firstTextBox').attr('disable', 'disable');
}
else if($("#firstTextBox").val()== '' && $("#secondTextBox").val()== '')
{
$('#firstTextBox').removeAttr('disable');
$("#secondTextBox").removeAttr('disable');
}
});
</script>

Categories