How do I enable input2 if enable 1 has input within it (basically re-enabling it), I'm still a beginner and have no idea to do this.
<form id="form1">
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
<script language="javascript">
function valid() {
var firstTag = document.getElementById("text1").length;
var min = 1;
if (firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
}
}
//once input from text1 is entered launch this function
</script>
</form>
if i understand your question correctly, you want to enable the second input as long as the first input have value in it?
then use dom to change the disabled state of that input
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
//enable the text2 tag
document.getElementById("text2").disabled = false;
}
Please try this code :
var text1 = document.getElementById("text1");
text1.onchange = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("text2").disabled = false;
} else {
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1">
<input type="text" id="text2" disabled="disabled">
I think you should use .value to get the value. And, then test its .length. That is firstTag should be:
var firstTag = document.getElementById("text1").value.length;
And, the complete function should be:
function valid() {
var min = 1;
var firstTag = document.getElementById("text1");
var secondTag = document.getElementById("text2");
if (firstTag.length > min) {
secondTag.disabled = false
} else {
secondTag.disabled = true
}
}
Let me know if that works.
You can use the .disabled property of the second element. It is a boolean property (true/false).
Also note that you need to use .value to retrieve the text of an input element.
Demo:
function valid() {
var text = document.getElementById("text1").value;
var minLength = 1;
document.getElementById("text2").disabled = text.length < minLength;
}
valid(); // run it at least once on start
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2">
I would just change #Korat code event to keyup like this:
<div>
<input type="text" id="in1" onkeyup="enablesecond()";/>
<input type="text" id="in2" disabled="true"/>
</div>
<script>
var text1 = document.getElementById("in1");
text1.onkeyup = function () {
if (this.value != "" || this.value.length > 0) {
document.getElementById("in2").disabled = false;
} else {
document.getElementById("in2").disabled = true;
}
}
</script>
I tried to create my own so that I could automate this for more than just two inputs although the output is always set to null, is it that I cannot give text2's id from text1?
<div id="content">
<form id="form1">
<input type="text" id="text1" onkeyup="valid(this.id,text2)">
<input type="text" id="text2" disabled="disabled">
<script language ="javascript">
function valid(firstID,secondID){
var firstTag = document.getElementById(firstID).value.length;
var min = 0;
if(firstTag > min)
//if the text entered is longer than 1 alert to screen
{
document.getElementById(secondID).disabled = false;
}
if(firstTag == 0){
document.getElementById(secondID).disabled = true;
}
}
//once input from text1 is entered launch this function
</script>
</form>
First, you have to correct your code "document.getElementById("text1").length" to "document.getElementById("text1").value.length".
Second, there are two ways you can remove disabled property.
1) Jquery - $('#text2').prop('disabled', false);
2) Javascript - document.getElementById("text2").disabled = false;
Below is the example using javascript,
function valid() {
var firstTag = document.getElementById("text1").value.length;
var min = 1;
if (firstTag > min) {
document.getElementById("text2").disabled = false;
}
else
{
document.getElementById("text2").disabled = true;
}
}
<input type="text" id="text1" onkeyup="valid()">
<input type="text" id="text2" disabled="disabled">
If I understand you correctly, what you are asking is how to remove the disabled attribute (enable) from the second input when more than 1 character has been entered into the first input field.
You can to use the oninput event. This will call your function every time a new character is added to the first input field. Then you just need to set the second input field's disabled attribute to false.
Here is a working example.
Run this example at Repl.it
<!DOCTYPE html>
<html>
<body>
<!-- Call enableInput2 on input event -->
<input id="input1" oninput="enableInput2()">
<input id="input2" disabled>
<script>
function enableInput2() {
// get the text from the input1 field
var input1 = document.getElementById("input1").value;
if (input1.length > 1) {
// enable input2 by setting disabled attribute to 'false'
document.getElementById("input2").disabled = false;
} else {
// disable input2 once there is 1 or less characters in input1
document.getElementById("input2").disabled = true;
}
}
</script>
</body>
</html>
NOTE: It is better practice to use addEventListener instead of putting event handlers (e.g. onclick, oninput, etc.) directly into HTML.
Related
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">
I am trying to run a simple if-statement that checks if the input's value (what is typed in) is at least 5 and then to show the submit button. I tried using the keyup function to detect the value as it is being typed in.
Does anyone see what I am doing wrong?
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
if (nameInput => 5) {
$('#submit-package').fadeBoolToggle();
}
//$('#package-name-input').val().fadeBoolToggle(length > 5);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
You can pass condition as your function parameter, also you should change => to >=
jQuery.fn.fadeBoolToggle = function(bool) {
return bool ? this.fadeIn(400) : this.fadeOut(400);
}
$('#submit-package').hide();
$('#package-name-input').on('keyup', function() {
var nameInput = $(this).val().length;
$('#submit-package').fadeBoolToggle(nameInput >= 5);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="gen-input" id="package-name-input">
<div class="proceed-btn sans-pro" id="submit-package">
<span class="proceed-btn-text">SUBMIT</span>
</div>
Do it like:
use keyup() method
var i = 0;
$('#target').hide();
$('#text').keyup(function(event) {
i++;
if(i == 5)
{
$('#target').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" id="text">
<div id="target">
<input type="button" value="submit">
</div>
This looks like a syntax error. Greater than or equal to is expressed as >=, not =>.
I want to set a minimum number of text that is written in a text box.
Normally we use the min property of html. But I don't want it.
Can anybody help me with the JavaScript code which check the number of text written in a text box and if it is lesser than 7 and greater than 21 an alert box would be shown. Or else it wont
<input type="text" id="txt">
<input type="button" onClick="myFunction()">
Js
function myFunction() {
.....
}
I know only this much.
Please help
You can use pattern attribute of HTML5
This will set minimum characters required to 1 and max characters required
to 15
<input type="text" id="txt" pattern="[a-z]{1,15}>
function myFunction() {
if ($('#txt').val().length < 21 && $('#txt').val().length > 7) alert("yez");
}
$('button').on('click', function() {
myFunction()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txt">
<button>click</button>
this should work - it checks the length of the content in your #txt HTML element. If its greater than 7 and smaller than 21 it will alert yez
i added snippet which is counting only number of real 'words' empty spaces are omitted.
function wordCount(text) {
totalCount = 0;
words = text.split(' ')
words.forEach(function(word) {
if (word.length > 0) {
totalCount++;
}
})
return totalCount;
}
window.myFunction = function() {
textarea = document.getElementById('txt');
words = wordCount(textarea.value);
if(words < 7 || words > 21) {
alert('Wrong number of words');
}
}
<input type="text" id="txt">
<input type="button" onClick="myFunction()" value="Submit">
You can trigger an event on blur that means, when the text box loses focus
$(document).ready(function(){
$('#text-box').blur(function(){
var value = $('#text-box').val();
if(value.length < 7 || value.length > 21){
alert("Invalid length");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text-box">
function validate(){
x=document.myForm
input=x.myInput.value
if (input.length>5){
alert("The field cannot contain more than 5 characters!")
return false
}else {
return true
}
}
I have a form that the user can use to enter 5 numbers. I have given all five input boxes the same id and a different name. I want to perform a validation of each input box. I want to be able to change background color of the input boxes based on the number they enter. For example, every input box with number in range 0-5 should change its background color to red and those between 6-10 should be green.
I have been able to write a code that would cause the color to change for one input box, however I cannot think of a way to optimize my code and avoid having to write the same code five times. Here is what I have got so far:
Form:
<form id="numbers">
Number1: <input id ="color" name="num1" type="number" onchange="check();">
<br><br>
Number2: <input id ="color" name="num2" type="number" onchange="check();">
<br><br>
Number3: <input id ="color" name="num3" type="number" onchange="check();">
<br><br>
</form>
Function:
function check() {
var inputVal = document.getElementById("color").value;
if (inputVal=="" || inputVal ==null) {
document.getElementById("color").style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
document.getElementById("color").style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
document.getElementById("color").style.backgroundColor = "green";
}
}
If I change inputVal to an array and use a for loop to save values of document.getElementById("color").value, it will save the first number entered by the user five times and will only update the color of the first box.
Here is what I tried:
var inputVal = new Array();
for(var i=0; i<5; i++) {
inputVal[i]= document.getElementById("color").value;
}
You can have the clicked element as a parameter
function check(element) {
var inputVal = element.value;
if (inputVal=="" || inputVal ==null) {
element.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
element.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
element.style.backgroundColor = "green";
}
}
and pass the argument for each input
<form id="numbers">
Number1: <input id ="color1" name="num1" type="number" onchange="check(this);" />
<br/><br/>
Number2: <input id ="color2" name="num2" type="number" onchange="check(this);" />
<br/><br/>
Number3: <input id ="color3" name="num3" type="number" onchange="check(this);" />
<br/><br/>
</form>
But ID's must be unique. Here is a FIDDLE
You can use jquery to achieve this. First remove all the id value, they should not be same. Then use $('input').on('change', function (){
$(this).css("background-color","red")})...
This way you can change colors based on values.
First, you can simplify your JavaScript by designating it to target this, since you're executing the function onchange.
Second, you should never leave an open-ended IF...THEN...ELSE, just bad habit for when they can result in BIG changes.
Third, as noted by others, id must be unique across the page.
Give this a try:
function check(tar) {
var inputVal = tar.value;
if(inputVal == '' || inputVal == null) {
tar.style.backgroundColor = 'white';
} else if(inputVal >= 0 && inputVal <= 5) {
tar.style.backgroundColor = 'red';
} else if(inputVal >= 6 && inputVal <= 10) {
tar.style.backgroundColor = 'green';
} else {
tar.style.backgroundColor = 'yellow';
}
}
<form id="numbers">
Number1: <input class ="color" name="num1" type="number" onchange="check(this);" />
<br><br>
Number2: <input class ="color" name="num2" type="number" onchange="check(this);" />
<br><br>
Number3: <input class ="color" name="num3" type="number" onchange="check(this);" />
</form>
Here's a JSFiddle: http://jsfiddle.net/v1daq6sx/
I hope this helps. ^^
When the user changes their value it fires the function giveInputColor. You can use this one function to check infinitely many inputs with the class hello.
Working Example: http://codepen.io/anon/pen/bNqraN
HTML
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
<input class="hello"/>
jQuery
$('input.hello').keyup(function(event) {
/* Act on the event */
var value = $(this).val();
$(this).css('backgroundColor', giveInputColor(value));
});
function giveInputColor(value) {
// Give Input a color based on value parameter
if (value >= 0 && value <= 5) return 'Red';
else if (value >= 6 && value <= 10) return 'Green';
else return 'White';
}
Without going into any major redesign of your logic (you could make it more efficient, but I focused on just getting the behavior that you are looking for), you can simply add the function to each element with an event listner, and then use e.target to determine which element is the one that changed and triggered the function call. Note - the aproach is a little more streamlined in jQuery, but I will stick with native JS here.
First off, lets give all of these inputs a common class ("number-field"), to make them easier to find:
<form id="numbers">
Number1: <input id="num1" name="num1" type="number" class="number-field">
<br><br>
Number2: <input id="num2" name="num2" type="number" class="number-field">
<br><br>
Number3: <input id="num3" name="num3" type="number" class="number-field">
<br><br>
</form>
I also made the id attributes unique and remover the onchange attributes, since we whill add the event listener dynamically.
Then we needed updated the check() function to accept the change event as a parameter (e) which is used in the first line of the function to determine the element that triggered the change event, using e.target (note - e.srcElement is to support older versions of IE).
function check(e) {
var inputEl = e.target || e.srcElement;
var inputVal = inputEl.value;
if (inputVal == "" || inputVal == null) {
this.style.backgroundColor = "white";
}
else if (inputVal >= 0 && inputVal <= 5) {
this.style.backgroundColor = "red";
}
else if (inputVal >= 6 && inputVal <= 10) {
this.style.backgroundColor = "green";
}
}
The rest of the code is simply updated to point to the variable that was determined in the first line.
Finally, the function needed to be bound to the number inputs, so, using the class attribute that I added earlier, you can find all of those inputs, cycle through them, and add event listeners to each one.
var numInputs = document.getElementsByClassName("number-field");
for (i = 0; i < numInputs.length; i++) {
numInputs[i].addEventListener('change', check);
}
I checked it out locally and it is behaving the way that I believe that you were wanting it to.
There are a series of textboxes like:
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
<input type="text" class="jq-textBox" />
User can fill up the textbox values from top to bottom order. Only first textbox is required and all other textboxes are optional.
Allowed order to fill textbox values:
1st
1st & 2nd
1st, 2nd & 3rd
and likewise in sequence order
Dis-allowed order:
2nd
1st & 3rd
1st, 2nd & 4th
This means that user needs to fill up the first textbox only or can fill up the other textboxes in sequential order. User can NOT skip one textbox and then fillup the next one.
How to validate this in javascript/jQuery?
Any help is highly appreciated!
I would personaly use the disabled html attribute.
See this jsFiddle Demo
html
<form>
<input type="text" class="jq-textBox" required="required" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="text" class="jq-textBox" disabled="disabled" />
<input type="submit" />
</form>
(Note the required attribute for HTML5)
jquery
$('input.jq-textBox').on('keyup', function(){
var next = $(this).next('input.jq-textBox');
if (next.length) {
if ($.trim($(this).val()) != '') next.removeAttr('disabled');
else {
var nextAll = $(this).nextAll('input.jq-textBox');
nextAll.attr('disabled', 'disbaled');
nextAll.val('');
}
}
})
Also see nextAll() jquery Method
Edit :
If you want to hide the disabled inputs in order to show them only when the previous input is filled, just add this css :
input[disabled] {
display: none;
}
Demo
You can iterate over the list backwards to quickly figure out whether there is a gap.
var last = false,
list = $(".jq-textBox").get().reverse();
$.each(list, function (idx) {
if ($(this).val() !== "") {
last = true;
}
else if (last) {
alert("you skipped one");
}
else if (list.length === idx + 1) {
alert("must enter 1");
}
});
http://jsfiddle.net/rnRPA/1/
Try
var flag = false, valid = true;
$('.jq-textBox').each(function(){
var value = $.trim(this.value);
if(flag && value.length !=0){
valid = false;
return false;
}
if(value.length == 0){
flag = true;
}
});
if(!valid){
console.log('invalid')
}
Demo: Fiddle
You can find all inputs that are invalid (filled in before the previous input) this way:
function invalidFields() {
return $('.jq-textBox')
.filter(function(){ return !$(this).val(); })
.next('.jq-textBox')
.filter(function(){ return $(this).val(); });
}
You can then test for validity:
if (invalidFields().length) {
// invalid
}
You can modify invalid fields:
invalidFields().addClass('invalid');
To make the first field required, just add the HTML attribute required to it.
I think a more elegant solution would be to only display the first textbox, and then reveal the second once there is some input in the first, and then so on (when they type in the second, reveal the third). You could combine this with other solutions for testing the textboxes.
To ensure the data is entered into the input elements in the correct order, you can set up a system which modifies the disabled and readonly states accordingly:
/* Disable all but the first textbox. */
$('input.jq-textBox').not(':first').prop('disabled', true);
/* Detect when the textbox content changes. */
$('body').on('blur', 'input.jq-textBox', function() {
var
$this = $(this)
;
/* If the content of the textbox has been cleared, disable this text
* box and enable the previous one. */
if (this.value === '') {
$this.prop('disabled', true);
$this.prev().prop('readonly', false);
return;
}
/* If this isn't the last text box, set it to readonly. */
if(!$this.is(':last'))
$this.prop('readonly', true);
/* Enable the next text box. */
$this.next().prop('disabled', false);
});
JSFiddle demo.
With this a user is forced to enter more than an empty string into an input field before the next input is essentially "unlocked". They can't then go back and clear the content of a previous input field as this will now be set to readonly, and can only be accessed if all following inputs are also cleared.
JS
var prevEmpty = false;
var validated = true;
$(".jq-textBox").each(function(){
if($(this).val() == ""){
prevEmpty = true;
}else if($(this).val() != "" && !prevEmpty){
console.log("nextOne");
}else{
validated = false;
return false;
}
});
if(validated)
alert("ok");
else
alert("ERROR");
FIDDLE
http://jsfiddle.net/Wdjzb/1/
Perhaps something like this:
var $all = $('.jq-textBox'),
$empty = $all.filter(function() { return 0 === $.trim(this.value).length; }),
valid = $empty.length === 0
|| $empty.length != $all.length
&& $all.index($empty.first()) + $empty.length === $all.length;
// do something depending on whether valid is true or false
Demo: http://jsfiddle.net/3UzHf/ (thanks to Arun P Johny for the starting fiddle).
That is, if the index of the first empty item plus the total number of empties adds up to the total number of items then all the empties must be at the end.
This is what you need :
http://jsfiddle.net/crew1251/jCMhx/
html:
<input type="text" class="jq-textBox" /><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/><br />
<input type="text" class="jq-textBox" disabled/>
js:
$(document).on('keyup', '.jq-textBox:first', function () {
$input = $(this);
if ($input.val()!='')
{
$('input').prop('disabled',false);
}
else {
$('input:not(:first)').prop('disabled',true);
}
});
var checkEmpty = function ()
{
var formInvalid = false;
$('#MyForm').each(function () {
if ($(this).val() === '') {
formInvalid = true;
}
});
if (formInvalid) {
alert('One or more fields are empty. Please fill up all fields');
return false;
}
else
return true;
}