i would like input from my user to go into a database, but it is not working. I have a working block of sql code that would insert the data into the database, but i keep getting "undefined" errors when it gets ran.
This is the fully working sql code
<?php
require 'creationlink.php';
$quizname = $_POST['name'];
$quest = $_POST['question'];
$ans1 = $_POST['answer1'];
$ans2 = $_POST['answer2'];
$ans3 = $_POST['answer3'];
$ans4 = $_POST['answer4'];
$correct = $_POST['A'];
//initiates connection with database with creation file
$sql = "INSERT INTO Quiz(question, answer1, answer2, answer3, answer4, correct) VALUES (?, ?, ?, ?, ?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ssssss", $quest, $ans1, $ans2, $ans3, $ans4, $correct);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not execute query: $sql. " . mysqli_error($conn);
}
}
else{
echo "ERROR: Could not prepare query: $sql. " . mysqli_error($conn);
}
?>
and this is the code that i would like the sql to apply to, which is just a simple quiz template that iterates depending on the user input.
<html>
<body>
<form id='namennumber' action="includes/dbquestions.php" method="post">
<label for="quizname"><b>Quiz name</b></label>
<input name="quizname" type="text" placeholder="Enter quizname" required>
<div id="myHTMLWrapper">
</div>
</form>
<div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont">
<div id="questionform" class="modal">
<label for="question"><b>Enter a question</b></label>
<input name="question" type="text" placeholder="Enter a question" value ="question" required>
<br>
<label for="answer1">Possible answer A</label>
<input type="text" name="answer1" placeholder="Enter a possible answer" value ="answer1"required>
<br>
<label for="answer2">Possible answer B</label>
<input type="text" name="answer2" placeholder="Enter a possible answer" value ="answer2"required>
<br>
<label for="answer3">Possible answer C</label>
<input type="text" name="answer3" placeholder="Enter a possible answer" value ="answer3"required>
<br>
<label for="answer4">Possible answer D</label>
<input type="text" name="answer4" placeholder="Enter a possible answer" value ="answer4"required>
<br>
<h3>Correct answer</h3>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="A") echo "checked"; ?> value="A" />
<label for="A">A</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="B") echo "checked"; ?> value="B" />
<label for="B">B</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="C" )echo "checked"; ?> value="C" />
<label for="C">C</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="D" )echo "checked"; ?> value="D"/>
<label for="D">D</label>
<br>
<form action="includes/dbquestions.php">
<button style="width:auto;" id="enter" class="btn btn-primary big-btn" >Save</button>
</form>
</div>
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 0; i < number; i++) {
myHTML += '<span class="test">Question ' + (i + 1)
myHTML += '<input type="button" value="Content" id="bt" onclick="toggle(\'cont\')">' +
'</span><br/><br/>';
}
wrapper.innerHTML = myHTML
function toggle(cont) {
var cont = document.getElementById('cont');
if (cont.style.display == 'block') {
cont.style.display = 'none';
document.getElementById(ele.id).value = 'Show DIV';
}
else {
cont.style.display = 'block';
document.getElementById(ele.id).value = 'Hide DIV';
}
};
</script>
</div>
</body>
In your HTML, all the <input> elements are outside the <form> and hence you are getting the undefined error. To resolve the error move your <input> elements to the <form> tag. Try replacing your html code as below.
<html>
<body>
<form id='namennumber' action="includes/dbquestions.php" method="post">
<label for="quizname"><b>Quiz name</b></label>
<input name="quizname" type="text" placeholder="Enter quizname" required>
<div id="myHTMLWrapper">
</div>
</form>
<div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont">
<div id="questionform" class="modal">
<form action="includes/dbquestions.php"> //moved all the input elements
<label for="question"><b>Enter a question</b></label>
<input name="question" type="text" placeholder="Enter a question" value="question" required>
<br>
<label for="answer1">Possible answer A</label>
<input type="text" name="answer1" placeholder="Enter a possible answer" value="answer1" required>
<br>
<label for="answer2">Possible answer B</label>
<input type="text" name="answer2" placeholder="Enter a possible answer" value="answer2" required>
<br>
<label for="answer3">Possible answer C</label>
<input type="text" name="answer3" placeholder="Enter a possible answer" value="answer3" required>
<br>
<label for="answer4">Possible answer D</label>
<input type="text" name="answer4" placeholder="Enter a possible answer" value="answer4" required>
<br>
<h3>Correct answer</h3>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="A") echo "checked"; ?> value="A" />
<label for="A">A</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="B") echo "checked"; ?> value="B" />
<label for="B">B</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="C" )echo "checked"; ?> value="C" />
<label for="C">C</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="D" )echo "checked"; ?> value="D" />
<label for="D">D</label>
<br>
<button style="width:auto;" id="enter" class="btn btn-primary big-btn">Save</button>
</form>
</div>
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 0; i < number; i++) {
myHTML += '<span class="test">Question ' + (i + 1)
myHTML += '<input type="button" value="Content" id="bt" onclick="toggle(\'cont\')">' +
'</span><br/><br/>';
}
wrapper.innerHTML = myHTML
function toggle(cont) {
var cont = document.getElementById('cont');
if (cont.style.display == 'block') {
cont.style.display = 'none';
document.getElementById(ele.id).value = 'Show DIV';
} else {
cont.style.display = 'block';
document.getElementById(ele.id).value = 'Hide DIV';
}
};
</script>
</body>
</html>
As a note, you are using the same parameter for action, for both the <form>s in your HTML. See below.
action="includes/dbquestions.php"
Since you are using $_POST in your server side code, you will have to specify method as post for your <form>, as the default method for a <form> is get and not post.
UPDATE
From your errors, that you have posted in the comments, I've combined the 2 forms that you were using.
<html>
<body>
<form id='namennumber' action="includes/dbquestions.php" method="post">
<label for="quizname"><b>Quiz name</b></label>
<input name="quizname" type="text" placeholder="Enter quizname" required>
<div id="myHTMLWrapper">
</div>
<div style="border:solid 1px #ddd; padding:10px; display:none;" id="cont">
<div id="questionform" class="modal">
<label for="question"><b>Enter a question</b></label>
<input name="question" type="text" placeholder="Enter a question" value="question" required>
<br>
<label for="answer1">Possible answer A</label>
<input type="text" name="answer1" placeholder="Enter a possible answer" value="answer1" required>
<br>
<label for="answer2">Possible answer B</label>
<input type="text" name="answer2" placeholder="Enter a possible answer" value="answer2" required>
<br>
<label for="answer3">Possible answer C</label>
<input type="text" name="answer3" placeholder="Enter a possible answer" value="answer3" required>
<br>
<label for="answer4">Possible answer D</label>
<input type="text" name="answer4" placeholder="Enter a possible answer" value="answer4" required>
<br>
<h3>Correct answer</h3>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="A") echo "checked"; ?> value="A" />
<label for="A">A</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="B") echo "checked"; ?> value="B" />
<label for="B">B</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="C" )echo "checked"; ?> value="C" />
<label for="C">C</label>
<br>
<input type="radio" name="A" <?php if (isset($answer) && $answer=="D" )echo "checked"; ?> value="D" />
<label for="D">D</label>
<br>
<button style="width:auto;" id="enter" class="btn btn-primary big-btn">Save</button>
</form>
</div>
</div>
<script>
var wrapper = document.getElementById("myHTMLWrapper");
var number = prompt("Enter the number of questions");
var myHTML = '';
for (var i = 0; i < number; i++) {
myHTML += '<span class="test">Question ' + (i + 1)
myHTML += '<input type="button" value="Content" id="bt" onclick="toggle(\'cont\')">' +
'</span><br/><br/>';
}
wrapper.innerHTML = myHTML
function toggle(cont) {
var cont = document.getElementById('cont');
if (cont.style.display == 'block') {
cont.style.display = 'none';
document.getElementById(ele.id).value = 'Show DIV';
} else {
cont.style.display = 'block';
document.getElementById(ele.id).value = 'Hide DIV';
}
};
</script>
</body>
</html>
Related
I want form to be loop by how many checkboxes are checked. Like if for each color what sizes are available. But having some issues. For each checkbox I check It's implementing on all color arrays like in the picture what am looking for
form page
<form method="post" action="submit.php">
ID:<input type="text" name="id" />
Name:<input type="text" name="product" />
<div class="form-group fieldGroup">
<div class="input-group">
Color : <input type="text" name="color[]" id="color">
X <input type="checkbox" name="size[]" id="size" value="X" >
XL <input type="checkbox" name="size[]" id="size" value="XL">
S <input type="checkbox" name="size[]" id="size" value="S">
M <input type="checkbox" name="size[]" id="size" value="M">
<span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span> Add
</div>
</div>
<input type="submit" name="submit" class="btn btn-primary" value="SUBMIT"/>
</form>
submit.php code
if(isset($_POST['submit'])){
$colorArray = $_POST['color'];
$sizeArray = $_POST['size'];
$product = $_POST['product'];
$sl = 1;
$id = $_POST["id"];
$product = $_POST["product"];
if(!empty($colorArray)){
for($i = 0; $i < count($colorArray); $i++){
if(!empty($colorArray[$i])){
foreach ($sizeArray as $x ){
$color = $colorArray[$i];
echo "<h2>" .$sl."> Name : ". $product ." > ".$id ." > ". $color .">" .$x ."</h2>";
$sl++;
}
}
}
}
}
I don't know why this code won't work. I need a simple solution. This is just a college project and it doesn't have to do more then just following:
I want to make ti so that when someone enters their name, location and eaddress, gender and comment alert box pops up with this kind of form:
Name, Location, eAddress, Gender
comment...
Code:
<div style="font-family:'Cinzel';text-align:center;">
Ime: <input type="text" name="Ime" value=""><br></br>
Lokacija: <input type="text" name="Lokacija" value=""></br><br>
E Adresa: <input type="text" name="eAdresa" value=""></br><br>
<form>
<input type="radio" name="gender" value="male" checked> Muško
<input type="radio" name="gender" value="female"> Žensko
<input type="radio" name="gender" value="other"> Drugo<br>
<button onclick="Ispis()">Pošalji</button>
</form>
<textarea rows="4" cols="50" name="Komentar" form="usrform" placeholder="Ostavite komentar..."></textarea>
</div>
<script>
function Ispis(){
var Ime=getElementsByName=("Ime")[0].value;
var lokacija=getElementsByName=("Lokacija")[0].value;
var eAdresa=getElementsByName=("eAdresa")[0].value;
var Pol=getElementsByName=("gender")[0].value;
alert(Ime+","+Lokacija+","+eAdresa+","+Gender+"<br>"+Komentar);
}
</script>
There are a few problems with your code:
the form instantly gets submitted when clicking on a button, you can make an input with button type that will not submit automatically
lokacija=document.getElementsByName("Lokacija")[0].value needs document. and doesn't need = after getElementsByName
few missing variables, javascript variable names are case sensitive
in the alert box, you can use "\n" for line break (new line)
to correctly handle selected radio buttons, you can use the :checked queryselector like so: var Gender = document.querySelector('[name="gender"]:checked').value
function Ispis(){
var Ime = document.getElementsByName("Ime")[0].value;
var lokacija = document.getElementsByName("Lokacija")[0].value;
var Gender = document.getElementsByName("gender")[0].value;
var Gender = document.querySelector('[name="gender"]:checked').value;
var eAdresa = document.getElementsByName("eAdresa")[0].value;
var Komentar = document.getElementsByName("Komentar")[0].value;
alert(Ime+","+lokacija+","+eAdresa+","+Gender+"\n"+Komentar);
}
<div style="font-family:'Cinzel';text-align:center;">
Ime: <input type="text" name="Ime" value=""><br><br>
Lokacija: <input type="text" name="Lokacija" value=""><br><br>
E Adresa: <input type="text" name="eAdresa" value="">
<form>
<input type="radio" name="gender" value="male" checked> Muško
<input type="radio" name="gender" value="female"> Žensko
<input type="radio" name="gender" value="other"> Drugo<br>
<input type="button" onclick="Ispis()" value="alert!">
</form>
<textarea rows="4" cols="50" name="Komentar" form="usrform" placeholder="Ostavite komentar..."></textarea>
</div>
I think this is because of the button that is submitting your form try out to put
<input type="button" onclick="Ispis()" value="Yourtext">
then rename your variables with lowercase, it's case sensitive
You can change your code as below to work...
<div style="font-family:'Cinzel';text-align:center;">
Ime: <input type="text" name="Ime" value=""><br></br>
Lokacija: <input type="text" name="Lokacija" value=""></br><br>
E Adresa: <input type="text" name="eAdresa" value=""></br><br>
<form>
<input type="radio" name="gender" value="male" checked> Muško
<input type="radio" name="gender" value="female"> Žensko
<input type="radio" name="gender" value="other"> Drugo<br>
<button onclick="Ispis()">Pošalji</button>
</form>
<textarea rows="4" cols="50" name="Komentar" form="usrform" placeholder="Ostavite komentar..."></textarea>
</div>
<script>
function Ispis(){
var Ime=document.getElementsByName("Ime")[0].value;
var lokacija=document.getElementsByName("Lokacija")[0].value;
var eAdresa=document.getElementsByName("eAdresa")[0].value;
var Gender=document.getElementsByName("gender")[0].value;
var Komentar=document.getElementsByName("Komentar")[0].value;
debugger
alert(Ime+","+lokacija+","+eAdresa+","+Gender+"\n"+Komentar);
}
</script>
You had some syntax errors, here a working version:
function Ispis() {
var ime = document.getElementsByName("ime")[0].value;
var lokacija = document.getElementsByName("lokacija")[0].value;
var eAdresa = document.getElementsByName("eadresa")[0].value;
var pol = document.getElementsByName("gender")[0].value;
var komentar = document.getElementsByName("komentar")[0].value;
alert(ime + "," + lokacija + "," + eAdresa + "," + pol + "<br>" + komentar);
}
<div style="font-family:'Cinzel';text-align:center;">
<form>
Ime: <input type="text" name="ime" value=""><br> Lokacija: <input type="text" name="lokacija" value=""><br> E Adresa: <input type="text" name="eadresa" value=""><br>
<input type="radio" name="gender" value="male" checked> Muško
<input type="radio" name="gender" value="female"> Žensko
<input type="radio" name="gender" value="other"> Drugo<br>
<button type="button" onclick="Ispis()">Pošalji</button>
</form>
<textarea rows="4" cols="50" name="komentar" form="usrform" placeholder="Ostavite komentar..."></textarea>
</div>
Written using ES6:
(function () {
const getValueFromElement = name => document.getElementsByName(name)[0].value
const ispis = () => {
const ime = getValueFromElement("ime");
const lokacija = getValueFromElement("lokacija");
const eAdresa = getValueFromElement("eadresa");
const pol = getValueFromElement("gender");
const komentar = getValueFromElement("komentar");
alert(`${ime},${lokacija},${eAdresa},${pol},<br>${komentar}`)
}
const button = document.getElementById('button')
button.addEventListener('click', () => ispis())
}());
<div style="font-family:'Cinzel';text-align:center;">
<form>
Ime: <input type="text" name="ime" value=""><br> Lokacija: <input type="text" name="lokacija" value=""><br> E Adresa: <input type="text" name="eadresa" value=""><br>
<input type="radio" name="gender" value="male" checked> Muško
<input type="radio" name="gender" value="female"> Žensko
<input type="radio" name="gender" value="other"> Drugo<br>
<button id="button" type="button">Pošalji</button>
</form>
<textarea rows="4" cols="50" name="komentar" form="usrform" placeholder="Ostavite komentar..."></textarea>
</div>
I am having a PHP while loop. Inside my while loop, I am having an HTML form. I am processing that form values through ajax into my PHP which then updates those values in my DB. The problem is whenever I submit that form it only updates the first fetched row in my table. I am also passing the unique Id through my form into ajax but for some reason, only the first row is keep getting updated.
My Php Code:
<?php
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) { ?><form>
<input type="text" name="id" value="<?php echo $row['no'] ?>"><br>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio" value="NO">NO
<input type="radio" name="optradio" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio1" value="NO">NO
<input type="radio" name="optradio1" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio2" value="NO">NO
<input type="radio" name="optradio2" value="YES">YES
</div>
</fieldset>
<button type="submit" value="Submit" class="btn">SUBMIT</button>
</form><?php }
My Ajax Code:
$(document).ready(function(){
var launchAjax = function () { // event handler for button click
$.post(
"inbetween.php/",
{
id: $("[name=id]").val(),
question: $("[name=optradio]:checked").val(),
question1: $("[name=optradio1]:checked").val(),
question2: $("[name=optradio2]:checked").val(),
}
);
}
$(".btn").click(launchAjax);
});
My PHP SQL Query
<?php
include 'common.php';
$id = filter_input(INPUT_POST, "id", FILTER_SANITIZE_NUMBER_INT);
$question = filter_input(INPUT_POST, "optradio", FILTER_SANITIZE_STRING);
$question1 = filter_input(INPUT_POST, "optradio1", FILTER_SANITIZE_STRING);
$question2 = filter_input(INPUT_POST, "optradio2", FILTER_SANITIZE_STRING);
function getMark($answer, $mark = 1){
$result = 0;
if($answer == 'YES'){
$result = $mark;
}
return $result;
}
$p = 0;
$p += getMark($question, 1);
$p += getMark($question1, .5);
$p += getMark($question2, 2);
$command1 = "UPDATE rating SET marks = marks + '$c', marks= marks/ totalNumber WHERE no = '$id'";
// prepare and executing
$stmt1 = $dbh->prepare($command1);
$result = $stmt1->execute();
?>
You are using PDO, but your while loop seems to be using the mysqli approach, and if you are selecting multiple rows you use fetchAll, update your code as such:
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
$id = $row['no'];
}
Update: if you want multiple forms, one for each row, you have to do it this way:
<?php
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) { ?><form>
<input type="text" name="id" value="<?php echo $row['no'] ?>"><br>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio" value="NO">NO
<input type="radio" name="optradio" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio1" value="NO">NO
<input type="radio" name="optradio1" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio2" value="NO">NO
<input type="radio" name="optradio2" value="YES">YES
</div>
</fieldset>
<button type="submit" value="Submit" class="btn">SUBMIT</button>
</form><?php }
I don't know if i missed some small error or what but can't get it to work.
I have a form which will send data to email_to_us.php. Inside the form I have two radio buttons. They are inside this form becouse this is a mandatory data which is also send to us. Now I want to change a form depending on what a user chooses. So far I have this:
HTML:
<form action="email_to_us.php" method="post">
<span class="link_title">Prijavljam se na tečaj:</span><br><br>
<select name="prijava_na_datum" required>
<option value="" selected="selected">Izberi datum</option>;
<?php
$con = mysqli_connect('localhost','root','','viverius_education');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql = mysqli_query($con, "SELECT ID_TECAJA, DATUM FROM razpisani_tecaji WHERE STATUS ='odprt' AND ST_ODPRTIH_MEST>0");
while ($row = $sql->fetch_assoc()){
echo "<option value='" . $row['ID_TECAJA'] . "'>" . $row['DATUM'] . "</option>";
}
?>
</select>
<br>
<input type="radio" id="radio1" name="status_osebe" value="fizicna" required> Fizična oseba
<input type="radio" id="radio2" name="status_osebe" value="pravna"> Pravna oseba<br><br>
<form method ="post" id="fizicna_oseba">
<input class="span7" type="text" name="ime" value="" placeholder="Ime" required/>
<input class="span7" type="text" name="priimek" value="" placeholder="Priimek" required />
<input class="span7" type="email" name="email" value="" placeholder="Email" required/>
<input class="span7" type="text" name="telefon" value="" placeholder="Telefonska številka (podatek ni obvezen)"/><br>
Vaša izobrazba/status<br>
<select name="izobrazba" required>
<option></option>
<option value="student">Študent</option>
<option value="pripravnik">Pripravnik</option>
<option value="specializant">Specializant</option>
<option value="specialist">Specialist</option>
</select>
<input class="span7" type="text" name="kraj" value="" placeholder="Ustanova/kraj (podatek ni obvezen)"/><br>
</form>
<form method ="post" id="podjetje">
<input class="span7" type="text" name="ime" value="" placeholder="Ime" required/>
<input class="span7" type="text" name="priimek" value="" placeholder="Priimek" required />
<input class="span7" type="email" name="email" value="" placeholder="Email" required/>
<input class="span7" type="text" name="telefon" value="" placeholder="Telefonska številka (podatek ni obvezen)"/><br>
Izberite koliko oseb želite prijaviti na tečaj? Odprla se vam bodo dodatna okna kjer prosimo, da izpolnete podatke o udeležencih.<br>
<input type="radio" id="radio01" name="st_oseb" value="fizicna" required>1
<input type="radio" id="radio02" name="st_oseb" value="pravna">2
<input type="radio" id="radio03" name="st_oseb" value="fizicna" required>3
<input type="radio" id="radio04" name="st_oseb" value="pravna">4
<input type="radio" id="radio05" name="st_oseb" value="pravna">5<br><br>
Vaša izobrazba/status<br>
<select name="izobrazba" required>
<option></option>
<option value="student">Študent</option>
<option value="pripravnik">Pripravnik</option>
<option value="specializant">Specializant</option>
<option value="specialist">Specialist</option>
</select>
<input class="span7" type="text" name="kraj" value="" placeholder="Ustanova/kraj (podatek ni obvezen)"/><br>
</form>
<input type="checkbox" name="register" value="register"> Ob prijavi me tudi registriraj!
Kaj pridobim z registracijo?<br><br>
<input type="submit" class="btn send_btn" value="Pošlji" />
<div class="clear"></div><br>
</form>
JavaSript:
<script type="text/javascript">
$('#radio1').change(function() {
if(this.checked) {
$('#fizicna_oseba').show();
$('#podjetje').hide();
}
});
$('#radio2').change(function() {
if(this.checked) {
$('#podjetje').show();
$('#fizicna_oseba').hide();
}
});
</script>
A simpler and cleaner way would be to use with class name
<input ... class="rButton">
<input ... class="rButton">
Script
$( ".rButton" ).change(function() {
switch($(this).val()) {
case 'fizician_ca' :
// do something on this value
break;
case 'etc' :
// do something with this value
break;
}
});
Using radio button I want to change my form. For example if 'A' radio button is selected, it should show me a form where I can enter my name and age. If 'B' is selected, it should show me another form, where I can see a picture, but the text field for the name and age are no longer visible.
You can use the onchange attribute of an input to call a javascript function, which hides A & shows B or vice versa
function hideA(x) {
if (x.checked) {
document.getElementById("A").style.visibility = "hidden";
document.getElementById("B").style.visibility = "visible";
}
}
function hideB(x) {
if (x.checked) {
document.getElementById("B").style.visibility = "hidden";
document.getElementById("A").style.visibility = "visible";
}
}
Show :
<input type="radio" onchange="hideB(this)" name="aorb" checked>A |
<input type="radio" onchange="hideA(this)" name="aorb">B
<div id="A">
<br/>A's text</div>
<div id="B" style="visibility:hidden">
<br/>B's text</div>
I liked the Answer from Vinayak Garg
Though a more portable solution was desired that could be used for many options using a basic structure minimal javascript is needed to swap options
The example function used in the next 2 snippets is:
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for(i = 0 ; i < radioName.length; i++){
document.getElementById(radioName[i].id.concat("Settings")).style.display="none";
}
document.getElementById(x.id.concat("Settings")).style.display="initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production1</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent1</label>
<input type="text" name="d1" value="/">
</p>
</div>
</fieldset>
Doing it this way you can add new options without changing the javascript
such as adding alpha and beta options as shown below you will see the same javascript is used.
function swapConfig(x) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat("Settings")).style.display = "none";
}
document.getElementById(x.id.concat("Settings")).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this)" name="urlOptions" id="beta" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="b1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
</fieldset>
It could be even more reusable by adding a second variable to the function:
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
function swapConfig(x, y) {
var radioName = document.getElementsByName(x.name);
for (i = 0; i < radioName.length; i++) {
document.getElementById(radioName[i].id.concat(y)).style.display = "none";
}
document.getElementById(x.id.concat(y)).style.display = "initial";
}
<fieldset>
<legend>Url and Domain Configuration</legend>
<p>
<label for="production">Production</label>
<input type="radio" onchange="swapConfig(this, 'Settings')" name="urlOptions" id="production" checked="checked" />
<label for="development">Development</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="development" />
<label for="alpha">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="alpha" />
<label for="beta">Beta</label>
<input type="radio" onchange="swapConfig(this,'Settings')" name="urlOptions" id="beta" />
</p>
<p>
<label for="alphaVar">Alpha</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="alphaVar" checked="checked" />
<label for="betaVar">Beta</label>
<input type="radio" onchange="swapConfig(this,'Val')" name="urlVars" id="betaVar" />
</p>
<div id="productionSettings">
<br/>Production Settings
<p>
<label for="p1">Production</label>
<input type="text" name="p1" value="/">
</p>
</div>
<div id="developmentSettings" style="display:none">
<br/>Development Settings
<p>
<label for="d1">Developent</label>
<input type="text" name="d1" value="/">
</p>
</div>
<div id="alphaSettings" style="display:none">
<br/>Alpha Settings
<p>
<label for="a1">Alpha</label>
<input type="text" name="a1" value="/">
</p>
</div>
<div id="betaSettings" style="display:none">
<br/>Beta Settings
<p>
<label for="d1">Beta</label>
<input type="text" name="b1" value="/">
</p>
</div>
<div id="alphaVarVal">
<br/>Alpha Values
<p>
<label for="aV1">Alpha Vals</label>
<input type="text" name="aV1" value="/">
</p>
</div>
<div id="betaVarVal" style="display:none">
<br/>Beta Values
<p>
<label for="bV1">Beta Vals</label>
<input type="text" name="bV1" value="/">
</p>
</div>
</fieldset>
Javascript for loops are well described in this Answer of the question For-each over an array in JavaScript?
This can be done like this.
<html>
<head>
<script language="Javascript">
function show(x)
{
var element=document.getElementById(x.id);
if(element.id=='a')
{
document.getElementById("area").innerHTML="Name : <input type='text' id='name' >";
}
else
{
document.getElementById("area").innerHTML="<img src='imgSrc' alt='NoImage'>"
}
}
</script>
</head>
<body>
<input type="radio" onclick="show(this)" name="radioButton" id="a" >A
<input type="radio" onclick="show(this)" name="radioButton" id="b" >B
<br> <br> <br>
<div id="area"> </div>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<div class="row clearfix">
<input type="radio" name="salary_status" id="Hourly" onclick="Hourly()"> Hourly
<input type="radio" name="salary_status" id="Percentage" onclick="Percentage()"> Percentage
</div>
<div class="row clearfix">
<p id="hourly" style="display:none"> <input type="text" placeholder=" Hourly" name="Hourly" placeholder="Hourly" required="required" class="form-control col-md-9 col-xs-12" ></p>
<p id="percentage" style="display:none"> <input type="number" name="Percentage" placeholder="Percentage" required="required" class="form-control col-md-9 col-xs-12" ></p>
</div>
<script>
var text1 = document.getElementById("percentage");
var text = document.getElementById("hourly");
function Hourly() {
var checkBox = document.getElementById("Hourly");
if (checkBox.checked == true){
text.style.display = "block";
text1.style.display = "none";
} else{
text.style.display = "none";
}
}
function Percentage() {
var checkBox = document.getElementById("Percentage");
if (checkBox.checked == true){
text1.style.display = "block";
text.style.display = "none";
} else {
text.style.display = "none";
}
}
</script>
</body>
</html>
I modified the above in a more easy way. Try editing it according to your needs:
<html>
<head>
<script language="Javascript">
function hideA()
{
document.getElementById("A").style.visibility="hidden";
document.getElementById("B").style.visibility="visible";
}
function hideB()
{
document.getElementById("B").style.visibility="hidden";
document.getElementById("A").style.visibility="visible";
}
</script>
</head>
<body>Show :
<input type="radio" name="aorb" onClick="hideB()" checked>A |
<input type="radio" name="aorb" onClick="hideA()">B
<div style="position: absolute; left: 10px; top: 100px;" id="A"><br/>A's text</div>
<div style="position: absolute; left: 10px; top: 100px; visibility:hidden" id="B"><br/>B's text</div>
</body>
</html>