create a textbox based on the value of a radioButton - javascript

Hello Everyone I want to make sure that in my project once I change the value of a radio button next to it is created / or a textBox is made visible ..
If the radioButton is "(SI)" the textBox is shown
if the radioButton is "(NO") the textBox is dimmed
I am attaching an attempt that I made to generate textBox .. but I do not know how to manage the value of the radioButton ..
PS do not be ruthless, I'm a beginner with JavaScript--
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num=1;
function accoda(){
if(document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr=document.createElement("TR");
var oTd1=document.createElement("TD");
var oTd2=document.createElement("TD");
var oField=document.createElement("INPUT");
var oButt=document.createElement("INPUT");
// setta attributi
oField.setAttribute("type","text");
oField.setAttribute("name","testo"+num);
oButt.setAttribute("type","button");
oButt.setAttribute("value","rimuovi");
// setta gestore evento
if(oButt.attachEvent) oButt.attachEvent('onclick',function(e){rimuovi(e);})
else if(oButt.addEventListener) oButt.addEventListener('click',function(e){rimuovi(e);},false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e){
if(document.removeChild && document.getElementById && document.getElementsByTagName) {
if(!e) e=window.event;
var srg=(e.target)?e.target:e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while(srg.tagName!="TR"){srg=(srg.parentNode)?srg.parentNode:srg.parentElement}
// riferimento al tbody
var tb=document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td><td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<script language="javascript">
function controlla(){
x=document.prova;
if (x.scelta.value=="si"){
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value=="no"){
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
</script>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br />
NO<input type="radio" name="scelta" value="no" /><br />
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>

Try this
function controlla() {
console.log("oie");
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=608675750'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si">
<input type="text" id="myInput" style="display: block;"><br>
NO<input type="radio" name="scelta" value="no"><br>
<button type="submit">INVIA</button>
</form>
</fieldset>
</body>
</html>

Change the display to 'none' for the textbox
You could have an if block. Something like
if(document.querySelector('_radiobutton_').checked) { //selecting the radio button with "SI"
document.querySelector('theTextBox').style.display = '' //selecting the textbox
}

Here is a simple example:
let chbxElement = document.getElementById('chckbx');
let textBoxElement = document.getElementById('txtbx');
chbxElement.addEventListener('change', (e) => {
textBoxElement.style.display = e.target.checked ? 'block' : 'none';
});
<input type="checkbox" id="chckbx"/>
<input type="text" id="txtbx" hidden/>

Apart from the placement of the textbox, you could add a textbox with for example an id "myInput" and a default display:none;
Then add an eventlistener to the change event. Then according to the value of the radio button show or hide the textbox.
For example:
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
var num = 1;
function accoda() {
if (document.createElement && document.getElementById && document.getElementsByTagName) {
// crea elementi
var oTr = document.createElement("TR");
var oTd1 = document.createElement("TD");
var oTd2 = document.createElement("TD");
var oField = document.createElement("INPUT");
var oButt = document.createElement("INPUT");
// setta attributi
oField.setAttribute("type", "text");
oField.setAttribute("name", "testo" + num);
oButt.setAttribute("type", "button");
oButt.setAttribute("value", "rimuovi");
// setta gestore evento
if (oButt.attachEvent) oButt.attachEvent('onclick', function(e) {
rimuovi(e);
})
else if (oButt.addEventListener) oButt.addEventListener('click', function(e) {
rimuovi(e);
}, false)
// appendi al relativo padre
oTd1.appendChild(oField);
oTd2.appendChild(oButt);
oTr.appendChild(oTd1);
oTr.appendChild(oTd2);
document.getElementById('tabella').getElementsByTagName('TBODY')[0].appendChild(oTr);
// incrementa variabile globale
num++
}
}
function rimuovi(e) {
if (document.removeChild && document.getElementById && document.getElementsByTagName) {
if (!e) e = window.event;
var srg = (e.target) ? e.target : e.srcElement;
// risali al tr del td che contiene l' elemento che ha scatenato l' evento
while (srg.tagName != "TR") {
srg = (srg.parentNode) ? srg.parentNode : srg.parentElement
}
// riferimento al tbody
var tb = document.getElementById('tabella').getElementsByTagName('TBODY')[0];
// rimuovi
tb.removeChild(srg);
}
}
//-->
</script>
</head>
<body>
<form name="modulo">
<input type="button" value="accoda" onclick="accoda()" />
<table border="1" id="tabella">
<tbody>
<tr>
<td><input type="text" name="testo0" /></td>
<td><input type="button" disabled="disabled" value="rimuovi" /></td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
<html>
<body>
<fieldset>
<strong>Vuoi inserire un affidatario?</strong>
<form action="?" method="POST" name="prova" onsubmit="return controlla();">
SI<input type="radio" name="scelta" value="si" /><br /> NO
<input type="radio" name="scelta" value="no" /><br />
<input type="text" id="myInput" style="display: none;">
<button type="submit">INVIA</button>
</form>
</fieldset>
<script language="javascript">
function controlla() {
x = document.prova;
if (x.scelta.value == "si") {
window.location.href = '../affidatario.php?idCantiere=<?php echo $idCantiere?>'
return false;
}
if (x.scelta.value == "no") {
alert("Hai risposto no");
window.location.href = '../inserimentoCantiere.php'
return false;
}
}
document.querySelectorAll('input[name="scelta"]').forEach(function(a) {
a.addEventListener("change", function() {
let textBox = document.getElementById("myInput");
if (textBox) textBox.style.display = this.value === "si" ? "block" : "none";
})
});
</script>
</body>
</html>

Related

Why is my exception handling not catching?

This is my html code that I am trying to create the exception handling for. I am trying to create the exceptions for the first form in this code.
<form id="survey" name="survey" method="post">
<div id="errorText"></div>
<fieldset class="labelfloatleft" id="contactinfo"><legend>Your Thoughts</legend>
<label for="firstname">First Name</label>
<input type="text" name="firstname" id="firstname" />
<label for="lastname">Last Name</label>
<input type="text" name="lastname" id="lastname" />
<label for="emailaddress">Email Address</label>
<input type="email" name="emailaddress" id="emailaddress"
size="30" placeholder="foryou#yahoo.com" />
</fieldset>
<fieldset><legend>Best Movie</legend>
<input type="radio" name="movie" id="horror" value="horror" checked="checked"/>
<label for="horror">The Horror</label>
<input type="radio" name="movie" id="badabing" value="badabing" />
<label for="badabing">Bada-Bing Bada-Boom</label>
<input type="radio" name="movie" id="roll" value="roll" />
<label for="roll">Roll or Die</label>
</fieldset>
<fieldset><legend>Comments</legend>
<label for="message">Your Opinion</label>
<textarea name="message" id="message" rows="7" cols="30"></textarea>
</fieldset>
<input type="submit" value="Send" class="button" id="submitBtn"/>
<input type="reset" value="Cancel" class="button" />
</form>
<h2>Welcome To Our World</h2>
<p class="very">We are a small time movie theater looking to help inspire
people who come to our theater. Our theaters come with
fresh food, cold and hot drinks, souvenirs and comfortable
seats to help make your experience worth while.
</p>
<h2>Most Popular</h2>
<ul>
<li>The Horror</li>
<li>Bada-Bing Bada-Boom</li>
<li>Roll or Die</li>
</ul>
<h2>Prices</h2>
<table title="prices">
<tr>
<th>Ticket</th>
<th>Price</th>
<th>Thursday Deal</th>
</tr>
<tr>
<td>Adult</td>
<td>$10.00</td>
<td rowspan="3">Half-Off</td>
</tr>
<tr>
<td>Child</td>
<td>$6.00</td>
</tr>
<tr>
<td>Senior</td>
<td>$8.00</td>
</table>
<form id="price" name="price" method="post">
<fieldset><legend>Ticket Quantity</legend>
<label for="adultinput">Adult 15-60
<input type="text" id="adultinput" value="1" size="2"/>
</label>
<label for="childinput">Child 1-14
<input type="text" id="childinput" value="0" size="2"/>
</label>
<label for="seniorinput">Senior 50 and up
<input type="text" id="seniorinput" value="0" size="2"/>
</label>
</fieldset>
<input type="submit" value="Calculate" id="calculate" class="button" />
<input type="reset" value="Cancel" class="button" />
</form>
This is my exception handling code that I am trying to get working. However, no matter how much I modify it, it never shows correctly. I have ran it in Chrome and have tried using a debugger to help however I am still unable to show the exceptions when I click the submit button.
"use strict";
var fnameComplete = true;
var lnameComplete = true;
var emailComplete = true;
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
var errorDiv = document.getElementById("errorText");
function verifyFname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(fname.value)) || (fname.value === "")){
fname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
fnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyLname() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(!(isNaN(lname.value)) || (lname.value === "")){
lname.style.background = "rgb(255,233,233)";
throw "Please enter your first name.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
errorDiv.style.display = "block";
lnameComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function verifyEmail() {
var validity = true;
var messageText = "";
var errorDiv = document.getElementById("errorText");
try {
if(email === "") {
email.style.background = "rgb(255,233,233)";
throw "Please enter your email.";
}
}
catch(message) {
validity = false;
messageText = message;
}
finally{
numErrorDiv.style.display = "block";
emailComplete = validity;
errorDiv.innerHTML = messageText;
}
}
function validateForm(e) {
if (e.preventDefault) {
e.preventDefault(); //prevent form from submitting
} else {
e.returnValue = false; //prevent form from submitting in IE8
}
formValidity = true; //reset value for revalidation
verifyEmail();
verifyFname();
verifyLname();
if(formValidity === true) {
document.getElementsByTagName("form")[0].submit();
}
}
function createEventListeners() {
var form = document.getElementsByTagName("form")[0];
if (form.addEventListener){
form.addEventListener("submit", validateForm, false);
} else if(form.attachEvent) {
form.attachEvent("onsubmit", validateForm);
}
}
if (window.addEventListener) {
window.addEventListener("load", createEventListeners, false);
} else if(window.attachEvent) {
window.attachEvent("onload", createEventListeners);
}
It looks like you try to access a non existing field.
Here you already get the values of the fields
var fname = document.getElementById("firstname").value;
var lname = document.getElementById("lastname").value;
var email = document.getElementById("emailaddress").value;
And in your comparisons you try to access a value field again. But you already have the plain value
if(!(isNaN(lname.value)) || (lname.value === "")){
}
Do it this way instead
if(!(isNaN(lname)) || (lname === "")){
}

Why doesn't validation work with this function?

I'm trying to validate a form (it's very simple it just have an input and a button) but my JS code doesn't work.
window.onload = iniciar;
function iniciar() {
document.getElementById("btn").addEventListener('submit', validar);
}
function validaNombre() {
var elemento = document.getElementById("nombre");
if (elemento.value = "") {
alert("por favor verifica el campo nombre");
return false;
} else {
return true;
}
}
function validar(e) {
if (validarNombre()) {
alert("Se envio el elemento");
} else {
e.preventDefault();
}
}
<form action="" method="GET" id="miForm">
<br>
<label>Name*</label><br>
<input type="text" class="b1" id="nombre" maxlength="32" name="name">
<br><br><br>
<input type="submit" id="btn" value="Registrar">
<br>
</form>
The submit event goes with the form, not the button.
You also had a typo in the function name validaNombre. And you have to use == to compare, not =.
window.onload = iniciar;
function iniciar() {
document.getElementById("miForm").addEventListener('submit', validar);
}
function validarNombre() {
var elemento = document.getElementById("nombre");
if (elemento.value == "") {
alert("por favor verifica el campo nombre");
return false;
} else {
return true;
}
}
function validar(e) {
if (validarNombre()) {
alert("Se envio el elemento");
} else {
e.preventDefault();
}
}
<form action="" method="GET" id="miForm">
<br>
<label>Name*</label><br>
<input type="text" class="b1" id="nombre" maxlength="32" name="name">
<br><br><br>
<input type="submit" id="btn" value="Registrar">
<br>
</form>

registration form validation using javascript

Im partly there but it would be helpful if any of you guys could send the entire code .
1) Create a form with the below given fields and validate the same using javascript or jquery.
Name : Text box- mandatory
Gender : Radio Button
Age : Text box - Accept Number only - (check for valid Age criteria)
Email : Text box -  should be in format example#gmail.com
Website : Text box -  should be in format http://www.example.com
Country : Select box with 10 countries
Mobile :  Text box - should be a 10 digit number - Display this field only after the user selects a country
Social Media Accounts : Facebook, Google, Twitter (3 checkboxes) - Display Social media section only if selected Country is India
I agree the Terms and Conditions - Checkbox
All fields are mandatory and show error messages for all fields(if not valid)
Only allow to submit form after checking the 'I agree' checkbox.
<!DOCTYPE html>
<html>
<head>
<title>Get Values Of Form Elements Using jQuery</title>
<!-- Include CSS File Here -->
<link rel="stylesheet" href="form_value.css"/>
<!-- Include JS File Here -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="form_value.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#social").hide() ;
// $("#hide").click(function(){
// $("social").hide();
// });
// var country = document.getElementByName("country")[0].value;
// if (country.value == "India") {
// $("#show").click(function(){
//     $("social").show();
// });
// }
if (!(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/).test(document.email_id.value)) {
alert("You have entered an invalid email address!")
return (false)
}
});
</script>
</head>
<body onload="disableSubmit()">
<div class="container">
<div class="main">
<h2>Get Values Of Form Elements Using jQuery</h2>
<form action="">
<!-- Text -->
<br>
<br>
<label>Name :</label>
<input type="text" id="text" name="name" value=""required/><br>
<!-- Radio Button -->
<br><br><br>
<label>Gender:</label>
<input type="radio" name="male" value="Male">Male
<input type="radio" name="female" value="Female">Female
<br><br>
<!-- Textarea -->
<label>Email :</label>
<input type="text" id="Email" value="" id="Email"/>
<br>
<br><br>
Age: <input type="text" id="Age" onkeypress="return IsNumeric(event);" ondrop="return false;" onpaste="return false;" />
<span id="error" style="color: Red; display: none">* Input digits (0 - 9)</span>
<br><br>
<label> Website:</label>
<input type="text" id="text" value="" name = "Website" id="website" />
<script type="text/javascript">
function validate() {
if(Website.value.length==0)
{
document.getElementById("Website").innerHTML="Should be in the format http://www.example.com ";
}
}
</script>
<br><br>
<label>Country:</label>
<select class="country" id = "country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
<option value="uae">United Arab Emirates</option>
<option value="germany">Germany</option>
<option value="france">France</option>
<option value="netherlands">Netherlands</option>
<option value="yemen">Yemen</option>
<option value="pakistan">Pakistan</option>
<option value="russia">Russia</option>
</select>
<br><br>
<label>Mobile:</label>
<input type="text" id="phone" name="phone" onkeypress="phoneno()" maxlength="10">
<script type="text/javascript">
function phoneno(){
$('#phone').keypress(function(e) {
var a = [];
var k = e.which;
for (i = 48; i < 58; i++)
a.push(i);
if (!(a.indexOf(k)>=0))
e.preventDefault();
});
}
</script>
<br><br>
<div id = "social" >
<p>Social Media Accounts.</p> <input type="checkbox" id="Facebook" value="Facebook"><label for="Facebook"> Facebook</label><br> <input type="checkbox" id="Google" value="Google"><label for="Google"> CSS</label><br> <input type="checkbox" id="Twitter" value="Twitter"><label for="Twitter"> Twitter</label><br>
</div>
<br>
<br>
<script>
function disableSubmit() {
document.getElementById("submit").disabled = true;
}
function activateButton(element) {
if(element.checked) {
document.getElementById("submit").disabled = false;
}
else {
document.getElementById("submit").disabled = true;
}
}
</script>
<input type="checkbox" name="terms" id="terms" onchange="activateButton(this)"> I Agree Terms & Coditions
<br><br>
<input type="submit" name="submit" id="submit">
</script>
</form>
</div>
</body>
</html>
this is my js page content form_value.js
$(document).ready(function() {
// Function to get input value.
$('#text_value').click(function() {
var text_value = $("#text").val();
if(text_value=='') {
alert("Enter Some Text In Input Field");
}else{
alert(text_value);
}
});
// Funtion to get checked radio's value.
$('#gender_value').click(function() {
$('#result').empty();
var value = $("form input[type='gender']:checked").val();
if($("form input[type='gender']").is(':checked')) {
$('#result').append("Checked Radio Button Value is :<span> "+ value +" </span>");
}else{
alert(" Please Select any Option ");
}
});
// Get value Onchange radio function.
$('input:gender').change(function(){
var value = $("form input[type='gender']:checked").val();
alert("Value of Changed Radio is : " +value);
});
// Funtion to reset or clear selection.
$('#radio_reset').click(function() {
$('#result').empty();
$("input:radio").attr("checked", false);
});
$('#Email').click(function() {
function validate(Email) {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za- z]{2,4})$/;
//var address = document.getElementById[email].value;
if (reg.test(email) == false)
{
alert('Should be in the format example#gmail.com');
return (false);
}
}
});
});
$("#Age").click(function() {
var specialKeys = new Array();
specialKeys.push(8); //Backspace
function IsNumeric(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
function handleChange(input) {
if (input.value < 0) input.value = 0;
if (input.value > 100) input.value = 100;
}
});
</script>
<!DOCTYPE html> <html> <head> <script> function validateForm() {
var name = document.forms["myForm"]["fname"].value;
var gender = document.forms["myForm"]["gender"].value;
var age = document.forms["myForm"]["age"].value;
var a = parseInt(age);
var email = document.forms["myForm"]["email"].value;
var url = document.forms["myForm"]["website"].value;
var country = document.forms["myForm"]["country"].value;
var mobileCountry = document.forms["myForm"]["mobileCountry"].value;
var mcLength = mobileCountry.length;
if (name == "") {
alert("Name Field is mandatory");
return false;
}
if (gender != "male" && gender != "female") {
alert("Atleast one Gender has to be chosen");
return false;
}
if(isNaN(a)){
alert("Age is compulsory and must be a number");
return false;
}
if(email == ""){
alert("Email address is required");
}
else if(/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(email)){
} else{
alert("Email address entered is invalid");
return false;
}
if(/^(ftp|http|https):\/\/[^ "]+$/.test(url)){
} else{
alert("Website url entered is invalid");
return false;
}
if(country != "choose"){
document.getElementById("mc").style.display = "block";
} else{
document.getElementById("mc").style.display = "none";
}
if(mcLength != 10){
alert("Number must be ten digits");
return false;
}
} function displaySocial(){ var social =
document.getElementById("social");
var mc = document.getElementById("mobileCountry");
var country = document.getElementById("country");
var selectedValue = country.options[country.selectedIndex].value;
if (selectedValue != "choose") {
if(selectedValue == "india"){
if(social.style.display = "none"){
social.style.display = "block";
} else{
social.style.display = "none";
} } else{
social.style.display = "none"; }
if(mc.style.display = "none"){
mc.style.display = "block";
} else{
mc.style.display = "none"; } } else{
mc.style.display = "none"; }
} </script> </head> <body> <form name="myForm" action="/action_page_post.php" onsubmit="return validateForm()" method="post"> Name: <input type="text" name="fname"><br> Gender: <input type="radio" name="gender" value="male"> Male <input type="radio" value="female" name="gender"> Female <br> age: <input type="text" name="age"><br> email: <input type="text" name="email"><br> website: <input type="text" name="website"><br> country: <select type="text" name="country" id="country" onclick="displaySocial()"><option value="choose">--choose--</option><option value="usa">USA</option><option value="uk">UK</option><option value="ng">Nigeria</option><option value="india">India</option></select><br> <span id="mobileCountry" style="display: none;">mobile country: <input type="text" name="mobileCountry"><br></span> <span id="social" style="display: none;">Social Media: <input type="radio" name="gender"> Facebook <input type="radio" name="gender"> Google <input type="radio" name="gender"> Twitter</span> <br> <p> <input type="submit" value="Submit"> </form> <p id="error"></p> </body> </html>

Using Buttons in JavaScript

How can you create a button so that whenever you click on it a question changes to its uppercase form, then when you click the button again it changes to its lowercase form. I believe I should create a function of some sort, just not sure how. Below is what I have tried so far:
function upper_lower() {
if (windows.document.f1.value=="lower") {
windows.document.value = "UPPER"
windows.document.question = windows.document.question.toUpperCase();
windows.document.queston.size="40"
} else {
windows.document.value = "lower"
windows.document.question = windows.document.question.toLowerCase()
windows.document.queston.size="30"
}
}
Question
<input type="text" name="question" value="Favorite food?" size="25">
readonly /input
<input type="button" name="f1" value="UPPER" onClick = "upper_lower">
Try this
Html:
Question <input type="text" name="question" id="question1" value="Favorite food?" size="25" readonly></input>
<input type="button" name="f1" id="button1" value="UPPER" onClick="upper_lower()"></input>
js:
var toggle = true;
function upper_lower(){
var question = document.getElementById('question1'),
button = document.getElementById('button1');
if(toggle){
question.value = question.value.toUpperCase();
button.value = 'LOWER';
toggle = false;
} else{
question.value = question.value.toLowerCase();
button.value = 'UPPER';
toggle = true;
}
}
Snippet below (indented weird for some reason)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
</head>
<body>
Question <input type="text" name="question" id="question1" value="Favorite food?" size="25" readonly></input>
<input type="button" name="f1" id="button1" value="UPPER" onClick="upper_lower()"></input>
</body>
<script>
var toggle = true;
function upper_lower(){
var question = document.getElementById('question1'),
button = document.getElementById('button1');
if(toggle){
question.value = question.value.toUpperCase();
button.value = 'LOWER';
toggle = false;
} else{
question.value = question.value.toLowerCase();
button.value = 'UPPER';
toggle = true;
}
}
</script>
</html>
Try This Updated Code...
<script type="text/javascript">
var flag = 0;
function changecase() {
if (flag == 0) {
document.form1.instring.value = document.form1.instring.value.toUpperCase();
document.form1.Convert.value = 'To Lower'
flag = 1;
}
else
{
document.form1.instring.value = document.form1.instring.value.toLowerCase();
document.form1.Convert.value = 'To Upper'
flag = 0;
}
}
</script>
<form name="form1" method="post">
<input name="instring" type="text" value="this is the text string" size="30">
<input type="button" name="Convert" value="To Upper " onclick="changecase();">
</form>

How can I do live validation for radio button on click event just like we do for textbox on keyup event?

I want to know how can i live validate radio button like text box on click event or on key up or press event? Like textbox, when we start typing and if it passes validation, then error message is gone; in the same way i want to implement this functionality for radio button. I have the following code which works only for textbox on keyup event and not for radio buttons -
HTML -
<form name="form1" id="form1" method="post" action="">
<table border="0" align="center" width="50%" cellpadding="5">
<tr>
<th align="right" valign="top"><label for="txtemail">Email ID:</label></th>
<td>
<input type="text" name="txtemail" id="txtemail" size="30" onKeyUp="return isValid();" />
<span id="erremail"></span>
</td>
</tr>
<tr>
<th align="right" valign="top"><label>Gender:</label></th>
<td>
<input type="radio" name="gender" id="radmale" value="Male" onClick="this.checked; return isValid();" />
<label for="radmale">Male</label>
<input type="radio" name="gender" id="radfemale" value="Female" onClick="return isValid();" />
<label for="radfemale">Female</label>
<span id="errgender"></span>
</td>
</tr>
<tr>
<td align="right">
<input type="submit" name="btnsubmit" value="Register" onClick="return isValid();">
</td>
<td>
<input type="reset" value="Clear Form">
</td>
</tr>
</table>
</form>
JavaScript -
<script type="text/javascript">
var flag;
function isValid()
{
flag = true;
reqdField("txtemail", "erremail", "Email ID is empty");
isValidEmail("txtemail", "erremail", "Email ID is not valid", /^[a-z0-9_.-]+#[a-z-.]+\.[a-z.]{2,5}$/);
checkGender("radmale", "radfemale", "errgender", "Select your gender");
return flag;
}
// checking all required fields
function reqdField(ctrid, errid, errmsg)
{
var str = document.getElementById(ctrid).value;
if(str.length == 0)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
// checking is email id valid
function isValidEmail(ctrid, errid, errmsg, validExp)
{
var email = document.getElementById(ctrid).value;
if(email.match(validExp) == null)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
// checking is gender selected
function checkGender(ctrid1, ctrid2, errid, errmsg)
{
var male = document.getElementById(ctrid1);
var female = document.getElementById(ctrid2);
if(male.checked == false && female.checked == false)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
}
}
</script>
Another issue I am facing in this code is regarding reqdField() function. This function does work and only isValidEmail() runs. I only see email is not valid when it is left empty and can not display email id is empty. How can i achieve the same?
Here is the demo JSFiddle
<script type="text/javascript">
var flag;
function isValid()
{
flag = true;
reqdField("txtemail", "erremail", "Email ID is empty");
isValidEmail("txtemail", "erremail", "Email ID is not valid", /^[a-z0-9_.-]+#[a-z-.]+\.[a-z.]{2,5}$/);
checkGender();
return flag;
}
// checking all required fields
function reqdField(ctrid, errid, errmsg)
{
var str = document.getElementById(ctrid).value;
if(str.length == 0)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
flag = true;
}
}
// checking is email id valid
function isValidEmail(ctrid, errid, errmsg, validExp)
{
var email = document.getElementById(ctrid).value;
if(email.length == 0){
return;
}else{
if(email.match(validExp) == null)
{
document.getElementById(errid).innerHTML = errmsg;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
flag = true;
}
}
}
// checking is gender selected
function checkGender()
{
var ctrid1="radmale", ctrid2="radfemale", errid="errgender", errmsg="Select your gender"
var male = document.getElementById(ctrid1);
var female = document.getElementById(ctrid2);
if(male.checked == false && female.checked == false)
{
document.getElementById(errid).innerHTML = errmsg;
return false;
flag = false;
}
else
{
document.getElementById(errid).innerHTML = "";
return true;
}
}
</script>
and html is
<form name="form1" id="form1" method="post" action="">
<table border="0" align="center" width="50%" cellpadding="5">
<tr>
<th align="right" valign="top"><label for="txtemail">Email ID:</label></th>
<td><input type="text" name="txtemail" id="txtemail" size="30" onKeyUp="return isValid();" />
<span id="erremail"></span>
</td>
</tr>
<tr>
<th align="right" valign="top"><label>Gender:</label></th>
<td><input type="radio" name="gender" id="radmale" value="Male" onClick="return checkGender();" /><label for="radmale">Male</label>
<input type="radio" name="gender" id="radfemale" value="Female" onClick="return checkGender();" /><label for="radfemale">Female</label>
<span id="errgender"></span>
</td>
</tr>
<tr>
<td align="right"><input type="submit" name="btnsubmit" value="Register" onClick="return isValid();"></td>
<td><input type="reset" value="Clear Form"></td>
</tr>
</table>
</form>
Fiddle
$("input[type=radio]").click(function(){
var set = $(this).attr("name");
validateRadioSet(set);
});

Categories