ModifyDOM to clear text launched by a radio button - javascript

I have made a form that I can clear with a reset button. On this form, I have four radio buttons (that code is towards the top). When a button is selected, info comes up using "displayText". I want to attach an onclick handler to launch a function that deletes/closes that div when reset button is hit.
Someone suggested this but I can't get it to work.
document.getElementById("info").remove();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Infotech 550 Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<style>
#form {
margin-top: 30px;
margin-left: 30px;
}
.infoText {
margin-left: 20px;
color: blue
}
p.padding2 {
padding-top: 1%;
margin-left: 30px;
color: indigo
}
</style>
<script>
function textToDisplay (radioValue){
var displayText = "";
if (radioValue =="1"){
displayText = "I have no use for audio products in my library"
} else if (radioValue == "2"){
displayText = "Not very interested in using Audacity for anything in my library"
} else if (radioValue == "3"){
displayText = "Interesting program but no practical application at this time"
} else if (radioValue == "4"){
displayText = "I am going to learn more, I think there are ways Audacity could be useful in my library"
} else if (radioValue == "5"){
displayText = "I am going to use Audacity in my library for a local audio history project"
}
return (displayText);
}
// modify DOM function
function modifyDOM (radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
var insertionNode = document.getElementById("radioButtons");
var infoNode = document.getElementById("info");
if (infoNode === null) {
console.log("infoNode does not exist yet.");
var node = document.createElement("DIV");
// console.log(node);
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
insertionNode.appendChild(node);
} else {
console.log("infoNode DOES exist.");
infoNode.innerHTML = displayText;
}
function clearResult(){
document.getElementById("info").remove();
}
}
// test how many checkboxes selected //
function checkboxesSelected (checkboxes, errorString) {
console.log("checkboxesSelected function");
// keep a count of how many checkboxes have been selected ... initially zero
// have to use var cbSelected = 0;
// 2) Good practice to have var when declaring a variable ...not doing it in our JavaScript examples to not add more complexity.
var cbSelected = 0;
// for loop: first need an index i to iterate through array of checkboxes;
// start at beginning of array of checkboxes
// i=0 means we start at beginning of array
// test if all elements of array have been tested... know if i < checkboxes.length that we have still elements to examine
// i-- means that we subtract -1 from i
for (i=0; i<checkboxes.length; i++) {
// test if current checkbox is checked ... if yes, add 1 to counter
if (checkboxes[i].checked) {
// increment counter
cbSelected += 1;
}
}
// test how many checkboxes have been selected ...
// if checkboxesSelected equal to 0, then we have not and return errorString
if (cbSelected <= 1) {
return (errorString);
} else {
return "";
}
}
// validate function that calls other functions and acculumates errorString and test if this is empty or not //
function validate (form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.bed_extras, "At least TWO Audacity uses need to be selected.\n")
if (fail == "") return true
else { alert(fail); return false }
}
</script>
</head>
<body>
<div class="container-fluid">
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">AVM Game</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<!-- Links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle active" href="#" id="navbardrop" data-toggle="dropdown">
Infotech 550
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="Ex4_review.html">Open Source Tool Review</a>
<a class="dropdown-item" href="Ex4_form.html">Feedback Form</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="navbardrop" data-toggle="dropdown">
Interests
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Interest 1</a>
<a class="dropdown-item" href="#">Interest 2</a>
<a class="dropdown-item" href="#">Interest 3</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</nav>
<div>
<h1>Open-Source Project Data Collection</h1>
<h2>(Thank you for participating in our study)</h2>
</div>
<form id="form" method="post" action="mailto:stephentruddy#yahoo.com" onsubmit="return validate(this)">
<fieldset id="personal" class="form-group">
<legend>Personal Data</legend>
<div class="form-inline">
<label for="firstname" class="mr-sm-2">First Name:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="firstname" name="firstname" placeholder="Enter First Name" required>
</div>
<div class="form-inline">
<label for="lastname" class="mr-sm-2">Last Name:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="lastname" name="lastname" placeholder="Enter Last Name" required>
</div>
<div class="form-inline">
<label for="email" class="mr-sm-2">Email:</label>
<input type="email" class="form-control mb-2 mr-sm-2" id="email" name="email" placeholder="Enter A Valid Email" required>
</div>
<div class="form-inline">
<label for="state" class="mr-sm-2">State:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="state" name="state" placeholder="Enter Two Letter State " pattern="[A-Z]{2}" title="State needs to be TWO CAPITAL letters"]required>
</div>
<div class="form-inline">
<label for="firstname" class="mr-sm-2">Zipcode:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="zipcode" name="zipcode" placeholder="Enter 5 Digit Zipcode " pattern="[0-9]{5}" title="Zipcode needs to be 5 numbers"] required >
</div>
</fieldset>
<fieldset>
<legend>Questions About Audacity</legend>
<label>Rate your interest in using Audacicity in your library (1 being lowest):</label>
<div id="radioButtons" class="form-group">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="1" required onclick="modifyDOM(this)">
1</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="2" required onclick="modifyDOM(this)">
2</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="3" required onclick="modifyDOM(this)">
3</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="4" required onclick="modifyDOM(this)">
4</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="5" required onclick="modifyDOM(this)">
5</label>
</div>
</div>
<label>How would use Audacity (check at least TWO options)</label>
<div id="checkboxes" class="form-group">
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="oralhistory">
Oral History
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="multimedia">
Multimedia
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="dailynews">
Daily News
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="podcast">
Podcasts
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="natual world">
The Natural World
</label>
</div>
</div>
</fieldset>
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset" onclick="clearResult(this)">
</form>
<footer><p class="padding2">c. New World InfoTechnologies Corporation</p></footer>
</body>
</html>

