Issues With Javascript Checkboxes - javascript

Hi I am having some issues trying to get check box values. For a school project I have a pizza order form and I am suppose to print a summary of he order. I am having issues printing the toppings.
<label><input type = "checkbox" name = "topping" id = "sausage" value = "Sausage"/> Sausage</label>
<label><input type = "checkbox" name = "topping" id = "pepperoni" value = "Pepperoni"/> Pepperoni</label>
<label><input type = "checkbox" name = "topping" id = "beef" value = "Beef"/> Beef</label>
<label><input type = "checkbox" name = "topping" id = "bacon" value = "Bacon"/> Bacon</label><br />
<label><input type = "checkbox" name = "topping" id = "chicken" value = "Chicken"/> Chicken</label>
<label><input type = "checkbox" name = "topping" id = "ham" value = "Ham"/> Ham</label>
<label><input type = "checkbox" name = "topping" id = "olives" value = "Olives"/> Olives</label>
<label><input type = "checkbox" name = "topping" id = "peppers" value = "Peppers"/> Peppers</label><br />
<label><input type = "checkbox" name = "topping" id = "tomatoes" value = "Tomatoes"/> Tomatoes</label>
<label><input type = "checkbox" name = "topping" id = "mushrooms" value = "Mushrooms"/> Mushrooms</label>
<label><input type = "checkbox" name = "topping" id = "pineapple" value = "Pineapple"/> Pineapple</label>
Thats the html part and I have my javascript function where I think the problem is.
function toppings(inputCollection) {
var toppings = "";
for (var i = 0; i < inputCollection.length; i++) {
if (inputCollection[i].checked) {
toppings = toppings + inputCollection[i].value + " ";
}
}
return toppings;
}
I am fairly new to javascript so please don't flame me if I made a stupid mistake. Thank you very much

How are you calling your function?
This should do it - toppings(document.getElementsByName("topping"))

Have a look at this example, which also shows how labels are properly used:
http://jsbin.com/upeqam

Related

How do I make 2 checkboxes, that if for example one is checked and then you try to check the other it cancel the first one?

I have 2 checkboxes in my code:
<input type = "checkbox" id = "soundyes" name = "soundyes" value = "soundyes">
and
<input type = "checkbox" id = "soundno" name = "soundno" value = "soundno">
Is it possible that if for example, a person checked the "soundyes" one (soundyes.checked == true) and then tries to check the "soundno" one, it makes the first checkbox ("soundyes") unchecked (soundyes.checked == false) in JavaScript?
Thanks in advance!
You can use the handle the change event on both checkboxes.
function uncheck(input){
input.checked = false;
}
let no = document.querySelector("#soundno")
let yes = document.querySelector("#soundyes")
yes.addEventListener("click", e=>{
uncheck(no)
});
no.addEventListener("click", e=>{
uncheck(yes);
})
Checkbox 1: <input type = "checkbox" id = "soundyes" name = "soundyes" value = "soundyes">
Checkbox 2: <input type = "checkbox" id = "soundno" name = "soundno" value = "soundno">
const y = document.querySelector('#yes');
const n = document.querySelector('#no');
const both = [y, n];
both.map(c => c.addEventListener('change', e => {
both.filter(c => e.target !== c)[0].checked = !e.target.checked;
}));
<label>
<input type="checkbox" id="yes" checked /> yes
</label>
<label>
<input type="checkbox" id="no"/> no
</label>
This should work

How to go about using form validation with using just javascript and DOM elements?

