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">
Related
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.
I have a bunch of checkboxes, radio buttons, and text fields on my page. They all have '_boom' appended to the end of the id. I want to detect if any one of these inputs is not its original value, and if so, apply CSS to a button called 'save' on the page. Then, if the user reverts any changes they made and all inputs have their original values, I want to undo the CSS.
I've gotten close with the code below. But let's say I check 3 checkboxes. Upon checking the 1st box, the CSS changes. Good! I check the 2nd and 3rd boxes. The CSS stays the same. Good! But then I uncheck ONE of the boxes, and the CSS reverts. Bad! The CSS should only revert if I undo every change.
$('[id*="_boom"]').change(function() {
var sType = $(this).prop('type'); //get the type of attribute we're dealing with
if( sType === "checkbox" || sType === "radio" ){ //checkbox or radio type
var originalCheckedState = $(this).prop("defaultChecked");
var currentCheckedState = $(this).prop("checked");
if(currentCheckedState !== originalCheckedState){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
if( sType === "text" ){ //text type
var originalValue = $(this).prop("defaultValue");
var currentValue = $(this).val();
if(currentValue !== originalValue){
$("a#save").css("color","#CCCCCC");
}
else {
$("a#save").css("color","black");
}
}
});
#save {
color: black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
There are many possible improvements in your code to make it cleaner and standardized. Things like instead of relying on id you should consider class attribute and all... but I will not revamp your code. Here's the solution to your existing code.
The idea is loop through all the form elements and if atleast one of the elements is different than its default value then set the flag and come out of the loop.
At the end, check for that flag and set the css accordingly.
For this, I have enclosed your elements into a form form1.
$("#form1 :input").change(function() {
var changed = false;
formElems = $("#form1 :input");
for(i=0;i<formElems.length; i++){
var sType = $(formElems[i]).prop("type");
if(sType === "checkbox" || sType === "radio"){
if($(formElems[i]).prop("defaultChecked") !== $(formElems[i]).prop("checked")){
changed = true;
break;
}
}else if(sType === "text"){
if($(formElems[i]).prop("defaultValue") !== $(formElems[i]).val()){
changed = true;
break;
}
}
}
if(changed){
$("a#save").css("color","#CCCCCC");
}else{
$("a#save").css("color","black");
}
});
And here is your form
<form id="form1">
<input type="checkbox" id="check_boom" />
<input type="checkbox" id="check1_boom" />
<input type="checkbox" id="check2_boom" />
<input type="radio" id="radio_boom" />
<input type="text" defaultValue="test" id="text_boom" />
<input type="text" defaultValue="test" id="text2_boom" />
Save
</form>
The problem is, when one of them change to its original value, it doesn't mean there is no change.
So, in your else code block, you should check all the inputs, if all of them are the original values, remove the 'save' class from the button, otherwise, keep it.
var isChanged = function ($element) {
var sType = $element.prop('type');
if (sType === "checkbox" || sType === "radio") {
var originalCheckedState = $element.prop("defaultChecked");
var currentCheckedState = $element.prop("checked");
if (currentCheckedState !== originalCheckedState) {
return true;
} else {
return false;
}
} else if( sType === "text" ) {
var originalValue = $element.prop("defaultValue");
var currentValue = $element.val();
if (currentValue !== originalValue) {
return true;
} else {
return false;
}
}
};
var $inputs = $('[id*="_boom"]');
var isAnyChanged = function () {
$inputs.each(function () {
if (isChanged($(this))) {
return true;
}
});
return false;
};
$inputs.change(function () {
if (isChanged($(this))) {
$("a#save").css("color","#CCCCCC");
} else if (!isAnyChanged()) {
$("a#save").css("color","black");
}
});
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>
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;
}
I am making a simple form and i have this code to clear the initial value:
Javascript:
function clearField(input) {
input.value = "";
};
html:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);"/>
But what i don't want is that if the user fills the input but clicks it again, it gets erased. I want the field to have the starter value "Name" only if the input is empty. Thank you in advance!
do like
<input name="name" id="name" type="text" value="Name"
onblur="fillField(this,'Name');" onfocus="clearField(this,'Name');"/>
and js
function fillField(input,val) {
if(input.value == "")
input.value=val;
};
function clearField(input,val) {
if(input.value == val)
input.value="";
};
update
here is a demo fiddle of the same
Here is one solution with jQuery for browsers that don't support the placeholder attribute.
$('[placeholder]').focus(function() {
var input = $(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
}
}).blur(function() {
var input = $(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur();
Found here:
http://www.hagenburger.net/BLOG/HTML5-Input-Placeholder-Fix-With-jQuery.html
This may be what you want:
Working jsFiddle here
This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.
As soon as the box is clicked, the default text is cleared and text color set to black.
If text is erased, the default text string is replaced and light grey color reset.
HTML:
<input id="fname" type="text" />
jQuery/javascript:
$(document).ready(function() {
var curval;
var fn = $('#fname');
fn.val('Enter your name here').css({"color":"lightgrey"});
fn.focus(function() {
//Upon ENTERING the field
curval = $(this).val();
if (curval == 'Enter your name here' || curval == '') {
$(this).val('');
$(this).css({"color":"black"});
}
}); //END focus()
fn.blur(function() {
//Upon LEAVING the field
curval = $(this).val();
if (curval != 'Enter your name here' && curval != '') {
$(this).css({"color":"black"});
}else{
fn.val('Enter your name here').css({"color":"lightgrey"});
}
}); //END blur()
}); //END document.ready
HTML:
<input name="name" id="name" type="text" value="Name" onfocus="clearField(this);" onblur="fillField(this);"/>
JS:
function clearField(input) {
if(input.value=="Name") { //Only clear if value is "Name"
input.value = "";
}
}
function fillField(input) {
if(input.value=="") {
input.value = "Name";
}
}
var input= $(this);
input.innerHTML = '';
OP's question is no longer relevant- the question was asked in 2013 when the placeholder attribute wasn't well supported.
Nowadays you can just use <input placeholder="Your text here">
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#htmlattrdefplaceholder