You had your clearResult function inside the scope of your modifyDOM function. Move it to the global scope to call it directly from your html onclick handler.
function textToDisplay(radioValue) {
var displayText = "";
if (radioValue == "1") {
displayText = "I have no use for audio products in my library"
} else if (radioValue == "2") {
displayText = "Not very interested in using Audacity for anything in my library"
} else if (radioValue == "3") {
displayText = "Interesting program but no practical application at this time"
} else if (radioValue == "4") {
displayText = "I am going to learn more, I think there are ways Audacity could be useful in my library"
} else if (radioValue == "5") {
displayText = "I am going to use Audacity in my library for a local audio history project"
}
return (displayText);
}
// modify DOM function
function modifyDOM(radioInput) {
console.log(radioInput.name + " + " + radioInput.value);
var displayText = textToDisplay(radioInput.value);
var insertionNode = document.getElementById("radioButtons");
var infoNode = document.getElementById("info");
if (infoNode === null) {
console.log("infoNode does not exist yet.");
var node = document.createElement("div");
// console.log(node);
node.setAttribute("id", "info");
node.className = "form-text infoText";
var textnode = document.createTextNode(displayText);
node.appendChild(textnode);
insertionNode.appendChild(node);
} else {
console.log("infoNode DOES exist.");
infoNode.innerHTML = displayText;
}
}
function clearResult() {
var info = document.getElementById("info");
var infoParent = document.getElementById("radioButtons")
infoParent.removeChild(info)
}
// test how many checkboxes selected //
function checkboxesSelected(checkboxes, errorString) {
console.log("checkboxesSelected function");
// keep a count of how many checkboxes have been selected ... initially zero
// have to use var cbSelected = 0;
// 2) Good practice to have var when declaring a variable ...not doing it in our JavaScript examples to not add more complexity.
var cbSelected = 0;
// for loop: first need an index i to iterate through array of checkboxes;
// start at beginning of array of checkboxes
// i=0 means we start at beginning of array
// test if all elements of array have been tested... know if i < checkboxes.length that we have still elements to examine
// i-- means that we subtract -1 from i
for (i = 0; i < checkboxes.length; i++) {
// test if current checkbox is checked ... if yes, add 1 to counter
if (checkboxes[i].checked) {
// increment counter
cbSelected += 1;
}
}
// test how many checkboxes have been selected ...
// if checkboxesSelected equal to 0, then we have not and return errorString
if (cbSelected <= 1) {
return (errorString);
} else {
return "";
}
}
// validate function that calls other functions and acculumates errorString and test if this is empty or not //
function validate(form) {
console.log("validate form");
var fail = "";
fail += checkboxesSelected(form.bed_extras, "At least TWO Audacity uses need to be selected.\n")
if (fail == "") return true
else {
alert(fail);
return false
}
}
#form {
margin-top: 30px;
margin-left: 30px;
}
.infoText {
margin-left: 20px;
color: blue
}
p.padding2 {
padding-top: 1%;
margin-left: 30px;
color: indigo
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Infotech 550 Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<nav class="navbar navbar-expand-md bg-dark navbar-dark">
<!-- Brand -->
<a class="navbar-brand" href="#">AVM Game</a>
<!-- Toggler/collapsibe Button -->
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">
<span class="navbar-toggler-icon"></span>
</button>
<!-- Navbar links -->
<div class="collapse navbar-collapse" id="collapsibleNavbar">
<!-- Links -->
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="#">Home</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle active" href="#" id="navbardrop" data-toggle="dropdown">
Infotech 550
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="Ex4_review.html">Open Source Tool Review</a>
<a class="dropdown-item" href="Ex4_form.html">Feedback Form</a>
</div>
</li>
<li class="nav-item dropdown">
<a class="nav-link" href="#" id="navbardrop" data-toggle="dropdown">
Interests
</a>
<div class="dropdown-menu">
<a class="dropdown-item" href="#">Interest 1</a>
<a class="dropdown-item" href="#">Interest 2</a>
<a class="dropdown-item" href="#">Interest 3</a>
</div>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
</div>
</nav>
<div>
<h1>Open-Source Project Data Collection</h1>
<h2>(Thank you for participating in our study)</h2>
</div>
<form id="form" method="post" action="mailto:stephentruddy#yahoo.com" onsubmit="return validate(this)">
<fieldset id="personal" class="form-group">
<legend>Personal Data</legend>
<div class="form-inline">
<label for="firstname" class="mr-sm-2">First Name:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="firstname" name="firstname" placeholder="Enter First Name" required>
</div>
<div class="form-inline">
<label for="lastname" class="mr-sm-2">Last Name:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="lastname" name="lastname" placeholder="Enter Last Name" required>
</div>
<div class="form-inline">
<label for="email" class="mr-sm-2">Email:</label>
<input type="email" class="form-control mb-2 mr-sm-2" id="email" name="email" placeholder="Enter A Valid Email" required>
</div>
<div class="form-inline">
<label for="state" class="mr-sm-2">State:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="state" name="state" placeholder="Enter Two Letter State " pattern="[A-Z]{2}" title="State needs to be TWO CAPITAL letters" ]required>
</div>
<div class="form-inline">
<label for="firstname" class="mr-sm-2">Zipcode:</label>
<input type="text" class="form-control mb-2 mr-sm-2" id="zipcode" name="zipcode" placeholder="Enter 5 Digit Zipcode " pattern="[0-9]{5}" title="Zipcode needs to be 5 numbers" ] required>
</div>
</fieldset>
<fieldset>
<legend>Questions About Audacity</legend>
<label>Rate your interest in using Audacicity in your library (1 being lowest):</label>
<div id="radioButtons" class="form-group">
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="1" required onclick="modifyDOM(this)">
1</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="2" required onclick="modifyDOM(this)">
2</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="3" required onclick="modifyDOM(this)">
3</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="4" required onclick="modifyDOM(this)">
4</label>
</div>
<div class="form-check-inline">
<label class="form-check-label">
<input type="radio" class="form-check-input" name="bed_size" value="5" required onclick="modifyDOM(this)">
5</label>
</div>
</div>
<label>How would use Audacity (check at least TWO options)</label>
<div id="checkboxes" class="form-group">
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="oralhistory">
Oral History
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="multimedia">
Multimedia
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="dailynews">
Daily News
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="podcast">
Podcasts
</label>
</div>
<div class="form-check form-check-inline">
<label class="form-check-label">
<input type="checkbox" class="form-check-input" name="bed_extras" value="natual world">
The Natural World
</label>
</div>
</div>
</fieldset>
<input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset" onclick="clearResult(this)">
</form>
<footer>
<p class="padding2">c. New World InfoTechnologies Corporation</p>
</footer>
</body>
</html>