Was given a puzzle to figure out which is to use just form validation using only js and the peculiar thing here is that there is no form name, and the types dont use IDs but they do have names, but the main objective besides that is to make sure at least there is some data entered on each input type (ie. fullname can even be 1 letter, as long as its one character). Another thing to note is I cannot change the html code in anyway. Since I cannot use form name in my validation, the examples I have seen online are helpful but not enough to the point where I can proceed. Any help will be appreciated.
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
Its a bit messy but its working . I dont change any HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
</style>
</head>
<body>
<form action = "form.html" method = "get"><br/>
Name:<input type = "text" name = "fullname" value="Enter Full Name"/><br/>
Gender:<br/>
Male<input type = "radio" name = "gender" value="male"/>Female<input type = "radio" name = "gender"
value="female"/><br/>
Hobbies<br/>
Baseball <input type = "checkbox" name = "hobbies[]" value = "baseball" />
Football <input type = "checkbox" name = "hobbies[]" value = "football" />
Hockey <input type = "checkbox" name = "hobbies[]" value = "hockey" /><br/>
Favorite Show <select name = "show">
<option value = "">Choose Below</option>
<option value = "ATHF">Aqua Teen Hunger Force</option>
<option value = "Family Guy">Family Guy</option>
<option value = "Simpsons">Simpsons</option>
</select><br/>
Comments<br/>
<textarea cols = "50" rows = "6" name = "comments">Enter Comments</textarea><br/>
<input type = "submit" name = "submit" value = "enter me" />
</form>
</body>
<script type="text/javascript">
function validate(){
name = document.getElementsByName("fullname")[0].value.length
gender1 = document.getElementsByName("gender")[0].checked
gender2 = document.getElementsByName("gender")[1].checked
hobbies1 = document.getElementsByName("hobbies[]")[0].checked
hobbies2 = document.getElementsByName("hobbies[]")[1].checked
hobbies3 = document.getElementsByName("hobbies[]")[2].checked
show = document.getElementsByName("show")[0].value
comment = document.getElementsByName("comments")[0].value.length
if(name==0 || (!gender1 && !gender2) || (!hobbies1 && !hobbies2 && !hobbies3) || comment==0 || show==""){
alert("please fill all")
}
}
button = document.getElementsByName("submit")
eButton = button[0].addEventListener("click",validate)
</script>
</html>

HTML form failed to validate using the jQuery Validation Plugin

