Javascript to show content if checkbox is checked - javascript

In this Fiddle I have made script that should show the form if the checkbox is checked but I can't make it work. It says that the function is unknown variable.
Html
<input type="checkbox" id="_My.notFinal" onclick='toggleCheckbox();'>
<label>
<b>Buying for someone else.</b>
</label>
<span id="LicenseCustomer" style="display:none">/*some form*/</span>
And javascript
function toggleCheckbox() {
var lfckv = document.getElementById("_My.notFinal").checked;
if (lfckv) {
document.getElementById("LicenseCustomer").style.display = "block";
} else {
document.getElementById("LicenseCustomer").style.display = "none";
}
}
https://jsfiddle.net/00gckvxw/1/

Here it is the corrected version https://jsfiddle.net/00gckvxw/24/.
document.getElementById("_My.notFinal").onclick = toggleCheckbox;
It has to do with when the events are attached. check this out: testing a function in jsfiddle.
I also changed the span to div and class attribute to id. I wouldn't recommend using <tr> inside a <div> or <span>, better use id on <tr> directly or use <tbody> if you have multiple lines.

I think you missed out to include the Javascript file in your in html, because it is not able to find the function toggleCheckbox on click of checkbox. Also
Also span element has class = 'LicenseCustomer', change this to id='LicenseCustomer'
try including inline script
<script>
function toggleCheckbox() {
var lfckv = document.getElementById("_My.notFinal").checked;
console.log(lfckv);
if (lfckv) {
document.getElementById("LicenseCustomer").style.display = "block";
} else {
document.getElementById("LicenseCustomer").style.display = "none";
}
}
</script>
<input type="checkbox" id="_My.notFinal" onclick='toggleCheckbox();'>
<label><b>Buying for someone else.</b>
<label>
<span id="LicenseCustomer" style="display:none">
<tr valign=middle>
<td class="bodycopy" align=right width=160><b>License Contact:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseContact" type="text" class="inputBox" size="32" _label="<br>License Contact"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License E-mail Address:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseEmail" type="text" class="inputBox" size="32" _label="<br> License E-mail Address"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License Phone:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicensePhone" type="text" class="inputBox" size="32" _label="<br> License Phone"></td>
</tr>
</span>

corrected version:
http://pastebin.com/RrMD78AG
Few mistakes i want to tell you:-
first you are using class="LicenseCustomer" and you are using document.getElementById selector (it cannot get element with class name).
second you are using onclick="toggleCheckbox();", when you calling function you does not have to use 'semicolon' at the end of a function name (its an incorrect syntax) - onclick="toggleCheckbox()" (no semicolon).

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input type="checkbox" id="_My.notFinal" class='checkbox'>
<label><b>Buying for someone else.</b>
</label>
<span class="LicenseCustomer" style="display:none">
<tr valign=middle>
<td class="bodycopy" align=right width=160><b>License Contact:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseContact" type="text" class="inputBox" size="32" _label="<br>License Contact"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License E-mail Address:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicenseEmail" type="text" class="inputBox" size="32" _label="<br> License E-mail Address"></td>
</tr>
<tr valign=middle>
<td class="bodycopy" align=right><b> License Phone:</b> </td>
<td class="smallcopy" nowrap><input name="_My.LicensePhone" type="text" class="inputBox" size="32" _label="<br> License Phone"></td>
</tr>
</span>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</body>
</html>
Below is the Javascript
$(document).ready(function()
{
$(".checkbox").change(function() {
if(this.checked)
{
$(".LicenseCustomer").css('display','block');
}
else
{
$(".LicenseCustomer").css('display','none');
}
})
});
Demo : https://jsbin.com/bowicivupa/edit?html,js,console,output

Try to something like this.
function toggleCheckbox(){
var lfckv = document.getElementById('myCheck').checked;
if(lfckv){
document.getElementsByTagName("span")[0].setAttribute("style", "display:none");
} else {
document.getElementsByTagName("span")[0].setAttribute("style", "display:block");
}
}

Related

Javascript to get the text of checked checkboxes

