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

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

Related

When using a form that takes to the main website

I am doing a form window before you get in the main website so I tried to make it so that if you don't fill any of the spaces it will open a window alert asking to fill those spaces. Plus I'd like that you would only get to the main website if you fill all the spaces but yet the button on the form window always takes to the main website without requiring filling of the camps.
On the button I wrote this:
<a href="index1.html">
<input type="button" value="Terminar" onclick = location.href='index1.html' >
</a>
and on the js window I wrote the window alert command to each one of the categories:
if(frm.name.value=="" || frm.name.value==null || frm.name.length < 3) {
alert("Please write your first name ")
frm.name.focus();
return false;
It seems you are trying to validate the an input field based on a few criteria.
Your question is not clear. Is this what you are trying to do?
function validateInput() {
if (frm.value == "" || frm.value == null || frm.value.length < 3) {
alert("Please write your first name ")
frm.focus();
} else
location.href = 'index1.html'
}
<input type="text" id="frm" placeholder="Please write your first name" />
<input type="button" value="Terminar" onClick="validateInput()">
You want something like this. In your code the input is wrapped in an a tag. so it will always trigger the event. Adding a button the trigger the event will help.
button = document.getElementById('enter');
input = document.getElementById('fill');
button.onclick = function() {
if (input.value == null || input.value == "" || input.value == " ") {
alert('Please write your first name');
} else {
window.location.href = 'index1.html';
}
};
<input id="fill">
<button id="enter">Enter</button>

Make alert appear when start typing input

I am trying to make something happen only when a user inputs data into an input element that has been created. However I don't want to validate that data has been inputted or make the user press a button to check if data has been inputted, I want something to happen as soon as the first data value is typed in the input field. I decide to just use a demo of something similar that I want to create - to cut out the clutter:
I have tried:
var input = document.getElementById("input");
if(input == ""){
alert("no value");
}else{
input.style.background = "blue";
}
<input type="text" id="input">
But nothing seems to be working. For what reason is it not working?
So in this example I would only want the background to be blue when the first data value is typed in.
I also tried:
var input = document.getElementById("input");
if(input.length == 0){
alert("no value");
}else{
input.style.background = "blue";
}
and:
var input = document.getElementById("input");
if(input == undefined){
alert("no value");
}else{
input.style.background = "blue";
}
as well as variations using != and !==
Is it something small I'm missing?
You were checking the actual element, not it's value. And, you didn't have any event listener set up for the element. But, it doesn't make much logical sense to check for no value after a value has been entered.
// When data is inputted into the element, trigger a callback function
document.getElementById("input").addEventListener("input", function(){
// Check the value of the element
if(input.value == ""){
alert("no value");
}else{
input.style.background = "blue";
}
});
<input type="text" id="input">
Try this,
jQuery
$('#input').keyup(()=>{
if($('#input').val() == ""){
alert("no value");
} else{
$('#input').css({backgroundColor: 'your-color'});
}
});
Hello you can try this
<input type="text" id="input" onkeyup="inputfun()">
<script type="text/javascript">
function inputfun(){
var input = document.getElementById("input");
if(input.value == ""){
input.style.background = "";
alert("no value");
}else{
input.style.background = "blue";
}
}
</script>
function handleCurrentInput(event) {
const value = event.target.value;
if (!value) {
alert("no value");
} else {
alert("value entered -->", value);
}
}
<input type="text" id="input" onInput="handleCurrentInput(event)">

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

Javascript form validation checkbox and radio not working

I have a form that I need to validate with javascript to make sure at least one checkbox and one radio is checked. I know it would probably be easier to use jQuery but I'm trying to accomplish this with pure javascript. Here is the code:
<form name="bulbform" action="compute.php" onsubmit=" return validateForm()" method="post">
<p>Enter your name: <input type="text" name="name" size="20"></p>
<p><strong>Light Bulbs</strong></p>
<label><input type="checkbox" name="bulbs[]" value="2.39">Four 25-watt light bulbs for $2.39</label><br>
<label><input type="checkbox" name="bulbs[]" value="4.29">Eight 25-watt light bulbs for $4.29</label><br>
<label><input type="checkbox" name="bulbs[]" value="3.95">Four 25-watt long-life light bulbs $3.95</label><br>
<label><input type="checkbox" name="bulbs[]" value="7.49">Eight 25-watt long-life light bulbs $7.45</label><br>
<p><strong>Payment Method</strong></p>
<label><input type="radio" name="cc" value="Visa">Visa</label><br>
<label><input type="radio" name="cc" value="Master Card">Master Card</label><br>
<label><input type="radio" name="cc" value="Discover">Discover</label><br>
<p><input type="submit" value="Order" /> <input type="reset" value="Clear form"/></p></form>
Here is my javascript
var radios = document.getElementsByTagName('input');
var value;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
alert(value);
return true;
}
else{
alert("You must select a payment method.")
return false;
}
With the else removed I'm able to show the credit card selected but when I add the else it always says you must select a payment method and is never true... Thanks ahead of time for any advice you can give.
See this plunker: https://plnkr.co/edit/5NiIA1w9axvmOJEjXVlP
function validateForm() {
var radios = document.getElementsByTagName('input');
var value;
var paymentMethodSelected = false;
for (var i = 0; i < radios.length; i++) {
if (radios[i].type === 'radio' && radios[i].checked) {
// get value, set checked flag or do whatever you need to
value = radios[i].value;
alert(value);
paymentMethodSelected = true;
}
}
if (!paymentMethodSelected) {
alert("You must select a payment method.");
return false;
}
return true;
}
You don't have an ending form tag (not critical, but good practice)
You were returning from the validation function before you had checked all radio buttons
The check for an invalid form state should be handled outside the for loop
The variable radios contains checkboxes, textbox, and radio buttons.
A radio button and a textbox are not checkbox.
So the condition radios[i].type=='radio' && radios.type='checked' will evaluate to false and the else part will be evaluated.
The code below uses the variables checkedCB and checkedRadio to store if any checkbox or radio button is checked.
Try something like this:
function validateForm() {
var inputs = document.getElementsByTagName('input');
var valued;
var checkedCB=false,checkedRadio=false;
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checkedCB=true;
}
else if(inputs[i].type == 'radio' && inputs[i].checked) {
checkedRadio=true;
}
if(checkedRadio && checkedCB) return true;
}
alert("You must select atleast one light bulb and a payment method.");
return false;
}
And you can put the attribute checked in any one radio button.
i.e.
<label><input type="radio" name="cc" value="Visa" checked>Visa</label><br>
If you would like to make sure at least one checkbox and one radio is checked before form submit then, you could introduce counters variable in your scripts that will count how many check box and radio button checked inside of the loop.
And before return just check at least one checkbox and one radio selected as follow:
if(checkbox_checked_count>=1&&radio_checked_count==1){
alert("Yahoo! You have successfully validated your form.")
return true;
}else{
alert("You must select a payment method.")
return false;
}
Your validateForm() function full script could like following one:
function validateForm(){
var inputs = document.getElementsByTagName('input');
var radio_checked_count=0;
var checkbox_checked_count=0;
var i;
for (i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox"&&inputs[i].checked) {
checkbox_checked_count++;
}
if (inputs[i].type == "radio"&&inputs[i].checked) {
radio_checked_count++;
}
}
if(checkbox_checked_count>=1&&radio_checked_count==1){
alert("Yahoo! You have successfully validated your form.")
return true;
}else{
alert("You must select a payment method.")
return false;
}
}
Here is what your javascript is doing.
It checks the first radio button, finds that it is NOT checked so it executes the else statement and alerts that you must choose a card or whatever. Then it hits the return false statement and exits the loop (doesn't matter what it's returning, a return statement will exit the loop). That's all.
If you had checked the first checkbox using an attribute checked, it will find that the first radio button IS checked and then alert it and return out of the loop without checking the rest. Your for loop is not closed in the question if you want to edit it.
You should prompt user for payment selection only after for-loop, try this code snippet:
function validateForm() {
var payments = document.getElementsByName("cc");
var count = payments.length;
var selected = false;
while (count--)
if (selected = payments[count].checked)
break;
if (!selected) {
alert('Choose payment method');
return false;
}
return true;
}
<form name="bulbform" action="compute.php" onsubmit=" return validateForm()" method="post">
<p><strong>Payment Method</strong>
</p>
<label>
<input type="radio" name="cc" value="Visa">Visa</label>
<br>
<label>
<input type="radio" name="cc" value="Master Card">Master Card</label>
<br>
<label>
<input type="radio" name="cc" value="Discover">Discover</label>
<br>
<p>
<input type="submit" value="Order" />
<input type="reset" value="Clear form" />
</p>
Thanks to Mahesh Bansod for the help I used their example and tweaked it to my needs. Below is my working validation code for a textbox, checkbox and radio.
function validateForm(){
//check to make sure the name is not blank
var cusName = document.forms["bulbform"]["name"].value;
if (cusName == null || cusName == ""){
alert("Your name must be filled out.");
return false;
}
//check to see that atleast one radio and checkbox are checked
var inputs = document.getElementsByTagName('input');
var checkCheckBox=false, checkRadio=false; //set both rado and checkbox to false
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox' && inputs[i].checked) {
checkCheckBox=true; //set checkbox true if one is checked
}
else if(inputs[i].type == 'radio' && inputs[i].checked) {
checkRadio=true; //set radio true if one is checked
}
if(checkRadio && checkCheckBox) return true; //if both are true return true
}
//if checkbox is false alert user and return false
if(!checkCheckBox){
alert("You must select atleast one item.");
return false; //
}
//if radio is false alert user and return false
if(!checkRadio){
alert("You must select a payment method.");
return false;
}
}

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

Categories