dymanic forms fields based on radio boxes - javascript

I want to make a dynamic form. I am basing this on the post here
How To Show And Hide Input Fields Based On Radio Button Selection which has an updated jsfiddle here http://jsfiddle.net/QAaHP/16/
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
}
else document.getElementById('ifYes').style.display = 'none';
}
Yes <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="yesCheck"/>
No <input type="radio" onclick="javascript:yesnoCheck();" name="yesno" id="noCheck"/>
<br>
<div id="ifYes" style="visibility:hidden">
If yes, explain:
<input type='text' id='yes' name='yes'/>
<br>What can we do to accommodate you?
<input type='text' id='acc' name='acc'/>
</div>
other 3 <input type='text' id='other3' name='other3'><br>
other 4 <input type='text' id='other4' name='other4'><br>
Not being a big fan of javascript, I tried to modify this in a new jsfiddle here for detection of 'ifno' condition as well
http://jsfiddle.net/35nxgw8o/
My goal is to detect both the 'no' and 'yes' conditions so that I am making this an 'either/or, never 'both' condition but having little luck doing so. Maybe I am goiing about it all wrong?

#Stevish Indeed onchage does it.
I am posting what I used here as is so others may find it useful. It is PHP and Javascript. It allws me to set the pre-determined variable in the URL (GET) , then depending on which way it was loaded,(hideshow or showhide) Javascript handles it from there.
echo '><span style="color:#666; font-weight:bold; line-height: 300%"> Yes</span><input type="radio" name="mppdf" value="yes" onChange="getValue(this)"';
if ($_GET['mppdf']!='yes')
{
$showhide=' style="display: none "';
$hideshow=' style="display: block "';
echo ' checked';
}
else
{
}
if (($_GET['pdf']=='yes') || ($_GET['mppdf']=='yes') || (isset($_GET['pdfname'])))
{
$hideshow=' style="display:none; "';
$showhide=' style="display: block "';
echo ' checked';
}
else
{
echo '><div id="yourfield1" '.$showhide.'>';
echo'<input style="width: 120px; height: 16px; color:#666; background-color: #DDD; font-weight:bold" type="text" value="'.$_GET['pdfname'].'" placeholder="'.$name.'" id="pdfname" name="pdfname"';
echo' <div id="yourfield2" '.$hideshow.'"> ';
echo'
<span style="color:#666; font-weight:bold; line-height: 300%"> jpg</span>
<input type="radio" name="jpgpdf" value="no" id="JPG"';
if (($_GET['pdf']!='yes') && ($_GET['mppdf']!='yes') && (!isset($_GET['pdfname'])))
{
echo ' checked';
}
else
{
}
echo '><span style="color:#666; font-weight:bold; line-height: 300%"> pdf</span><input type="radio" name="jpgpdf" value="no" id="PDF"';
if (($_GET['pdf']=='yes') || ($_GET['mppdf']=='yes') ||(isset($_GET['pdfname'])))
{
echo ' checked';
}
else
{
}
echo'>
</div>';
<script type="text/javascript">
function getValue(x) {
if(x.value == 'No'){
document.getElementById("yourfield1").style.display = 'none'; // you need a identifier for changes
document.getElementById("yourfield2").style.display = 'block'; // you need a identifier for changes
}
else{
document.getElementById("yourfield1").style.display = 'block'; // you need a identifier for changes
document.getElementById("yourfield2").style.display = 'none'; // you need a identifier for changes
}
}
</script>

Related

Having trouble changing P tag on new page based on user input

Newbie here. I'm working on an Interactive rating site with two html pages, a CSS style stylesheet and a JS sheet. My issue is that the P tag will not change to the desired string (from a selection of multiple strings assigned to different variables) based on the users input.
When I place the strings at the top of the JS sheet it works; the catch is it only places the last variable into the p tag. So, I moved them into an if else statement. I'm not getting any red marks in VSCode, but it's still not working for me. Here's my code.
index.html
<html>
<body>
<form action="thank_you.html" method="get" onsubmit= "return isChecked();"
class="rating_radio">
<input class="rr_input" type="radio" name="rating" id="one" value="one"/><span
class="rr_span">1</span>
<input class="rr_input" type="radio" name="rating" id="two" value="two"/><span
class="rr_span">2</span>
<input class="rr_input" type="radio" name="rating" id="three" value="three"/>
<span class="rr_span">3</span>
<input class="rr_input" type="radio" name="rating" id="four" value="four"/><span
class="rr_span">4</span>
<input class="rr_input" type="radio" name="rating" id="five" value="five"/><span
class="rr_span">5</span>
<input class="rr_button" type="submit" value="SUBMIT" method="get"></input>
</form>
</body>
<script src="rating.js"></script>
</html>
thank_you.html
xx
rating.js
function isChecked() {
var checkOne = document.getElementById('one').checked;
var checkTwo = document.getElementById('two').checked;
var checkThree = document.getElementById('three').checked;
var checkFour = document.getElementById('four').checked;
var checkFive = document.getElementById('five').checked;
var rating = document.getElementById('yourRating');
if (checkOne == false && checkTwo == false && checkThree == false && checkFour ==
false && checkFive == false) {
alert("You need to select an option!");
return false;
}
if (checkOne == true) {
rating.innerHTML = 'You selected 1 out of 5'; /trying to get this tag to change in
thank.html/
return true;
}
else if (checkTwo == true) {
rating.innerHTML = 'You selected 2 out of 5'; /trying to get this tag to change
in thank.html/
return true;
}
else if (checkThree == true) {
rating.innerHTML = 'You selected 3 out of 5'; /trying to get this tag to change
in thank.html/
return true;
}
else if (checkFour == true) {
rating.innerHTML = 'You selected 4 out of 5'; /trying to get this tag to change
in thank.html/
return true;
}
else if (checkFive == true) {
rating.innerHTML = 'You selected 5 out of 5'; /trying to get this tag to change
in thank.html/
return true;
}
}
main.css
.select{
display: block;
color: #f97813;
background-color: #262f37;
padding: 5px;
text-align: center;
width: 50%;
margin-left: auto;
margin-right: auto;
margin-top: 1.5rem;
border-radius: 50px;
}
Go easy on me, I'm as new as new gets. Any help would be greatly appreciated.

jquery - toggle input values with link and php sessions

I have read all sorts of similar Q/A. This may be too specific I suppose.
I would like to toggle input (text) values by "clicking" a voided hyperlink
<a id="same" href="javascript:;">link</a>
The toggle values are stored in sessions.
So click the link once and value="session". Click again value="". Back and forth. I know its probably simple. I can read jquery. Still learning to write it.
$("#same").on("click", function(){
$("[name='event_contact_name']").val($("[name='<?php echo "session 1"; ?>']").val());
$("[name='event_contact_lastname']").val($("[name='<?php echo "session 2"; ?>']").val());
$("[name='event_contact_phone']").val($("[name='<?php echo "session 3"; ?>']").val());
$("[name='event_contact_email']").val($("[name='<?php echo "session 4"; ?>']").val());
});
You could PHP echo $_SESSION["something"] inside a data-* attribute of your input elements. like:
data-sessionval="<?= $_SESSION["something"] ?>"
Example with anchor toggle
$("#same").on("click", function() {
var tog = this._sessTog = !this._sessTog;
$("[data-sessionval]").val(function() {
return tog ? $(this).data("sessionval") : "";
});
});
<a id="same" href="javascript:;">Use session values</a>
<br>
Name: <input name="event_contact_name" data-sessionval="php echoed here">
last name: <input name="event_contact_lastname" data-sessionval="php echo text">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
But using anchors for something cehckoxes were invented for - seems odd, so:
$("#same").on("change", function() {
var ckd = this.checked;
$("[data-sessionval]").val(function() {
return ckd ? $(this).data("sessionval") : "";
});
});
<label><input id="same" type="checkbox"> Use session values</label>
<br>
Name: <input name="event_contact_name" data-sessionval="php echoed here">
last name: <input name="event_contact_lastname" data-sessionval="php echo text">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
If you don't like the checkbox, use CSS:
$("#same").on("change", function() {
var ckd = this.checked;
$("[data-sessionval]").val(function() {
return ckd ? $(this).data("sessionval") : "";
});
});
[type=checkbox] + span:before {
margin-right: 10px;
content: "\2610";
}
[type=checkbox]:checked + span:before {
content: "\2611";
color: #0bf;
}
<label>
<input id="same" type="checkbox" hidden>
<span>Use Session values</span>
</label>
<br> Name: <input name="event_contact_name" data-sessionval="php echoed here">
Last name: <input name="event_contact_lastname" data-sessionval="php echo text">
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Enable radio button only for admin user

In the application I'm developing I have an admin panel in that panel there a function to create, edit and delete users.
In the form I create 3 user types using a while loop which drags data from a database and the 3 user types are:
Admin
Manager
User
HTML Form:
<?php
/**
* Created by PhpStorm.
* User: SiNUX
* Date: 4/6/2017
* Time: 3:41 PM
*/
session_start();
include_once("../iConnect/handShake.php");
$getUserRole = "SELECT * FROM userroles ORDER BY urId ASC";
$getUserRoleQuery = $dbConnect -> query($getUserRole);
?>
<html>
<head>
<title>Timer User Creation</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Style Sheets -->
<link rel="stylesheet" type="text/css" href="../../CSS/main.css">
<!-- Java Scripts -->
<script language="JavaScript" type="text/javascript" src="../../jScripts/jquery-3.2.0.min.js"></script>
<script language="javascript" type="text/javascript" src="../../jScripts/svrTimeDate.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/reload.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/setMsg.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/userCreatFunctions.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/multiScript.js"></script>
<script language="JavaScript" type="text/javascript" src="../../jScripts/getIds.js"></script>
</head>
<body onload="pauseLoad4()">
<div id="divCenter" class="box">
<label id="userName">Hello <?php echo $_SESSION["fName"]." ".$_SESSION["lName"]; ?></label><br><br>
<label id="uId" hidden>1</label>
<div style="width: 166px; position: absolute; left: 642px; top: 20px; height: 44px;">
<img src="../../images/logo.png" width="142" height="33">
</div>
<label for="date">Date:</label>
<label id="date" style="margin-left: 50px;"></label><br><br>
<label for="fName">First Name:</label>
<input type="text" id="fName" name="fName" style="margin-left: 10px;" onkeyup="checkEmpty();">
<label for="lName" style="margin-left: 8px;">Last Name:</label>
<input type="text" id="lName" name="lName" style="margin-left: 10px;" onkeyup="checkEmpty();" disabled>
<label for="uName" style="margin-left: 8px;">User Name:</label>
<input type="text" id="uName" name="uName" style="margin-left: 7px;" onkeyup="checkEmpty();" disabled><br><br>
<label for="pWord1" style="margin-left: 8px;" >Password:</label>
<input type="password" id="pWord1" name="pWord1" style="margin-left: 17px;" onkeyup="checkLength();" disabled>
<label for="pWord2" style="margin-left: 8px;">Confirm Password:</label>
<input type="password" id="pWord2" name="pWord2" style="margin-left: 8px;" onkeyup="checkPass();" disabled>
<label for="uTeam" style="margin-left: 8px;">Team</label>
<select name="uTeam" id="uTeam" style="width: 170px;" onchange="teamId(this.id);enableRoles();" disabled>
<option></option>
</select>
<input type="text" name="uTeamId" id="uTeamId" hidden><br><br>
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
<label id="msgID" hidden></label>
<div id="msg"></div>
<div id="sbmBtns">
<input type="button" value="Reset" name="reset" id="reset" class="btn" onclick="resetForm()">
<input type="button" value="Submit" name="submit" id="submit" class="btn" onclick="pauseLoad3();" disabled>
</div>
</div>
</body>
</html>
I use a JavaScript to validate the form and to enable the next text box if the validation criteria is met.
JavaScript:
function checkEmpty() {
var msg = document.getElementById('msg'),
fName = document.getElementById('fName'),
lName = document.getElementById('lName'),
uName = document.getElementById('uName'),
pass1 = document.getElementById("pWord1");
//Using ajax made the function to check if the text box value is empty or not
//when that text box has focus.
if ($("#fName").is(':focus')){
if (fName.value.length <= 3){
msg.innerHTML = "First name is too short";
}else{
msg.innerHTML = "";
lName.disabled = false;
}
}
if ($("#lName").is(':focus')){
if (lName.value === fName.value){
msg.innerHTML = "Last and first name can't be the same";
pass1.disabled = true;
}else{
if (lName.value.length <= 3){
msg.innerHTML = "Last name is too short";
}else{
msg.innerHTML = "";
uName.disabled = false;
}
}
}
if ($("#uName").is(':focus')){
if (uName.value.length <= 3){
msg.innerHTML = "User name is too short";
pass1.disabled = true;
}else{
if(uName.value.length > 0){
checkUname();
}
}
}
function checkUname() {
if(window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
if (xmlhttp.responseText === "1"){
msg.innerHTML="Username taken";
pass1.disabled = true;
}else{
msg.innerHTML = "";
pass1.disabled = false;
}
}
};
xmlhttp.open("POST","../Functions/matchUname.php?uName="+uName.value,true);
xmlhttp.send();
}
}
function checkLength() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
passLength1 = pass1.value.length;
if(passLength1 <= 4){
document.getElementById("msg").innerHTML ="Password is less than 4 characters!";
}else{
document.getElementById("msg").innerHTML ="";
pass2.disabled = false;
}
}
function checkPass() {
var pass1 = document.getElementById("pWord1"),
pass2 = document.getElementById("pWord2"),
uTeam = document.getElementById("uTeam"),
matchColor = "#66cc66",
noMatchColor = "#ff6666";
if (pass1.value === pass2.value){
document.getElementById("msg").innerHTML ="Passwords match!";
pass1.style.backgroundColor = matchColor;
pass2.style.backgroundColor = matchColor;
uTeam.disabled = false;
}else{
document.getElementById("msg").innerHTML ="Passwords do not match!";
pass1.style.backgroundColor = noMatchColor;
pass2.style.backgroundColor = noMatchColor;
}
}
function enableRoles() {
var team = document.getElementById("uTeam").value,
teamId = document.getElementById("uTeamId").value,
tlCheck = document.getElementById("tl"),
role = document.getElementsByClassName("userRoles");
if (team !== ""){
//For loop to enable radio buttons
for (var i = 1; i < role.length; i++){
role[i].disabled = false;
//This part will take the team is from uTeamId text box
//send it to getTeam.php checks if that team has a leader if that team has a leader
//"set" value will be returned making the check box for team attribute team leader disabled.
if(window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
// document.getElementById("msgID").innerHTML = xmlhttp.responseText;
tlCheck.disabled = xmlhttp.responseText === "set";
}
};
xmlhttp.open("POST","../Functions/getTeam.php?teamId="+teamId,true);
xmlhttp.send();
}
}
}
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
It's working with out any errors but I want to disable the Admin user type if the logged in user is not a admin. I can get this done by using pure PHP but it breaks the flow of the form.
In my HTML/PHP form I have used PHP to archive what I'm describing but it not really what want to do I want use JavaScript or jQuery or AJAX to archive this.
The PHP I use:
<div id="userRoles">
<label for="userRoles">User Role:</label><label for="uAttrib" style="margin-left: 250px;">User Attributes:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" class="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>"
<?php if ($_SESSION["uRole"] != "1" && $row["userRole"] == "Admin" ){?> disabled <?php } ?>><?php echo $row["userRole"]; }?>
<input type="checkbox" id="tl" name="tl" value="yes" style="margin-left: 120px;" disabled>Team Leader
</div>
Can some direct me down the right path or show me how to do this.
UPDATE:
After talking with professionals I learned that what I was trying to do is to shoot my self in the foot by my own gun. It's a bad idea to use client side languages to handle security options and WE CAN'T TRUST THE USER. My main issues was the flow of the form but security trumps the beauty so this will be split in to another one which the normal user want even see the admin option.
I would like to leave this question here and don't mind if it get closed so others can learn something from my mistake.
Just to nail this one down...
After a nice chat discussion, it appears that Jack (OP) has understood the importance not to manage user level security on client side.
The questions no longer needs more answer.
;)