How can I get the checked checkboxes using JavaScript for the following HTML.
All my check boxes will have id's as follows as shown in the HTML
SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0
SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1
// ... and so on, up to
SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_n
I tried with the following code
var IDtoFind="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_"
var txts = document.getElementsByTagName('input');
for (var i = 0; i < txts.length; ++i) {
if (txts[i].name.indexOf(IDtoFind)!=-1) {
if(txts[i].checked){ alert(txts[i].id); }
// targetId = txts[i].id;
}
}
But its not working . Ineed to get the text of the checkbox labels
<table id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceTable" cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td>
<span class="ms-RadioText" title="NO SECURITY ISSUE Observed">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0">NO SECURITY ISSUE Observed</label>
</span>
</td>
</tr>
<tr>
<td>
<span class="ms-RadioText" title="Staff NOT wearing identification / name badge">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1" type="checkbox">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1">Staff NOT wearing identification / name badge</label>
</span>
</td>
</tr>
</tbody>
</table>
You can use the nextelementsibling property like
function get() {
var inputs = document.querySelectorAll('input[type="checkbox"][id^="SECURITY_"]'),
labels = [];
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
labels.push(inputs[i].nextElementSibling.innerHTML.trim())
}
}
alert(labels)
}
<table id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceTable" cellpadding="0" cellspacing="1">
<tbody>
<tr>
<td>
<span class="ms-RadioText" title="NO SECURITY ISSUE Observed">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0">NO SECURITY ISSUE Observed</label>
</span>
</td>
</tr>
<tr>
<td>
<span class="ms-RadioText" title="Staff NOT wearing identification / name badge">
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1" type="checkbox">
<label for="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_1">Staff NOT wearing identification / name badge</label>
</span>
</td>
</tr>
</tbody>
</table>
<button onclick="get()">Get</button>
Note: You can simplify the checkbox selector, if you can add a class to those checkboxes
<input id="SECURITY_6ab5ce28-f328-4096-91c1-db49a5007d0c_MultiChoiceOption_0" type="checkbox" checked="checked" class="security-multichoiceoption"/>
then
inputs = document.getElementsByClassName('security-multichoiceoption')
here
i made a demo which returns an array of maching objects you can simply reach elements by using those function there it returns an array so those()[0].id will simply return the id of first selected element

Java Script Form Validation

I am building adding JavaScript validation to my sign in form, i can successfully validate the username against certain criteria, however i am struggling to validate the password input. Any help would be greatly appreciated. Many Thanks.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>An AJAX Username Verification Tool</TITLE>
<META NAME="Keywords" CONTENT="form, username, checker">
<META NAME="Description" CONTENT="An AJAX Username Verification Script">
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css" />
<SCRIPT type="text/javascript">
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#username").change(function() {
var usr = $("#username").val();
if(usr.length <= 4)
{
$("#status").html('<font color="red">The username should have more than <strong>4</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else if(usr.length >= 14)
{
$("#status").html('<font color="red">The username not be longer than <strong>14</strong> characters.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else if(usr.indexOf('#') === -1 )
{
$("#status").html('<font color="red">Please insert correct <strong>Email</strong> format.</font>');
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
}
else
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check.php",
data: "username="+ usr,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#username").removeClass('object_error'); // if necessary
$("#username").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#username").removeClass('object_ok'); // if necessary
$("#username").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
});
// HERE IS WHERE I AM HAVING THE PROBLEMS
$("#password").change(function() {
var pass = $("#password").val();
if(pass.length <= 4){
$("#status2").html('<font color="red">The username should have more than <strong>4</strong> characters.</font>');
$("#password").removeClass('object_ok'); // if necessary
$("#password").addClass("object_error");
}
});
// END OF PROBLEM
});
</SCRIPT>
</HEAD>
<BODY>
<center>
<div align="center">
<h2 align="center">AJAX Username Verification</h2>
<form>
<table width="700" border="0">
<tr>
<td width="200"><div align="right">Username: </div></td>
<td width="100"><input id="username" size="20" type="text" name="username"></td>
<td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td width="200"><div align="right">Password: </div></td>
<td width="100"><input size="20" type="text" name="password"></td>
<td width="400" align="left"><div id="status2"></div></td>
</tr>
<tr>
<td width="200"><div align="right">Confirm Password: </div></td>
<td width="100"><input size="20" type="text" name="confirm_password"></td>
<td width="400" align="left"><div id="status3"></div></td>
</tr>
</table>
</form>
</div>
</center>
</BODY>
</HTML>
You haven't placed the id on password field.
<td width="100"><input size="20" type="text" name="password"></td> this should be like
<td width="100"><input size="20" type="text" id="password"></td>
So you can replace your <tr> with this
<tr>
<td width="200"><div align="right">Password: </div></td>
<td width="100"><input size="20" type="text" name="password" id="password"></td>
<td width="400" align="left"><div id="status2"></div></td>
</tr>
At first, you must assign id "password" to your input, then JQUERY will can to find this input. And, I think, it much better to change attribute "type" to "password" for password inputs:
<input size="20" type="password" name="password" id="password"/>

