Make Javascript instantly/immediately be interchangeable depending on user input - javascript

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} );

Related

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">

Unchecking of the checked checkboxes on another button click

I want the checked checkboxes to be unchecked when clicking another button:
Below is the HTML
<input type="checkbox" name="checkb" id="Agent" value="Agent"> type=Agent
<br />
<input type="checkbox" name="checkb" id="Customer" value="Customer"> type=Customer
<br />
<input type="checkbox" name="checkb" id="Phone" value="Phone"> type=Phone
<br />
<input type="checkbox" name="checkb" id="ID_Card" value="ID_Card"> type=ID_Card
<br />
<input type=datetime id="Start_Date" value="" placeholder="Start_Date" />
<input type=datetime id="End_Date" value="" placeholder="End_Date" />
<button id="date">
Interval
</button>
On clicking of the Interval button if any checkboxes are checked they should get unchecked.
Below is the event listener for the Interval button:
var check1 = document.getElementById("Agent");
var check2 = document.getElementById("Customer");
var check3 = document.getElementById("Phone");
var check4 = document.getElementById("ID_Card");
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
if (check1.checked) {
var ischecked1 = check1.checked;
check1.checked != ischecked1;
}
if (check2.checked) {
var ischecked2 = check2.checked;
check2.checked != ischecked2;
}
if (check3.checked) {
var ischecked3 = check3.checked;
check3.checked != ischecked3;
}
if (check4.checked) {
var ischecked4 = check4.checked;
check4.checked != ischecked4;
}
});
}
Below code runs without any errors, but the boxes do not get unchecked if they are checked.
Below is the fiddle
Your statements are just evaluating as booleans, not performing assignments:
check1.checked != ischecked1; // this returns a boolean, doesn't do any assignment
You want to do this to toggle the checked state:
check1.checked = !ischecked1;
Same thing for other checkboxes.
There's also no need to create the extra variables, you can just do the toggling and reading directly:
check1.checked = !check1.checked;
Since you're only toggling checkboxes when they are checked, you can just directly set them to false as well.
if (check1.checked) check1.checked = false;
Instead of having if statements, you can use array iteration to do the toggling:
[check1, check2, check3, check4].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
// or query the checkboxes directly and do the same
[...document.querySelectorAll('input[type="checkbox"]')].forEach(check => {
if (check.checked) {
check.checked = false;
}
});
Your mistake is in this line:
check1.checked != ischecked1;
This actually means "compare if check1.checked is not equal to ischecked1".
Most simple solution would be to remove the if statement and just do this:
check1.checked = !check1.checked
This means "set check1.checked to the opposite of check1.checked".
Since all checkboxes have the same name you could also collect all checkboxes by requesting them by name and use a loop to walk through them. A small example:
// Collect all checkboxes with a CSS selector that matches all input
// elements with a name attribute that's equal to "checkb"
var checkboxes = document.querySelectorAll('input[name="checkb"]');
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
// this is a for loop, it will run for as long as i
// is smaller than the amount of found checkboxes (checkboxes.length)
for(var i = 0; i < checkboxes.length; i++) {
// Get the checkbox from the checkboxes collection
// collection[i] means get item from collection with index i
var checkbox = checkboxes[i];
// Revert the .checked property of the checkbox
checkbox.checked = !checkbox.checked;
}
});
}
By the looks of it you just want to uncheck everything on click of button
you can just do this
var newBtn = document.getElementById("date");
if (newBtn) {
newBtn.addEventListener("click", function() {
document.getElementById("Agent").checked =
document.getElementById("Customer").checked =
document.getElementById("Phone").checked =
document.getElementById("ID_Card").checked = false;
});
}

How can I apply CSS to a link if at least one input is not original, and undo that change if all inputs are original?

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 disable a text-box when clicking on other radio-buttons using a single function in javaScript?

I want to disable the text-box (its id is text1), when clicking on other radio buttons using a single function. According to my code the text-box is showing when the user is clicking on the radio button (its id is rd_other). But when the user clicking on the other radio buttons, after clicking the above radio button (its id is rd_other) the text-box is not disabling.
Here is HTML my code.
<input type="radio" name="rd_other" id="rd_other" value="rd_other" data-toggle="radio" onchange="enableText()">Other (please specify)
<input type="text" name="text1" id="text1"class="form-control input-sm jfl" readonly="readonly" style="display: none;"/>
<input type="radio" name="rdn1" id="rdn1" value="rdn1" data-toggle="radio">I haven't received the disc
<input type="radio" name="rdn2" id="rdn2" value="rdn2" data-toggle="radio">I lost or damaged the protective cover
Here is my javaScript code.
function enableText() {
var text1 = document.getElementById('text1');
text1.readOnly = false;
text1.style.display = 'block';
}
Firstly, to make sure there are no confusions, onchange will only fire when a radio button is selected.
Secondly, you would have to hook up an onchange function to the two other radio buttons. The function below should work.
function disableText() {
var text1 = document.getElementById('text1');
text1.readOnly = true;
text1.style.display = 'none';
}
like this
function disable() {
//one radio button
var radio = document.getElementById("your_radio_button_id");
var checkbox = document.getElementById("your_checkbox_id");
if (radio.checked == true) {
checkbox.disabled = true;
}
}
or like this
function disable() {
var radios = document.getElementsByName("your_radio_button_group_name");
var checkbox = document.getElementById("your_checkbox_id");
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked == true) {
checkbox.disabled = true;
}
}
}
You can fix this like this:
window.enableText = function(e) {
var text1 = document.getElementById('text1');
if(e.id == "rd_other2") {
text1.readOnly = false;
text1.style.display = 'block';
}
else{
text1.readOnly = true;
text1.style.display = 'none';
}
}
please check the full example here :)

Javascript "next" button with checkbox "show hide Div"

Hello I have a site with several Questions and i want an survey to click throw a few "divs" and with a check box if they want to give no answer:
!!! Every thing works but if i type in 0 in the input field the alert comes but then i Can't get further ? WHY !!!
My code for the Checkbox:
<input type="checkbox" id="CheckBoxFeld" name="CheckBox2" >
My Code For the Next Button:
<input type="button" value="Next">
My Code for the TEST:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
And my Code for the ShowHide Function:
// Show and Hide Div
function showHideDiv(idHide, idShow){
//document.getElementById(idShow).style.display = "block";
//document.getElementById(idHide).style.display = "none";
document.getElementById(idHide).style.visibility = "hidden";
document.getElementById(idShow).style.visibility = "visible";
}
Try checking the length of the value:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field.length == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
}
Try using, onclick="check2();" instead of onclick="onclick=check2();"
<input type="button" class="Button" value="Next" onclick="check2();">
Javascript:
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && checkbox2 == false){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
A few issues
poor practice and illegal html to wrap a button in a link
if you use a link, return false to avoid the HREF to be followed. In this case the browser would likely go to top and some browsers would partially unload the page, making for example animations stop
Like this
Next
OR
<input type="button" onclick="check2()" value="Next">
using
function check2(){
var field = document.Survey.Answer2.value;
var checkbox2 = document.Survey.CheckBox2.checked;
if (field == 0 && !checkbox2){
alert("Please answer question 2");
}
else{
showHideDiv('Question2', 'Question3');
}
return false;
}
But only if your field contains 0.
If you want to test if it is empty, you need field.length==0 instead

Categories