Related

How to get data from a form which is written in inner HTML?

This is my code, here I want to access data from the textfields, how can I access them
This is my javascript function to add new form eevrytime add button is clicked
function elementAppender() {
if (count <= 5) {
let element = document.createElement('div');
element.id = `${count}`
Here, the code from which I have to get data is written in inner html
element.innerHTML = `<div class="col-md-6 mx-auto my-5" id="myDiv">
<div class="kumite-form">
<button type="button" class="close col-md-2" data-dismiss="form" style="color: coral; float: right;" onclick="remdiv(), count-=1">×</button>
<form action="#" class="mx-auto">
<h3 style="text-align: left;margin-left:10%">Group ${count}</h3>
<ul>
<li>
<div class="text-center">
Category:
<input class="" type="radio" name="category" value="female" style="font-size: 0.5px;">
<label>Male</label>
<input class="" type="radio" name="category" value="male" style="font-size: 0.5px;">
<label>Female</label>
</div>
</li>
<h4 style="text-align: left;margin-left:10%">Player 1</h4>
<li><input type="text" placeholder="Player 1 Name"></li>
<input type="text" placeholder="Date of Birth" onfocus="(this.type='date')"
onblur="(this.type='text')">
<li><input type="Number" placeholder="Weight (in kg)"></li>
The "value" property in JS comes in handy.
var myInput = document.querySelector("#idOfField").value

Will open a div close the previous

I am creating a menu that shows and hides divs.
This part of the code is working.
function Mudarestado(el) {
var display = document.getElementById(el).style.display;
if(display == "none")
document.getElementById(el).style.display = 'block';
else
document.getElementById(el).style.display = 'none';
}
<div class="wrapper">
<div class="sidebar">
<h6 style="color: White">Registos</h6>
<ul class="nav1">
<li><a type="button" class="button" onclick="Mudarestado('minhaDiv')">Requisição Manutenção</a></li>
<li><a type="button" class="button" onclick="Mudarestado('minhaDiv1')">Pedidos de Informação</a></li>
</ul>
</div>
<div class="content isOpen">
<div id="minhaDiv" style="display:none;" class="divCaixa center1">
<form class="form15" method="POST" style="max-width: 100%; width: auto; display: table;">
<div class="modal-header">
<button style="float:right" class="btn btn-primary view_data12" data-toggle="modal" data-target="#dataModal11">Pedidos Manutenção</button>
</div>
<div class="modal-header">
<h4 class="modal-title">REQUISIÇÃO DE MANUTENÇÃO</h4>
</div>
<ul class="flex-outer">
<li>
<label for="Pedido">Requerente</label>
<select class="form-control" id="Pedido" name="Pedido" required="">
<?php
$sql = "SELECT * FROM raddb.Valencias WHERE Id IN ('3') ORDER BY Destino ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['Id'].'">'.$ln['Destino'].'</option>';
}
?>
</select>
</li>
<li>
<label for="Assunto">Assunto</label>
<input type="text" class="form-control" id="Assunto" name="Assunto">
</li>
<li>
<label for="Descricao">Descrição</label>
<textarea rows="6" id="Descricao" placeholder="Digite o motivo da requisição"></textarea>
</li>
<li style="float: right">
<button type="button" class="btn btn-success" onclick="inserir_registo14()">Gravar</button>
</li>
</ul>
</form>
</div>
<div id="minhaDiv1" style="display:none;" class="divCaixa center1">
<form class="form6" method="POST" style="max-width: 100%; width: auto; display: table;">
<div class="modal-header">
<h4 class="modal-title">Pedidos de Informação Infância</h4>
</div>
<ul class="flex-outer">
<li>
<label for="DataRegisto2">Data do Contacto</label>
<input type="date" class="form-control" id="DataRegisto1" name="DataRegisto" value="<?php echo date("Y-m-d");?>">
</li>
<li>
<label for="Contacto">Responsável pelo Contacto</label>
<input type="text" class="form-control" id="Contacto" name="Contacto">
</li>
<li>
<label for="Telefone">Telefone (rede móvel)</label>
<input type="number" class="form-control" id="Telefone" name="Telefone">
</li>
<li>
<label for="NomeCrianca">Nome da Criança</label>
<input type="text" class="form-control" id="NomeCrianca" name="NomeCrianca">
</li>
<li>
<label for="DataNasc">Data Nascimento</label>
<input type="date" class="form-control" id="DataNasc" name="DataNasc" value="<?php echo date("Y-m-d");?>">
</li>
<li>
<label for="Visita">Visita</label>
<ul class="flex-outer">
<div class="form-check">
<label class="toggle">
<input type="radio" name="Visita" id="Visita1" value="Sim"> <span class="label-text"> Sim</span>
</label>
</div>
<div class="form-check">
<label class="toggle">
<input type="radio" name="Visita" id="Visita2" value="Não"> <span class="label-text">Não</span>
</label>
</div>
</ul>
</li>
<li>
<label for="DataVisita">Data da Visita</label>
<input type="date" class="form-control" id="DataVisita" name="DataVisita">
</li>
<li1>
<label for="Observacao1">Observações</label>
<textarea rows="6" id="Observacao1" name="Observacao1" placeholder="Digite a sua observação"></textarea>
</li1>
<li style="float: right">
<button type="button" class="btn btn-danger btn6" data-dismiss="modal">Cancelar</button>
<button type="button" class="btn btn-success" onclick="inserir_registo6()">Gravar</button>
</li>
</ul>
</form>
</div>
</div>
</div>
The problem is that when I have one div open and open another, it's not hiding the previous one and opens below the one that's already open.
I want to open the second div to hide the one that is open.
The problem is in js, but I am not advising to put that part I want to work
This is a possible solution:
function Mudarestado(el) {
var display = document.getElementById(el).style.display;
if(display == "none"){
document.getElementById(el).style.display = 'block';
document.getElementById(el).classList.add("active");
document.getElementByClassName("active").style.display = 'none';
document.getElementByClassName("active").classList.remove("active");
}else{
document.getElementById(el).style.display = 'none';
document.getElementByClassName(el).classList.remove("active");
}
}

knockout js, add additional elements to an array

I have an app where I want to add extra elements to an item in an array, I have created a fiddle of what I'm trying to achieve.
So the user starts the app, they click next fill in some details of an item and a description, they then should click next and fill in a price for the item(this is where I'm stuck). This example works up to a point, as in whenever I try and implement the price part I seem to be getting it wrong. You'll see once I click next the item is added to the array, however how do add more elements to the current item in the array. In case I've not made sense the logic should be:
Start
Page one (enter name and description)
Page two (enter price)
I understand I could do this all on one page but I don't want to I want knockout to be able to add a price after the name and description page. I would also like to be able to go back and amend the item. Can you anybody help in seeing what I should be doing next?
When I insert the name and description, do I have to also make an empty element in the array for the price? Then once the price is entered somehow insert this into the price element in the array? Not sure how/if this should be implemented.
This is my first knockout app so I be surprised if what I've actually done is correct, any help or pointers gratefully received :)
My code is below:
$(function() {
var main = new stuff();
ko.applyBindings(main, $('#ko')[0]);
});
function Item(data) {
this.itemname = ko.observable(data.itemname);
this.itemdescription = ko.observable(data.itemdescription);
this.itemenabled = ko.observable(data.itemenabled);
}
function stuff() {
var self = this;
self.items = ko.observableArray([]);
self.newItemName = ko.observable();
self.newItemDescription = ko.observable();
self.newItemEnabled = ko.observable();
// Operations
self.addItem = function() {
self.items.push(new Item({
itemname: this.newItemName(),
itemdescription: this.newItemDescription(),
itemenabled: this.newItemEnabled()
}));
};
};
//jquery stuff
$('#start').on('click', function(e) {
$("#page1").show(500);
$('#panel1').css('visibility', 'visible').hide().fadeIn().removeClass('hidden');
$("#start").hide(500);
})
$('#back').on('click', function(e) {
$("#panel1").hide(500);
$("#page1").hide(500);
$("#start").show(500);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="submit" class="btn btn-primary" id="start">Start</button>
<div id="ko">
<div class="panel panel-default hidden" id="panel1">
<div id="page1">
<form data-bind="submit: addItem">
<div class="panel panel-default" style="padding: 15px 0px 0px 0px;" id="panel2">
<div class="container">
<div class="form-group row">
<label for="inputItemName" class="col-lg-3 col-form-label">Enter Item Name</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputItemName" data-bind="value: newItemName" placeholder="">
</div>
</div>
<div class="form-group row">
<label for="textareaItemDescription" class="col-lg-3 col-form-label">Enter Item Description</label>
<div class="col-lg-8">
<textarea class="form-control" id="textareaItemDescription" rows="3" data-bind="value: newItemDescription"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-3 col-sm-9">
<label class="custom-control custom-checkbox checkbox-inline no_indent" style="font-weight:bold;">
<input type="checkbox" class="custom-control-input" checked="checked" data-bind="checked: newItemEnabled">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" style="padding-bottom: 2px;">Enabled</span>
</label>
</div>
</div>
</div>
</div>
<button type="button" class="btn btn-primary" id="back">Back</button>
<div class="pull-right">
<button type="submit" class="btn btn-primary" id="next1">Next</button>
</div>
</form>
</div>
</div>
<ul data-bind="foreach: items, visible: items().length > 0">
<li>
<input data-bind="value: itemname" style="color: black;" />
</li>
<li>
<input data-bind="value: itemdescription" style="color: black;" />
</li>
<li>
<input type="checkbox" data-bind="checked: itemenabled" />
</li>
</ul>
</div>
Ok, so I have added a new observable to track the page number along with basic functions to increment/decrement the number then I simply add the new item after the price has also been added.
$(function() {
var main = new stuff();
ko.applyBindings(main, $('#ko')[0]);
});
function Item(data) {
this.itemname = ko.observable(data.itemname);
this.itemdescription = ko.observable(data.itemdescription);
this.itemenabled = ko.observable(data.itemenabled);
this.price = ko.observable(data.itemprice);
}
function stuff() {
var self = this;
self.items = ko.observableArray([]);
self.newItemName = ko.observable();
self.newItemDescription = ko.observable();
self.newItemEnabled = ko.observable();
self.newItemPrice = ko.observable();
self.page = ko.observable(1);
// Operations
self.next = function() {
if (self.page() === 2) {
self.addItem();
}
self.page(self.page() + 1)
}
self.back = function() {
if (self.page() == 1) {
$("#panel1").hide(500);
$("#page1").hide(500);
$("#start").show(500);
}
self.page(self.page() - 1);
}
self.addItem = function() {
self.items.push(new Item({
itemname: this.newItemName(),
itemdescription: this.newItemDescription(),
itemenabled: this.newItemEnabled(),
itemprice: this.newItemPrice(),
}));
};
};
//jquery stuff
$('#start').on('click', function(e) {
$("#page1").show(500);
$('#panel1').css('visibility', 'visible').hide().fadeIn().removeClass('hidden');
$("#start").hide(500);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<button type="submit" class="btn btn-primary" id="start">Start</button>
<div id="ko">
<div class="panel panel-default hidden" id="panel1">
<div id="page1">
<form data-bind="submit: next">
<div class="panel panel-default" style="padding: 15px 0px 0px 0px;" id="panel2">
<div class="container" data-bind="if: page() == 1">
<div class="form-group row">
<label for="inputItemName" class="col-lg-3 col-form-label">Enter Item Name</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputItemName" data-bind="value: newItemName" placeholder="">
</div>
</div>
<div class="form-group row">
<label for="textareaItemDescription" class="col-lg-3 col-form-label">Enter Item Description</label>
<div class="col-lg-8">
<textarea class="form-control" id="textareaItemDescription" rows="3" data-bind="value: newItemDescription"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-sm-offset-3 col-sm-9">
<label class="custom-control custom-checkbox checkbox-inline no_indent" style="font-weight:bold;">
<input type="checkbox" class="custom-control-input" checked="checked" data-bind="checked: newItemEnabled">
<span class="custom-control-indicator"></span>
<span class="custom-control-description" style="padding-bottom: 2px;">Enabled</span>
</label>
</div>
</div>
</div>
</div>
<div class="container" data-bind="if: page() == 2">
<div class="form-group row">
<label for="inputPrice" class="col-lg-3 col-form-label">Enter Price</label>
<div class="col-lg-8">
<input type="text" class="form-control form-control-lg" id="inputPrice" data-bind="value: newItemPrice" placeholder="">
</div>
</div>
</div>
<button type="button" data-bind="click: back" class="btn btn-primary" id="back">Back</button>
<div class="pull-right">
<button type="submit" class="btn btn-primary" id="next1">Next</button>
</div>
</form>
</div>
</div>
<ul data-bind="foreach: items, visible: items().length > 0">
<li>
<input data-bind="value: itemname" style="color: black;" />
</li>
<li>
<input data-bind="value: itemdescription" style="color: black;" />
</li>
<li>
<label for="price">Price</label>
<input id="price" data-bind="value: price" style="color: black;" />
</li>
<li>
<input type="checkbox" data-bind="checked: itemenabled" />
</li>
</ul>
</div>

how to get radio input value that the selector gotten using find() function

I try to get value from children element that each child (item) has input fields with the same name. To do that, I used each() function. I get problem when retrieving value from radio input, I get the value from radio input that shouldn't. Here the code
<div class="accordion" id="menu-ui-sortable" role="tablist" aria-multiselectable="true">
<div class="panel menu-item">
<a class="panel-heading collapsed" role="tab" id="heading-menu-item-1" data-toggle="collapse" data-parent="#menu-ui-sortable" href="#menu-item-settings-1" aria-expanded="false" aria-controls="menu-item-settings-1">
<h4 class="panel-title">Menu Item 1</h4>
<i class="indicator glyphicon glyphicon-chevron-down pull-right"></i>
<i class="item-type pull-right">Halaman Web</i>
</a>
<input type="hidden" name="menu_item_type" value="page"/>
<input type="hidden" name="menu_item_page_id" value="12"/>
<input type="hidden" name="menu_item_content_id" value=""/>
<input type="hidden" name="menu_item_url" value="www.example.com/page-12"/>
<div id="menu-item-settings-1" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-menu-item-1">
<div class="panel-body">
<label>Label Navigasi</label>
<input type="text" class="form-control" name="menu_item_title" value="label 1"/>
<label>Atribut Judul</label>
<input type="text" class="form-control" name="menu_item_attr_title" value="attr 1"/>
<p class="menu_item_target"><label><input type="checkbox" name="menu_item_target" value="1" checked=""> Buka tautan di tab baru</label></p>
<label>CSS Classes/Icon</label>
<input type="text" class="form-control" name="menu_item_classes" value="fa fa-glass"/>
<label>Letak CSS Classes/Icon</label>
<div class="radio">
<label><input type="radio" name="menu_item_classes_position" value="left" checked=""> Sebelah kiri label</label>
<label><input type="radio" name="menu_item_classes_position" value="right"> Sebelah kanan label</label>
</div>
<label class="move-button-handle">
<span>Pindahkan: </span>
Naik Satu
Turun Satu
Urutan Pertama
Urutan Terakhir
</label>
<div class="menu-item-actions submitbox">
<p class="link-to-original">Asli: <a class="a-link" href="http://wordpress.dev/new-page-page/">new page page</a></p>
<a class="item-delete danger-highlight" href="#">Hapus</a><span> | </span>
<a class="item-cancel" href="#">Cancel</a>
</div>
</div>
</div>
</div>
<div class="panel menu-item">
<a class="panel-heading collapsed" role="tab" id="heading-menu-item-2" data-toggle="collapse" data-parent="#menu-ui-sortable" href="#menu-item-settings-2" aria-expanded="false" aria-controls="menu-item-settings-2">
<h4 class="panel-title">Menu Item 2</h4>
<i class="indicator glyphicon glyphicon-chevron-down pull-right"></i>
<i class="item-type pull-right">Homepage Content</i>
</a>
<input type="hidden" name="menu_item_type" value="homepage-content"/>
<input type="hidden" name="menu_item_page_id" value=""/>
<input type="hidden" name="menu_item_content_id" value="4"/>
<input type="hidden" name="menu_item_url" value="#content-4"/>
<div id="menu-item-settings-2" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-menu-item-2">
<div class="panel-body">
<label>Label Navigasi</label>
<input type="text" class="form-control" name="menu_item_title" value="label 2"/>
<label>Atribut Judul</label>
<input type="text" class="form-control" name="menu_item_attr_title" value="attr 2"/>
<p class="menu_item_target"><label><input type="checkbox" name="menu_item_target" value="1"> Buka tautan di tab baru</label></p>
<label>CSS Classes/Icon</label>
<input type="text" class="form-control" name="menu_item_classes" value="fa fa-search"/>
<label>Letak CSS Classes/Icon</label>
<div class="radio">
<label><input type="radio" name="menu_item_classes_position" value="left"> Sebelah kiri label</label>
<label><input type="radio" name="menu_item_classes_position" value="right" checked=""> Sebelah kanan label</label>
</div>
<label class="move-button-handle">
<span>Pindahkan: </span>
Naik Satu
Turun Satu
Urutan Pertama
Urutan Terakhir
</label>
<div class="menu-item-actions submitbox">
<a class="item-delete danger-highlight" id="delete-2" href="#">Hapus</a><span> | </span>
<a class="item-cancel" id="cancel-2" href="#">Cancel</a>
</div>
</div>
</div>
</div>
<div class="panel menu-item">
<a class="panel-heading collapsed" role="tab" id="heading-menu-item-3" data-toggle="collapse" data-parent="#menu-ui-sortable" href="#menu-item-settings-3" aria-expanded="false" aria-controls="menu-item-settings-3">
<h4 class="panel-title">Menu Item 3</h4>
<i class="indicator glyphicon glyphicon-chevron-down pull-right"></i>
<i class="item-type pull-right">Tautan Tertentu</i>
</a>
<input type="hidden" name="menu_item_type" value="custom-link"/>
<input type="hidden" name="menu_item_page_id" value=""/>
<input type="hidden" name="menu_item_content_id" value=""/>
<div id="menu-item-settings-3" class="panel-collapse collapse" role="tabpanel" aria-labelledby="heading-menu-item-3">
<div class="panel-body">
<label>URL</label>
<input type="text" class="form-control" name="menu_item_url" value="www.example.com"/>
<label>Label Navigasi</label>
<input type="text" class="form-control" name="menu_item_title" value="label 3"/>
<label>Atribut Judul</label>
<input type="text" class="form-control" name="menu_item_attr_title" value="attr 3"/>
<p class="menu_item_target"><label><input type="checkbox" name="menu_item_target" value="1"> Buka tautan di tab baru</label></p>
<label>CSS Classes/Icon</label>
<input type="text" class="form-control" name="menu_item_classes" value="fa fa-files"/>
<label>Letak CSS Classes/Icon</label>
<div class="radio">
<label><input type="radio" name="menu_item_classes_position" value="left" checked=""> Sebelah kiri label</label>
<label><input type="radio" name="menu_item_classes_position" value="right"> Sebelah kanan label</label>
</div>
<label class="move-button-handle">
<span>Pindahkan: </span>
Naik Satu
Turun Satu
Urutan Pertama
Urutan Terakhir
</label>
<div class="menu-item-actions submitbox">
<a class="item-delete danger-highlight" id="delete-3" href="#">Hapus</a><span> | </span>
<a class="item-cancel" id="cancel-3" href="#">Cancel</a>
</div>
</div>
</div>
</div>
</div>
<br/>
<button id="menu-nav-action" type="submit" class="btn btn-success btn-sm">Save</button>
The js
$(document).ready(function () {
$("#menu-ui-sortable").collapse().sortable({
placeholder: "ui-sortable-placeholder",
start: function(evt, ui ){
ui.placeholder.height(ui.helper.outerHeight());
},
helper: function(evt, ui){
var $clone = $(ui).clone();
$clone .css('position','absolute');
return $clone.get(0);
}
});
$(document).on('click', '#menu-nav-action', function (evt) {
var menuNav = [];
var ctn = 0;
$("#menu-ui-sortable > div.panel.menu-item").each(function () {
var menu_item_target = $(this).find('input[name="menu_item_target"]');
var menu_item_target_ = menu_item_target.is(':checked') ? menu_item_target.val() : '0';
var menu_item_classes_position = $(this).find('input[name="menu_item_classes_position"]');
var menu_item_classes_position_ = '';
for (var i = 0, length = menu_item_classes_position.length; i < length; i++) {
if (menu_item_classes_position[i].checked) {
menu_item_classes_position_ = menu_item_classes_position[i].value;
console.log(menu_item_classes_position_);
break;
}
}
/* Using each() function not work too */
/*$(menu_item_classes_position).each(function () {
if ($(this).is(':checked')) {
menu_item_classes_position_ = $(this).val();
console.log(menu_item_classes_position_);
}
});*/
menuNav.push({
nav_label: $(this).find('input[name="menu_item_title"]').val(),
nav_title_attr: $(this).find('input[name="menu_item_attr_title"]').val(),
nav_open_new_tab: menu_item_target_,
nav_css_classes: $(this).find('input[name="menu_item_classes"]').val(),
nav_css_classes_position: menu_item_classes_position_,
nav_type: $(this).find('input[name="menu_item_type"]').val(),
nav_link: $(this).find('input[name="menu_item_url"]').val(),
nav_order: ctn});
ctn++;
});
console.log(menuNav);
alert(JSON.stringify(menuNav));
});
});
Here the output:
[
{
"nav_label":"label 1",
"nav_title_attr":"attr 1",
"nav_open_new_tab":"1",
"nav_css_classes":"fa fa-glass",
"nav_css_classes_position":"", // **this should be "left"**
"nav_type":"page",
"nav_link":"www.example.com/page-12",
"nav_order":0
},
{
"nav_label":"label 2",
"nav_title_attr":"attr 2",
"nav_open_new_tab":"0",
"nav_css_classes":"fa fa-search",
"nav_css_classes_position":"", // **this should be "right"**
"nav_type":"homepage-content",
"nav_link":"#content-4",
"nav_order":1
},
{
"nav_label":"label 3",
"nav_title_attr":"attr 3",
"nav_open_new_tab":"0",
"nav_css_classes":"fa fa-files",
"nav_css_classes_position":"left",
"nav_type":"custom-link",
"nav_link":"www.example.com",
"nav_order":2
}
]
Based the HTML, the correct value for nav_css_classes_position in each item are "left", "right", and "left".
Here the demo: jsfiddle
you are using same radio names[name="menu_item_classes_position"]for every group. Use different names for each group.
In your example, there are 3 menu items containing radio buttons wrapped in accordion. But these radio buttons are acting as a one group. that is,when you select radio button of second menu item, it will deselect radio button of first menu item.
your problem is due to this
<input type="radio" name="menu_item_classes_position" value="left" checked="checked"> Sebelah kiri label</label>
All of your radio element belongs to same group name="menu_item_classes_position" , as per the documentation of the radio input only one button of a group can be checked at a time. This is why only in menu 3 the radio button is checked. You can confirm this in your fiddle as well.
You should give each set of radio button in a menu a different name to select the correct value.

Javascript results need to capture in php to email

I have a form where I have a total of 11 checkboxes for the user to select from. I want to be able to capture which particular checkbox the user has selected and be able to send that out via email. I am currently using php to do that.
I am able to capture the value and display it as an alert using Javascript. However, I am unable to figure out how I could possibly take that specific data captured using javascript and be able to pass it to PHP.
I am very unfamiliar with PHP and have tried to pass a variable through but have failed. See link for my code in further detail.
<!-- Modal Body -->
<div class="modal-body">
<p>Please fill out the information below.</p>
<form class="j-forms" style="box-shadow: none;"
id="TSCreatePackageForm" role="form" method="post"
action="php/customPackage.php">
<!-- Company Name -->
<div class="span6 unit">
<label class="label">Company Name</label>
<div class="input">
<label class="icon-right" for="tscpCompanyName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpCompanyName" name="tscpCompanyName"
placeholder="e.g XYZ Company">
</div>
</div>
<!-- Business Entity Type -->
<div class="span6 unit">
<label class="label">Business
Entity Type</label>
<div class="input">
<label class="icon-right" for="tscpBusinessType">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpBusinessType" name="tscpBusinessType"
placeholder="(I.E. Corporation, LLC,ETC)">
</div>
</div>
<!--Years in Business -->
<div class="span6 unit">
<label class="label">Years In Business</label>
<div class="input">
<label class="icon-right" for="tscpYears">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpYears" name="tscpYears" placeholder="e.g. 5">
</div>
</div>
<!-- Number of Units -->
<div class="span6 unit">
<label class="label">Number of units Owned/Managed</label>
<div class="input">
<label class="icon-right" for="tscpNumberOfUnits">
<i class="fa fa-briefcase"></i>
</label>
<input type="text" id="tscpNumberOfUnits" name="tscpNumberOfUnits"
placeholder="e.g. 525">
</div>
</div>
<!-- First Name -->
<div class="span6 unit">
<label class="label">First Name</label>
<div class="input">
<label class="icon-right" for="tscpFirstName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpFirstName" name="tscpFirstName"
placeholder="e.g John">
</div>
</div>
<!-- Last Name -->
<div class="span6 unit">
<label class="label">Last Name</label>
<div class="input">
<label class="icon-right" for="tscpLastName">
<i class="fa fa-user"></i>
</label>
<input type="text" id="tscpLastName" name="tscpLastName"
placeholder="e.g Doe">
</div>
</div>
<!-- Email -->
<div class="span6 unit">
<label class="label">Email</label>
<div class="input">
<label class="icon-right" for="tscpEmail">
<i class="fa fa-mail"></i>
</label>
<input type="text" id="tscpEmail" name="tscpEmail"
placeholder="e.g John#therrd.com">
</div>
</div>
<!-- Phone Number -->
<div class="span6 unit">
<label class="label">Phone</label>
<div class="input">
<label class="icon-right" for="tscpNumber">
<i class="fa fa-phone"></i>
</label>
<input type="text" placeholder="phone/mobile" id="tscpNumber"
name="tscpNumber">
<span class="tooltip tooltip-right-top">Your contact phone number</span>
</div>
</div>
<!-- Services -->
<div class="span12 unit">
<label class="label">Please Select Services You're Interested In:</label>
<div class="span6">
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService1"
value="Incident Reporting Database" checked>
<i></i>
Incident Reporting Database
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService2"
value="Rapsheet (National Criminal Background Search)">
<i></i>
Rapsheet (National Criminal Background Search)
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService3"
value="Social Security Number Validation">
<i></i>
Social Security Number Validation
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService4"
value="Sex Offender Database Check">
<i></i>
Sex Offender Database Check
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService5"
value="Evictions, Liens, and Judgment Search">
<i></i>
Evictions, Liens, and Judgment Search
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService6"
value="Trans Union And Equifax Credit Report">
<i></i>
Trans Union And Equifax Credit Report
</label>
</div>
<div class="span6">
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService7"
value="FICO Score">
<i></i>
FICO Score
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService8"
value="Bankruptcy Report">
<i></i>
Bankruptcy Report
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService9"
value="ID Mismatch Alert">
<i></i>
ID Mismatch Alert
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService10"
value="Equifax Credit Report">
<i></i>
Equifax Credit Report
</label>
<label class="checkbox-toggle">
<input type="checkbox" name="tscpService[]" id="tscpService11"
value="Sex Offender Search (Meagan’s Law)">
<i></i>
Sex Offender Search (Meagan’s Law)
</label>
</div>
</div>
<!-- Captcha -->
<div class="span12 unit">
<div class="captcha-group">
<div class="input">
<label class="icon-right" for="captcha_code">
<i class="fa fa-unlock-alt"></i>
</label>
<input type="text" id="captcha_code" name="human"
placeholder="solve the captcha">
<span class="tooltip tooltip-right-top">Enter sum of the digits</span>
</div>
<label class="captcha" for="captcha_code">
2 + 3 = ?
</label>
</div>
</div>
<!-- Buttons -->
<div class="span6 unit">
<button type="submit" name="submit" value="Send"
class="btn btn-lg btn-theme-bg">Send
</button>
<a class="btn btn-lg btn-primary" data-dismiss="modal">Close</a>
</div>
<!-- Last Name -->
<div class="span6 unit hidden">
<label class="label">Last Name</label>
<div class="input">
<label class="icon-right" for="vals">
<i class="fa fa-user"></i>
</label>
<input type="text" id="vals" name="vals">
</div>
</div>
</form>
<!-- Validation -->
<script>
var vals = [];
/**CheckBox Value Function **/
var $checkes = $('input:checkbox[name="tscpService[]"]').change(function () {
var vals = $checkes.filter(':checked').map(function () {
return this.value;
}).get();
alert(JSON.stringify(vals));
});
$('#TSCreatePackageForm').validate({
/* #validation states + elements */
errorClass: 'error-view',
validClass: 'success-view',
errorElement: 'span',
rules: {
tscpCompanyName: {
required: true,
letterswithbasicpunc: true
},
tscpBusinessType: {
required: true,
letterswithbasicpunc: true
},
tscpYears: {
required: true,
digits: true,
min: 1
},
tscpNumberOfUnits: {
required: true,
digits: true,
min: 1,
max: 99999
},
tscpFirstName: {
required: true
},
tscpLastName: {
required: true
},
tscpEmail: {
required: true,
email: true
},
tscpNumber: {
required: true,
phoneUS: true
},
captcha_code: {
required: true
}
},
// Add class 'error-view'
highlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(validClass).addClass(errorClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(validClass).addClass(errorClass);
}
},
// Add class 'success-view'
unhighlight: function(element, errorClass, validClass) {
$(element).closest('.input').removeClass(errorClass).addClass(validClass);
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').removeClass(errorClass).addClass(validClass);
}
},
// Error placement
errorPlacement: function(error, element) {
if ( $(element).is(':checkbox') || $(element).is(':radio') ) {
$(element).closest('.check').append(error);
} else {
$(element).closest('.unit').append(error);
}
}
});
</script>
PHP Code
<?php
if ($_POST["submit"]) {
$companyName = $_POST['tscpCompanyName'];
$businessType = $_POST['tscpBusinessType'];
$yearsBusiness = $_POST['tscpYears'];
$numberOfUnits = $_POST['tscpNumberOfUnits'];
$firstName = $_POST['tscpFirstName'];
$lastName = $_POST['tscpLastName'];
$email = $_POST['tscpEmail'];
$number = $_POST['tscpNumber'];
$human = intval($_POST['human']);
$from = "From:senderEmail#senderEmail.com";
$to = "recieverEmail#recieverEmail.com";
$subject = 'Custom Package Request';
$body ="Company Name: $companyName\n\n Business Type: $businessType\n\n Years In Business: $yearsBusiness\n\n First Name: $firstName\n\n Last Name: $lastName\n\n Email: $email\n\n Number: $number\n\n Services: $selected\n\n";
//Check if simple anti-bot test is correct
if ($human !== 5) {
$errHuman = 'Your anti-spam is incorrect';
}
// If there are no errors, send the email
if (!$errName && !$errEmail && !$errMessage && !$errHuman) {
if (mail ($to, $subject, $body, $from)) {
header("Location: /thank-you/mortgage-lending.html");
} else {
header("Location: /Error.html");
}
}
else {
header("Location: /error.html");
}
}
?>
Why don't you use a hidden field form and send data to hidden field value.
`<input type="hidden" name="sth" id="sth">
now you can send the javascript value to this input field
as you described above you have grabbed value of check box
let's suppose you have taken checkbox value to a variable named vals in js
now you can do
<script>
//if your value from checkbox is placed on variable vals
$('#sth').val(vals)
</script>
using this what you can do is you can grab your value using any of post method
I figured out a way to obtained the value and be able to email it out using PHP.
Here is the code:
<!-- Checkbox Value -->
<script>
var vals = [];
document.getElementsByName('vals').value = vals;
/**CheckBox Value Function **/
var $checkes = $('input:checkbox[name="tscpService[]"]').change(function () {
var vals = $checkes.filter(':checked').map(function () {
return this.value;
}).get();
alert(JSON.stringify(vals));
document.getElementById('vals').value = JSON.stringify(vals);
});
<!-- Checkbox Value -->

Categories