Jsfiddle code not working in localhost wamp

i have implemented validation for fundtransfer in jsfiddle.
it works fine in jsfiddle but not working in localhost.
i am using wamp.
here is my jsfiddle link - http://jsfiddle.net/BzdfN/31/
but when i am implementing this in localhost.its not working.
my html code is
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="validate.js"></script>
<title> Infy Bank Fund Transfer Entry Page </title>
</head>
<body>
<table class="layout" border="0" width="90%" align="center">
<form name="addcust" method ="POST" action ="http://localhost:8080/myapp/jsp/AddCustomerJSP.jsp">
<td colspan="2">
<table border="0" width="70%" align="center">
<tr>
<td align="center" colspan="2">
<div class="heading2">Infy Bank</div>
</td>
</tr>
<tr>
<td align="center" colspan="2"><p class="heading3">Fund transfer</p></td>
</tr>
<tr>
</tr>
<tr>
</tr>
<tr>
<td>Payers account no<span class="mandatory">*</span></td>
<td><input type="text" name="text10" id="text10" size="25" />
<div width="100%" id="equal"></div>
</td>
</tr>
<!--<tr>
<td>Payees account no<span class="mandatory">*</span></td>
<td>
<input type="text" name="name" value=2008 maxlength="25">
</td>
</tr>
<tr>
<td>Amount<span class="mandatory">*</span></td><td><input type="text" Value=500 name="state" maxlength="25"></td>
</tr>
<tr>
<td>Description<span class="mandatory">*</span></td><td><input type="text" name="pin" value=self maxlength="6"></td>
</tr>
<tr>
<td><span class="mandatory">*mandatory field</span></td>
<td><input type="submit" name="AccSubmit" value="Submit" onClick="return validatebal();">
<input type="reset" name="res" value="Reset"></td>
</tr>-->
</form>
</table>
<p align="right">Home</p>
</body>
</html>
and my validate.js is
$("#text10").keyup(function(){
$("#text10").blur();
$("#text10").focus();
});
$("#text10").change(function(){
var name = $('#text10').val();
var numbers = /^[0-9]+$/;
var specialChars = "<>#!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";
if (name == "" || name == " " )
{
$("#equal").show();
$("#equal a").html("please enter account number");
}
else if(name.match(numbers))
{
$("#equal").hide();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else if(name.match(specialChars))
{
$("#equal").show();
$("#equal a").html("correct account number"); // alert('All Boxes have elements.');
}
else
{
$("#equal").show();
$("#equal a").html("please check your account number correctly");
}
});
So guys can you what i am doing wrong.
please help
start your jQuery with:
$( document ).ready(function() {
.../ and end with:
});
maybe this will solve your problem
In jsfFiddle your code is executed on the onload event.
But with including validate.js in the head the content of the script is execute right at the place where you placed <script src="validate.js"></script>. So your jQuery selectors don't find any elements, because they are not in the DOM at the time the script is executed.
You have different possibilities.
Wrap the content of your validate.js into jQuery(function() { /*your code of validate.js **/ })
Another possibility is to place <script src="validate.js"></script> at the end of your document instead placing it in the head.
You can use delegated events like $(document).on("keyup","#text10", function() { /* .... */ }); that way it does not matter if #text10 is in the DOM at this time.
wrap your validate.js code in jQuery ready function as follows should solve the issue:
$(document).ready(function() {
// validate.js code
});

JavaScript checking & adding text to a table dynamically on submit button click

Basically my HTML looks like this:
<form method="post" name="htmlform" onsubmit = "checkFields()">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" size="30" maxlength="50"/>
/td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio" name="sex"
value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
When the form is submitted, the onsubmit() event checks if first_name textfield is blank, if it is then the label or span to its left is appended to output "first name*" + " you must enter a first name" and similarly for last name and sex.
The problem is that the text in the table does not update with appendchild. When I enclosed the statement in an alert for debugging the message is appended then disappears.
The JavaScript code is below for the onsubmit = "checkFields()".
function checkFields() {
var firstName = document.getElementById("first_name").value;
var lastName = document.getElementById("last_name").value;
if (firstName == "") {
//<span style='color:red'> Please enter a first name </span>
var nameHint = " Please enter a first name";
var node = document.getElementById("firstNameSpan");
//alert(node.appendChild(document.createTextNode(nameHint)) );
//not working
node.appendChild(document.createTextNode(nameHint));
} if (lastName == "") {
//additional code
}
}
Thanks in advance, your help is much appreciated. Also are there any JavaScript debuggers?
Regards
David D
I believe your sample code is not working due to incorrect html. document.getElementById("last_name") will return undefined.
http://jsfiddle.net/5E6my/1/
Thanks all, Im getting the ropes of JFiddle the split screen is very useful although the error messages are not useful for debugging. Here is the completed code (1) HTML (2) JavaScript.
<form method="post" name="htmlform" onsubmit="return checkFields();">
<table style="width: 479px;" border="30" cellspacing="3" cellpadding="10">
<tbody>
<tr>
<td valign="top"><span id="firstNameSpan" >First Name *</span></td>
<td valign="top"><input type="text" name="first_name" id="first_name"
size="30" maxlength="50" /></td>
</tr>
<tr>
<td valign="top"><span id = "lastNameSpan" >Last Name *</span></td>
<td valign="top"><input type="text" name="last_name" id="last_name" size="30"
maxlength="50" /></td>
</tr>
<tr>
<td style="text-align: center;" colspan="2" id = "sexMessage">
Please select Male or Female*</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="radio"
name="sex" value="male" /> Male <input type="radio" name="sex"
value="female" /> Female</td>
</tr>
<tr>
<td style="text-align: center;" colspan="2"><input type="submit" value="submit"
/></td>
</tr>
</tbody>
</table>
</form>
The JavaScript code to react to the onsubmit button's unfilled fields in the form are: (any ways to make this code simpler??)
window.checkFields = function()
{
var firstName = document.getElementById("first_name");
var lastName = document.getElementById("last_name");
if(firstName.value == "")
{
//<span style='color:red'> Please enter a first name </span>
var nameHint = " *Please enter a first name ";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="red";
} else{
var nameHint = " First Name *";
var fnNode = document.getElementById("firstNameSpan");
while(fnNode.firstChild)
{
fnNode.removeChild(fnNode.firstChild)
}
fnNode.appendChild(document.createTextNode(nameHint));
fnNode.style.color="black";
}
if (lastName.value == "")
{
//additional code
var nameHint = " *Please enter a last name";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="red";
} else{
var nameHint = " Last Name *";
var lnNode = document.getElementById("lastNameSpan");
while(lnNode.firstChild)
{
lnNode.removeChild(lnNode.firstChild)
}
lnNode.appendChild(document.createTextNode(nameHint));
lnNode.style.color="black";
}
var radios = document.getElementsByName("sex");
var radioValue = ""
for(var i=0; i<radios.length; i++)
{
if(radios[i].checked)
{
radioValue = radios[i].value;
}
}
if(radioValue === "")
{
var sexNode = document.getElementById("sexMessage");
var nameHint = "*You did not choose a sex";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="red";
} else {
var sexNode = document.getElementById("sexMessage");
var nameHint = "Please select Male or Female*";
while(sexNode.firstChild)
{
sexNode.removeChild(sexNode.firstChild);
}
sexNode.appendChild(document.createTextNode(nameHint));
sexNode.style.color="black";
}
return false;
}
The trick is to use as Yury suggested was the onsubmit="return checkfields()" and then in the code block to use window.checkFields = function() { etc.
One question that I have... is JQuery a lot simpler to use, im learning JavaScript before JQuery... should I skip to JQUery instead. Also does JQuery support the AJAX framework?
Much appreciated
David

jQuery not detach()'ing if it contains an input tag

I have a table which i need to move elements up and down in. I have the code working, but as soon as I add a tag to it, it throws the error:
Error: this.visualElement is undefined
Source File: http://192.9.199.11:83/templates/admin/js/jquery/ui.checkbox.js
Line: 94
The HTML looks like this:
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<th>Menu</th>
<td>Builds the main navigation menu panel</td>
<td width="80px">
<input type="hidden" class="hiddenData" name="" value="1" />
</td>
</tr>
<tr>
<th>Proudly Support</th>
<td>A widget which displays company's we proudly support</td>
<td width="80px">
<input type="hidden" class="hiddenData" name="" value="2" />
</td>
</tr>
</table>
And the jQuery is as follows:
$(".arrowButtons").live('click', function(e) {
e.preventDefault();
});
$(".upArrow").live('click', function(e) {
var element = $(this).parent().parent();
if(element.prev().html() != null)
{
var elementContents = element.html();
$("<tr>"+elementContents+"</tr>").insertBefore(element.prev());
element.remove();
}
});
Any idea on why that could be happening?
I just commented out the lines that were causing the problem in ui.checkbox.js and it is working. Will do proper testing, but so far everything seems to be working.

Categories

Resources