I'm aware that this is likely poorly formatted and/or coded. I'm looking for an answer as to why it doesn't give a message that the first name field is required. The submit button at the moment isn't working at all, no values are being printed to the screen. When just doing a form scrape it was working. Could anyone tell me why the validation for the one form isn't working? I made sure my jQuery validation plugin is hooked in. Bits of my html and JS code are below. This is for a school project.
<form id = "form">
<div>
<label for = "firstName">First Name</label>
<input type = "text" id = "firstName" placeholder = "Type First Name Here"
name = "firstName" required autofocus >
<br><br>
<label for = "lastName">Last Name</label>
<input type = "text" id = "lastName" name = "lastName">
</div>
<br>
<div>
<label for = "phone">Phone Number</label>
<input type = "tel" id = "phone">
</div>
<br>
<div> <p>
<label>Email</label>
<input type = "email" id = "email">
Password
<input type = "password" id = "pass">
</p>
</div>
<br>
<div> Which level of skill do you believe fits you (or your child) best?
</div>
Beginner<input type = "radio" value = "Beginner" name = "level">
Intermediate<input type = "radio" value = "Intermediate" name = "level">
Advanced<input type = "radio" value = "Advanced" name = "level">
<div id = "level"></div>
<br>
<br>
<label for = "age-spinner">Student Age</label>
<input id = "age-spinner" value = "5">
<br>
<br>
<div>Which days are you most available for a weekly piano lesson?</div>
<input type = "checkbox" value = "Monday" id = "monday" name = "days">Monday
<input type = "checkbox" value = "Tuesday" id = "tuesday" name =
"days">Tuesday
<input type = "checkbox" value = "Wednesday" id = "wednesday" name =
"days">Wednesday
<input type = "checkbox" value = "Thursday" id = "thursday" name =
"days">Thursday
<input type = "checkbox" value = "Friday" id = "friday" name = "days">Friday
<input type = "checkbox" value = "Saturday" id = "saturday" name =
"days">Saturday
<br>
<br>
<div>Best starting date? </div>
<input type = "text" id = "startDate">
</form>
<br><br>
<input type = "submit" id = "submit">
<button type= "button" id = "reset">Reset</button>
^^HTML Code. JS Code below. These are held in separate files.
$( "input[type='submit']" ).button();
$.validator.setDefaults({
submitHandler: function(){
var firstName = $("#firstName").val();
var lastName =$("#lastName").val();
var phone = $("#phone").val();
var email = $("#email").val();
var pass = $("#pass").val();
var age = $("#age-spinner").val();
var level = $("input[name='level']:checked").val();
var startDate = $("#startDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();
var days = " ";
//function to fill in data inputted from days
$("input[name='days']:checked").each(function(){
days += $(this).val() + ", "
});
$("#output").append("<br><br>Name: " + firstName + " " + lastName)
.append("<br>Phone #: " + phone)
.append("<br>Email: " + email)
.append("<br>Password: " + pass)
.append("<br>Student Age: " + age)
.append("<br>Student Level: " + level)
.append("<br>Proposed Start Date: " + startDate)
.append("<br>Available Days: " + days);
alert("Passed validation and submitted.");
}//end submitHandler
});
$("#form").validate();

Javascript html not displaying input

Whenever I run this code on my webpage, I am unable to get the buttons to perform an event upon being clicked. Nothing happens. I am wanting to display the user input for full name, date of birth and gender into the textbox whenever the user clicks display. If the user clicks next, the current data should be saved to the correct array and when the user clicks clear the current innput in the text boxes and the data in the array should be deleted. What do I need to adjust to make this happen?
<html>
<head>
<script language = "javascript">
var full_name;
var dob;
var gender;
var nameList = new Array();
var dateList = new Array();
var genderList = new Array();
function displayMembers() {
var str = " ";
var listLength = nameList.length;
for(var i = 0; i < listLength; i++) {
document.memberForm.textArea.nameList[i];
document.memberForm.textArea.dateList[i];
document.memberForm.textArea.genderList[i];
}
}
function saveMember() {
nametemp = document.getElementByName("full_name");
nameList.push(nametemp[0].value);
datetemp = document.getElementByName("dob");
dateList.push(datetemp[0].value;
gendertemp = document.getElementByName("gender");
genderList.push(gendertemp[0].value);
}
function clearList() {
nameList= [];
dateList = [];
genderList = [];
}
</script>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
<title>INTERNET TECHNOLOGIES CLUB MEMBER LIST </title>
</head>
<body>
<form name = "memberForm">
<h1>
INTERNET TECHNOLOGIES CLUB MEMBER LIST
</h1>
Full Name: <input type = "text" name = "full_name" value = ""/>
Date of Birth: <input type = "text" name ="dob" value = ""/>
<br>
Gender: <input type = "text" name = "gender" value = ""/>
<br>
<textarea name = "textBox" rows = "10" cols = "70">
</textarea>
<br>
<input type = "button" value = "NEXT" onclick = document.memberForm.
saveMember()"></button>
<input type = "button" value = "DISPLAY" onclick =document.memeberForm.textBox.write.Full Name Date of Birth Gender "displayMembers()">
</button>
</form>
</body>
</html>
There are probably more problems I'm not seeing but here you have an unterminated string.
Change it to
<input type="button" value="NEXT" onclick="document.memberForm.saveMember()"></button>

javascript click function not working on form generated in php

I have a form created using echo command in php. It is being displayed correctly. I have a javascript which detects click on radio button of form and displays the hyperlink/anchor corresponding to each button group, which is not working.
But if I create the form in html only without any php, it works perfectly. please HELP.
Form creation
echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo(($i+1)." ".$row[1]."<br>");
echo("
<input type = 'radio' value = $row[2] name = '$i'>$row[2]&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = $row[3] name = '$i'>$row[3]<br>
<input type = 'radio' value = $row[4] name = '$i'>$row[4]&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = $row[5] name = '$i'>$row[5]&nbsp&nbsp
<a id='$i' href='javascript:clear($i)'>Reset</a><br>");
$i++;
$z[]=$row[6];
}
SCRIPT
$('input:radio').click(function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
You can try changing $('input:radio') to $('input[type="radio"]').
Try this
$('input[type="radio"]').on('click', function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
$('body').on('click','input:radio',(function() {
var n = $(this).attr('name');
var k ='#' + n;
alert($(this).attr('name'));
$(k).show(400);
});
When clicking on dynamically created elements you need to use event delegation.
Hmm... your problem is that $row array should be with curly brackets because you're in double quotes
echo("<form name ='input' action = 'result.php' method = 'POST'>");
while($row = mysqli_fetch_array($result,MYSQLI_NUM))
{
echo(($i+1)." ".$row[1]."<br>");
echo("
<input type = 'radio' value = '{$row[2]}' name = '$i'>{$row[2]}&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = '{$row[3]}' name = '$i'>{$row[3]}<br>
<input type = 'radio' value = '{$row[4]}' name = '$i'>{$row[4]}&nbsp&nbsp&nbsp&nbsp
<input type = 'radio' value = '{$row[5]}' name = '$i'>{$row[5]}&nbsp&nbsp
<a id='$i' href='javascript:clear($i)'>Reset</a><br>");
$i++;
$z[]=$row[6];
}

Categories

Resources