Change text color base on checkbox

I'm trying to change the text "I have read and agree...." to a different color when the checkbox is being clicked. Does it require a DIV & label to be place for both the text & checkbox ?.
I also notice the checkbox would be move to next line, when I place in the div class="checkbox" & label
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx " onchange="isChecked(this,'sub1')"/></p>
<p><input type="submit" name="submit" value="Order now!" id="sub1" disabled="disabled"/></p>
JS
function isChecked(checkbox, sub1) {
var button = document.getElementById(sub1);
if (checkbox.checked === true) {
button.disabled = "";
} else {
button.disabled = "disabled";
}
}
$(document).ready(function(){
$('#termsChkbx').change(function(){
if($(this).is(':checked'))
{
$(this).parent('p').css('color','black');
}
else
{
$(this).parent('p').css('color','red')
}
});
});
try,
$(document).ready(function(){
$('#termsChkbx').change(function(){
if($(this).is(':checked'))
{
$(this).parent().css('color','black');
}
else
{
$(this).parent().css('color','red')
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>

Javascript border colour not changing on radio button click

Im sorry to open a question, which I am sure many will consider very basic but I don't really know javascript and am learning as my application grows
I have the following
When radio button is clicked I would like the div with class="teams" to change border colour to red.
I came up with this code
<label><input type="radio" onclick="return border()" name="picks['.$x.']" id="one" value="'.$row['team1'].'"><span>'.$team1.'</span></label><br />
<label><input type="radio" onclick=" return border()" name="picks['.$x.']" id="two" value="'.$row['team2'].'"><span>'.$team2.'</span></label><br />
<label><input type="radio" onclick="return border()" name="picks['.$x.']" id="three" value="draw"><span>Draw</span></label><br />
</center>';
function border(){
if(document.getElementById("one").checked){
document.getElementById("teams").style.borderColor="red"
}
else if( document.getElementById("two").checked){
document.getElementById("teams").style.borderColor="red"
}
}
echo'<div class="teams">';
echo'<img src="images/teams/'.$src1.'.png" id="t1" />';
echo'<img src="images/teams/'.$src2.'.png" id="t2" />';
echo'</div>';
Clearly I am doing something wrong. Any help will be greatly appreciated
Following is the error thrown.
teams is a class attribute and not ID.
Change getElementById("teams") to getElementsByClassName("teams")
Note that getElementsByClassName("teams") returns an array of matched elements; so use a loop to set the value of each or just use getElementsByClassName("teams")[0].style.borderColor
function border() {
var el = document.getElementsByClassName("teams")[0];
if (document.getElementById("one").checked || document.getElementById("two").checked) {
el.style.borderColor = "red";
el.style.borderStyle = "solid";
}
}
Try onclick="border(this.id)"
<labe><input type="radio" onclick="border(this.id)" name="picks['.$x.']" id="one" value="'.$row['team1'].'"><span>'.$team1.'</span></label><br />
<label><input type="radio" onclick=" border(this.id)" name="picks['.$x.']" id="two" value="'.$row['team2'].'"><span>'.$team2.'</span></label><br />
function border(id){
if(document.getElementById(id).checked){
document.getElementsByClassName('teams')[0].style.borderColor="red"
}
}
Working demo
In your code teams is a class name and not id.
echo'<div class="teams">';
Either you change it to id:
echo'<div id="teams">';
Or use getElementsByClassName("teams"), it will give you NodeList
document.getElementsByClassName("teams")[0].style.borderColor="red";
Apart from this, you could possibly try this solution just using css pseudo:
input[type=radio].check {
display: none;
}
input[type=radio].check + label.check {
border: 1px solid grey;
padding: 5px 7px;
cursor: pointer;
width: 150px;
display: block;
text-align: center;
margin-bottom: 2px;
}
input[type=radio].check:checked + label.check {
background: red;
}
<input type='radio' name='team' value='Team 1' class='check' id='check1' />
<label for='check1' class='check'>Team 1</label>
<input type='radio' name='team' value='Team2' class='check' id='check2' />
<label for='check2' class='check'>Team 2</label>
<input type='radio' name='team' value='Draw' class='check' id='check3' />
<label for='check3' class='check'>Draw</label>
Just a little tip I would try and get away from using the onclick events and move towards external javascript.
I've created an example of something you could try.
$(':radio').change(function ()
{
if ($(this).val() == "team1")
{
$(".row").css("border-color", "blue");
}
else if ($(this).val() == "team2")
{
$(".row").css("border-color", "red");
}
});
div.row {
border: 2px solid black;
height: 200px;
width:200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="row">
</div>
<label for="team1">1</label>
<input id="team1" type="radio" name="team1" value="team1">
<label for="team2">2</label>
<input id="team2" type="radio" name="team2" value="team2">

Categories