Displaying a name using Javascript - javascript

Am new to javascript and doing my student project. I have created a sample page where user enters the name of a place..
He can enter a maximum of 4 places.. I Just like to have a text of "Place A" on the top when user is entering 1st place and when he clicks on "Add Another Place" then "Place B" needs to be displayed to enter text and same like "Place C" and "Place D".
Here is my code
var i = 0;
function isNumericKey(e) {
if (window.event) {
var charCode = window.event.keyCode;
} else if (e) {
var charCode = e.which;
} else {
return true;
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function add() {
var a = document.getElementById("ad").value;
// alert('Please Enter Details');
if (a != 'null' || a != '') {
i++;
if (i == 1) {
//document.getElementById("input").reset();
document.getElementById("Place1").style.display = "none";
document.getElementById("Place2").style.display = "block";
document.getElementById("Place2").required = true;
document.getElementById("Place3").style.display = "none";
document.getElementById("Place4").style.display = "none";
} else if (i == 2) {
//document.getElementById("input").reset();
document.getElementById("Place1").style.display = "none";
document.getElementById("Place2").style.display = "none";
document.getElementById("Place3").style.display = "block";
document.getElementById("Place3").required = true;
document.getElementById("Place4").style.display = "none";
} else if (i == 3) {
//document.getElementById("input").reset();
document.getElementById("Place1").style.display = "none";
document.getElementById("Place2").style.display = "none";
document.getElementById("Place3").style.display = "none";
document.getElementById("Place4").style.display = "block";
document.getElementById("Place4").required = true;
document.getElementById("ad").style.display = "none";
}
}
}
<form action="abc.php" method="post">
<table width="600" ;>
<tr>
<td><font size=4px><label>Place</label></font>
<br>
<br>
</td>
<td>
<input type="text" name="Place1" id="Place1" value="" style="display:block; width: 20vw;height:30px;font-size:14pt;" onkeypress="return isNumericKey(event);" required="true" />
<br>
</td>
<td>
<input type="text" name="Place2" id="Place2" value="" style="display:none; width: 20vw;height:30px;font-size:14pt;" onkeypress="return isNumericKey(event);" />
<br>
</td>
<td>
<input type="text" name="Place3" id="Place3" value="" style="display:none; width: 20vw;height:30px;font-size:14pt;" onkeypress="return isNumericKey(event);" />
<br>
</td>
<td>
<input type="text" name="Place4" id="Place4" value="" style="display:none; width: 20vw;height:30px;font-size:14pt;" onkeypress="return isNumericKey(event);" />
<br>
</td>
</tr>
<td>
<input type="button" name="Add Another place" id="ad" value="Add Another place" onclick="add();" style="display: block;
height: 25px;
width: 175px;
border-radius: 25px;
background-color: #008CBA;
color: #fff;
border: #008CBA;
cursor: pointer;" />
Let me know how to do this..

There are lots of syntax error in your HTML code, anyways beside that the solution to your problem is quite simple. I have written the following script to acquire the functionality required
<script type="text/javascript">
var i = 1;
function add() {
if (i == 1)
{
document.getElementById("Place1").style.display = "none";
document.getElementById("Place2").style.display = "block";
i++;
}
else if(i==2)
{
document.getElementById("Place2").style.display = "none";
document.getElementById("Place3").style.display = "block";
i++;
}
else if (i == 3) {
document.getElementById("Place3").style.display = "none";
document.getElementById("Place4").style.display = "block";
document.getElementById("ad").style.display = "none";
}
}
</script>
And below is my HTML code
<table>
<tr>
<td><label>Place</label></td>
<td><input type="text" name="Place1" id="Place1" value="" style="display:block; width: 20px;height:30px;font-size:14pt;" placeholder="place1"/></td>
<td><input type="text" name="Place2" id="Place2" value="" style="display:none; width: 20px;height:30px;font-size:14pt;" placeholder="place2" /></td>
<td><input type="text" name="Place3" id="Place3" value="" style="display:none; width: 20px;height:30px;font-size:14pt;" placeholder="place3" /></td>
<td><input type="text" name="Place4" id="Place4" value="" style="display:none; width: 20px;height:30px;font-size:14pt;" placeholder="place4" /></td>
</tr>
<tr>
<td><input type="button" name="Add Another place" id="ad" value="Add Another place" onclick="add();" /></td>
</tr>

Something like that ???
var MAX_PLACES = 4;
var currentEditPlace = 0;
function editPlace(index)
{
var places = document.getElementById('places');
var place = places.getElementsByTagName("li")[index];
place.style.display = 'block';
var span = place.getElementsByTagName("span")[0];
var input = document.createElement('input');
input.setAttribute("type", "text");
input.setAttribute("value", "");
span.appendChild(input)
/** Return key => show next place */
input.onkeydown = function(e) {
/** Validation */
if (this.value != "" && e.keyCode == 13) {
addNewPlace();
}
}
/** Auto focus new input */
input.focus();
}
function addNewPlace() {
if (currentEditPlace+1 < MAX_PLACES) {
currentEditPlace++;
editPlace(currentEditPlace);
}
}
/** Start editing place A */
editPlace(currentEditPlace);
<ul id="places">
<li style="display:none;">Place A: <span></span></li>
<li style="display:none;">Place B: <span></span></li>
<li style="display:none;">Place C: <span></span></li>
<li style="display:none;">Place D: <span></span></li>
</ul>
<input type="button" value="Add new place" onclick="addNewPlace()"/>

you need to add jquery library
<ol></ol>
<button id="btn2">Append list item</button>
try this..
$(document).ready(function(){
$("#btn2").click(function(){
var count_cls = $('.munna').length;
if(count_cls<4)
{
$("ol").append("<li class='munna'>Place "+count_cls+"</li>");
}else
{
alert('max reached');
}
});
});
i have given for li you just change it to button whatever you want
chttK :http://jsfiddle.net/6yLpw9jv/2/

Related

Why does HTML say that my variable is not defined?

When I try to use the variable, it says it's not defined (error: "ReferenceError: hufc1 is not defined
at HTMLInputElement.onclick", this worked in my old code but not anymore. The code below is the full code to tell you what im trying to do.
<p id="redirect" style="display: none"><font color="32CD32"><em>You have entered the right Log In Infromation and You will be redirected into the document soon.</em></font></p>
<iframe id="embed" style="display: none"src="https://docs.google.com/document/d/1wZ9WVpkJAjdYVIyGEhgRBaEHulVKetOol17tizUVyLM/edit?usp=sharing" height='1080' width='1920'></iframe>
<p id="loginuser" style="display: block">USERNAME:
<input type="text" name="text1">
</p>
<p id="loginpass" style="display: block">PASSWORD:
<input type="password" name="dasnk2">
</p>
<input id="login" style="display: block" type="button" value="Log In" name="Submit" onclick=javascript:validate(text1.value,"Harrison",dasnk2.value,"88888888a") onclick=javascript:validate(text1.value,"Isaac",dasnk2.value,"IsABitch") onclick=javascript:validate(text1.value,"Adam",dasnk2.value,"faa222014") onclick=javascript:validate(text1.value,"Kelvin",dasnk2.value,"six921six921") >
<script>
function validate(text1,dasnk2,text3,text4) {
if (text1 === dasnk2 && text3 === text4) {
var redirect = document.getElementById('redirect');
var embed = document.getElementById("embed");
redirect.style.display = "block";
embed.style.display = "none";
setTimeout(function() {
embed.style.display = "block";
redirect.style.display = "none";
loginuser.style.display = "none";
loginpass.style.display = "none";
login.style.display = "none";
}, 5000);
} else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>```
If you want to keep your solution, you can pass value of input tag as parameter to function like below
onclick=javascript:validate(document.getElementsByName("text1")[0].value,"Isaac",document.getElementsByName("dasnk2")[0].value,"IsABitch")
function validate(text1,dasnk2,text3,text4) {
if (text1 === dasnk2 && text3 === text4) {
var redirect = document.getElementById('redirect');
var embed = document.getElementById("embed");
redirect.style.display = "block";
embed.style.display = "none";
setTimeout(function() {
embed.style.display = "block";
redirect.style.display = "none";
loginuser.style.display = "none";
loginpass.style.display = "none";
login.style.display = "none";
}, 5000);
} else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
<p id="redirect" style="display: none"><font color="32CD32"><em>You have entered the right Log In Infromation and You will be redirected into the document soon.</em></font></p>
<iframe id="embed" style="display: none"src="" height='1080' width='1920'></iframe>
<p id="loginuser" style="display: block">USERNAME:
<input type="text" name="text1">
</p>
<p id="loginpass" style="display: block">PASSWORD:
<input type="password" name="dasnk2">
</p>
<input id="login" style="display: block" type="button" value="Log In" name="Submit" onclick=javascript:validate(document.getElementsByName("text1")[0].value,"Harrison",document.getElementsByName("dasnk2")[0].value,"88888888a") onclick=javascript:validate(document.getElementsByName("text1")[0].value,"Isaac",document.getElementsByName("dasnk2")[0].value,"IsABitch") onclick=javascript:validate(document.getElementsByName("text1")[0].value,"Adam",document.getElementsByName("dasnk2")[0].value,"faa222014") onclick=javascript:validate(document.getElementsByName("text1")[0].value,"Kelvin",document.getElementsByName("dasnk2")[0].value,"six921six921") >
You can not get text1.value and dasnk2.value inline. You need move to a javascript function like below.
function validate(){
var name = document.getElementsByName("text1")[0].value;
var pass = document.getElementsByName("dasnk2")[0].value;
if((name == "test" && pass == "test") || (name == "test1" && pass == "test1") || (name == "test2" && pass == "test2") || (name == "test3" && pass == "test3")){
alert('Valid');
}else{
alert('Invalid');
}
}
<input type="text" name="text1">
</p>
<p id="loginpass" style="display: block">Password:
<input type="password" name="dasnk2">
</p>
<input id="login" style="display: block" type="button" value="Log In" name="Submit"
onclick="validate()">

HTML, JS - Display Loop's Output By Calling <div> From HTML To JS

I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" />&nbsp<input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" />&nbsp<input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>

Change css property with javascript

When I click on the button "Change/Add text to this picture" and input values in the two fields with id="top-distance" and id="left-distance" then click on the button "Done", those values should be set as the top and left css properties of the #img-text element. I tried to do that in the doneFunction() below but it doesn't work:
var pics = [['https://www.planwallpaper.com/static/images/ziiQN6XE5_UCWiCRXMT0B3p.jpg', 'Изображение 1'], ['https://www.planwallpaper.com/static/images/nature-wallpapers-free-download-1.jpg', 'Изображение 2'], ['https://www.planwallpaper.com/static/images/Beautiful_Wallpaper_1080p_Full_HD.jpg', 'Изображение 3'], ['https://www.planwallpaper.com/static/images/1080p-wallpaper-14854-15513-hd-wallpapers.jpg', 'Изображение 4'], ['https://static.pexels.com/photos/20974/pexels-photo.jpg', 'Изображение 5']];
var counter = 0;
function showImage() {
document.getElementById('main-pic').src = pics[counter][0];
document.getElementById('img-text').innerHTML = pics[counter][1];
//или чрез задаване на таг img тук: document.getElementById(...).innerHTML = '<img alt="Природа" class="main-pic" title="Природа" src="' + pics[counter][0] + '" />';
}
showImage();
function previousImg() {
if (counter == 0) {
alert('Няма предишно изображение.');
} else {
counter--;
}
showImage();
}
function nextImg() {
if (counter == pics.length - 1) {
alert('Няма следващо изображение.');
} else {
counter++;
}
showImage();
}
function addImg() {
var someURL = prompt('Посочете url на изображението, което желаете да добавите.', 'https://www.picwallz.com/wp-content/uploads/2017/02/desktop-natural-beauty-cave-with-nature-pics-high-quality-for-mobile-phones-v-898x505.jpg');
if (someURL == null) {
alert('Вие отказахте добавянето на ново изображение.');
return;
}
function isValidURL(stringURL) {
var pattern = /(http|https):\/\/(\w+:{0,1}\w*)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%!\-\/]))?/;
if (!pattern.test(stringURL)) {
alert("Не сте въвели url адрес, опитайте пак!");
return false;
} else {
return true;
}
}
if (isValidURL(someURL)) {
pics.push([someURL, 'Text']);
}
}
function changeAddText() {
document.getElementById('hidden-div').style.display = 'block';
}
function doneFunction() {
document.getElementById('hidden-div').style.display = 'none';
pics[counter][1] = document.getElementById('new-text').value;
//document.getElementById('img-text').style.top.value = document.getElementById('top-distance').value;
var pText = document.getElementById('img-text');
var topText = document.getElementById('top-distance').value;
if (!isNaN(topText) && (topText <= 200)) {
pText.style.top = topText;
} else {
alert('Please insert a number <=200.');
}
var leftText = document.getElementById('left-distance').value;
if (!isNaN(leftText) && (topText <= 100)) {
pText.style.left = leftText;
} else {
alert('Please insert a number <=100.');
}
showImage();
}
#main-pic {
position: relative;
width: 500px;
height: 350px;
}
#img-text {
color: white;
position: absolute;
top: 5px;
left: 20px;
}
.button {
height: 40px;
background-color: lightblue;
}
#hidden-div {
display: none;
}
<img id="main-pic" alt="Природа" title="Природа" /><br />
<p id="img-text"></p>
<br />
<input class="button" type="button" name="previous" value="Prev" onclick="previousImg(); return false;" />
<input class="button" type="button" name="next" value="Next" onclick="nextImg(); return false;" />
<input class="button" type="button" name="next" value="Add picture" onclick="addImg(); return false;" />
<input class="button" type="button" name="change-add-text" value="Change/Add text to this picture" onclick="changeAddText(); return false;" />
<div id="hidden-div">
<input id="new-text" type="text" name="new-text" placeholder="Your text" value="Picture" />
<input type="number" id="top-distance" name="topText" min="0" max="200" step="5" placeholder="top" />
<input type="number" id="left-distance" name="leftText" min="0" max="100" step="5" placeholder="left" />
<input class="button" type="button" name="done-button" value="Done" onclick="doneFunction(); return false;" />
</div>
You need to include the units when setting the position.
Change these lines:
pText.style.top = topText;
pText.style.left = leftText;
to:
pText.style.top = topText + 'px';
pText.style.left = leftText + 'px';

How to count checked checkboxes in different divs

<head><title>STUDENT WISE EXAM BACKLOGS DISPLAY FOR EXAM REGISTRATION</title>
<style type="text/css">
th {
font-family:Arial;
color:black;
border:1px solid #000;
}
thead {
display:table-header-group;
}
tbody {
display:table-row-group;
}
td {
border:1px solid #000;
}
</style>
<script type="text/javascript" >
function check_value(year,sem){
ysem="ys"+year+sem;
var reg=document.registration.regulation.value;
subjectsys="subjects"+year+sem;
amountsys="amount"+year+sem;
if(year==1){
if(sem==1){
var value_list = document.getElementById("ys11").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys12").getElementsByTagName('input');
}
}elseif(year==2){
if(sem==1){
var value_list = document.getElementById("ys21").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys22").getElementsByTagName('input');
}
}elseif(year==3){
if(sem==1){
var value_list = document.getElementById("ys31").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys32").getElementsByTagName('input');
}
}elseif(year==4){
if(sem==1){
var value_list = document.getElementById("ys41").getElementsByTagName('input');
}
if(sem==2){
var value_list = document.getElementById("ys42").getElementsByTagName('input');
}
}
values = 0;
for (var i=0; i<value_list.length; i++){
if (value_list[i].checked) {
values=values+1;
}
}
document.getElementById(subjectsys).value=values;
if (values=="0")
{
document.getElementById(amountsys).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById(amountsys).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","fee.php?year="+year+"&reg="+reg+"&sem="+sem+"&sub="+values,true);
xmlhttp.send();
}
</script>
</head>
<form id="registration" name="registration" action=subverify.php method=POST></br></br> <center> Backlog Subjects for <b>My HtNo</b>
</br></br>
<table border='1'><tr>
<th width='40'> </th><th width='90'>Regulation</th><th width='40'>Year</th>
<th width='40'>Sem</th><th width='350'>Subname</th>
<th width='70'>Internals</th><th width='70'>Externals</th>
</tr><div id="ys41"><tr>
<td width='40'><center><input type="checkbox" name="sub[]" value="344"
onclick="check_value(4,1)"></center></td>
<td width='90'><center>R07</center></td><td width='40'><center>4</center></td><td width='40'><center>1</center></td>
<td width='350'>EMBEDDED SYSTEMS</td><td width='70'><center>18</center></td>
<td width='70'><center>17</center></td></tr><tr><td colspan=5 align=right><b>Subjects: </b><input size=2 type=textbox id=subjects41 name=subjects41 value=0 maxlength=2 readonly=readonly></td>
<td align=right><b>Amount :</b></td>
<input type='hidden' name='regulation' id=regulationsubjects41 value='R07'>
<td><div id="amount41"><input type="textbox" name="amountval41" value="0" size="5" maxlength="5" readonly="readonly"></div></td></tr></div><div id="ys42"><tr>
<td width='40'><center><input type="checkbox" name="sub[]" value="527"
onclick="check_value(4,2)"></center></td>
<td width='90'><center>R07</center></td><td width='40'><center>4</center></td><td width='40'><center>2</center></td>
<td width='350'>DESIGN PATTERNS</td><td width='70'><center>12</center></td>
<td width='70'><center>14</center></td></tr><tr><td colspan=5 align=right><b>Subjects: </b><input size=2 type=textbox id=subjects42 name=subjects42 value=0 maxlength=2 readonly=readonly></td>
<td align=right><b>Amount :</b></td>
<input type='hidden' name='regulation' id=regulationsubjects42 value='R07'>
<td><div id="amount42"><input type="textbox" name="amountval42" value="0" size="5" maxlength="5" readonly="readonly"></div></td></tr></div><tr><td colspan=7><center><b><div id="maintotal"><input type="textbox" name="maintotal" value="0" size="5" maxlength="5" readonly="readonly"></div></center></b></td></tr><tr></tr></table></br></br> <center><input type='hidden' name='htno' value='08KN1A1219'>
<input type='submit' value='Register'></center></form></br>
This is a output of a PHP file with using dynamic data in the form.
I want to count only the checkboxes in the <div> tag and it has to display in that subjects <div> tag like subjects41 and subjects42. Can anyone please help me to update this JavaScript? It passes some ajax request for displaying the fee.
$("input[type=checkbox]:checked").length
You can use simple jquery something like this
var count=0;
$("input[type=checkbox]").each(function(){
if(this.is(":checked")){
count+=1;
}
})
alert(count);
Using jQuery ,
var ids = $('input[name="nameofcheckbox[]"]:checked')
.map(function(){
return this.value;
}).get();
Without Jquery:
var div = document.getElementById("ys41");
var checkboxes = [];
function getCheckBoxes(el) {
//check this is an element
if (el.nodeType == 1) {
var i = 0;
//get the children
var elements = el.childNodes;
// Loop through children
while (typeof elements[i] !== 'undefined') {
//check this is an element
if (elements[i].nodeType == 1) {
// If the type is checkbox add it to the array
if (elements[i].getAttribute('type') == 'checkbox') {
checkboxes[checkboxes.length] = elements[i];
}
// Otherwise recurse
else {
if (elements[i].childNodes.length > 0) {
getCheckBoxes(elements[i]);
}
}
}
i++;
}
}
}
getCheckBoxes(div);
Caveat: I don't have time right now to check that this works ;). If it doesn't comment and I'll correct this evening.
Since you wanted to do this using javascript,
<FORM>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="1"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="2"><br>
<INPUT TYPE=checkbox NAME="chkboxarray" VALUE="3"><br>
<INPUT TYPE=button NAME="CheckAll" VALUE="checkbox count" onClick="modify_boxes()">
</FORM>​
function modify_boxes(){
var total_boxes = document.forms[0].chkboxarray.length;
var count =0;
for ( i=0 ; i < total_boxes ; i++ ){
if (document.forms[0].chkboxarray[i].checked ==true)
count++;
}
alert(count);
}​​​​
Working Demo
here you go, this's what you asked :)
var i=0;
var checks= 0;
divelem = document.getElementById("divelem");
while(i < divelem.childNodes.length){
if( divelem.childNodes[i].nodeType != 3 //not empty space
&& divelem.childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelem.childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
alert("no of checkboxes checked in div are: "+checks);
I prefer you count in the php itself.
UPDATE:
here's the complete code, I am damn sure it's working. It gives all checkboxes that are checked in all div elements. Pls check.
<html>
<div >
1.<input type="checkbox" value="check1" / ></br>
2.<input type="checkbox" value="check2" / ></br>
3.<input type="checkbox" value="check3" / ></br>
</div>
<div >
4.<input type="checkbox" value="check4" / ></br>
5.<input type="checkbox" value="check5" / ></br>
</div>
<input type="button" value="count check" onclick="check()">
<script>
function check(){ //function can count checkboxes for all div elements in document
var checks= 0;
var divelems = document.getElementsByTagName('div');
for(no=0;no<divelems.length;no++){
var i=0;
while(i < divelems[no].childNodes.length){
if( divelems[no].childNodes[i].nodeType != 3 //not empty space
&& divelems[no].childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelems[no].childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
}
alert("no of checkboxes checked inside div are: "+checks);
}
</script>
</html>
UPDATE2:
pls check now
<html>
<script>
function check(div){ //function can count checkboxes for divs elements that is passed in as argument
var checks= 0;
var divelem = document.getElementById(div);
var i=0;
while(i < divelem.childNodes.length){
if( divelem.childNodes[i].nodeType != 3 //not empty space
&& divelem.childNodes[i].getAttribute('type') == 'checkbox' //is checkbox?
&& divelem.childNodes[i].checked ){ // is checked?
checks++;
}
i++;
}
alert("no of checkboxes checked inside "+div+" are: "+checks);
}
</script>
<div id="div1" >
1.<input type="checkbox" value="check1" / ></br>
2.<input type="checkbox" value="check2" / ></br>
3.<input type="checkbox" value="check3" / ></br>
<input type="button" value="count check div1" onclick="check('div1')">
</div>
<div id="div2" >
4.<input type="checkbox" value="check4" / ></br>
5.<input type="checkbox" value="check5" / ></br>
</div>
<input type="button" value="count check div2 " onclick="check('div2')">
</html>

Show/Hide divs, "one by one" and "all at once"

I'm using this to show/hide some divs, at the end I have a button to show the divs one by one.
How can I have a second button to show/hide all of them at once without messing too much with the HTML?
Basically each div contains an input field, so the user clicks the "Add one more" button to get an extra field. By default, all fields are hidden so I need a button to show them all at once (I have 14 divs to show/hide).
Any help will be appreciated.
Javascript
var counter = 0;
var numBoxes = 3;
function toggle4(showHideDiv) {
var ele = document.getElementById(showHideDiv + counter);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
if(counter == numBoxes) {
document.getElementById("toggleButton").style.display = "none";
}
}
HTML
<table>
<tr>
<td style="width: 150px;">
<div id="box1" style="display: none;">First</div>
</td>
<td style="width: 150px;">
<div id="box2" style="display: none;">Second</div
</td>
<td style="width: 150px;">
<div id="box3" style="display: none;">Third</div
</td>
</tr>
</table>
<input id="toggleButton" type="button" value="Add one more!" onclick="counter++; toggle4('box');">
Here's the basic functionality, though it needs some refinement:
var d = document,
table = d.getElementsByTagName('table')[0],
divs = table.getElementsByTagName('div'),
toggle = d.getElementById('toggleButton'),
allToggle = d.getElementById('allToggle'),
count = 0;
function toggles(){
var elem = divs[count];
elem.style.display = 'block';
count++;
}
toggle.onclick = function(){
toggles();
};
allToggle.onclick = function(){
if (allToggle.getAttribute('data-show') == 1){
for(var i=0,len=divs.length;i<len;i++){
divs[i].style.display = 'none';
allToggle.setAttribute('data-show',0);
allToggle.value = 'Show all';
}
}
else {
for(var i=0,len=divs.length;i<len;i++){
divs[i].style.display = 'block';
allToggle.setAttribute('data-show',1);
allToggle.value = 'Hide all';
}
}
}
​
JS Fiddle demo.
The above based on the following HTML:
<table>
<tr>
<td style="width: 150px;">
<div id="box1" style="display: none;">First</div>
</td>
<td style="width: 150px;">
<div id="box2" style="display: none;">Second</div>
</td>
<td style="width: 150px;">
<div id="box3" style="display: none;">Third</div>
</td>
</tr>
</table>
<input id="toggleButton" type="button" value="Add one more!" />
<input id="allToggle" type="button" value="Show all" />​
have a button with a function that selects all of the divs by a class (that you'll have to add) and hides/shows them. If you just want one button you'll have to remember your state, which in the example below I do with a global.
<button id="showhideall">
$(document).ready(function(){
var allshowing = true;
$("#showhideall").click(function(){
alert(allshowing);
if(allshowing){
$(".foo").hide();
allshowing=false;
} else {
$(".foo").show();
}
});
}​);​
var counter = 0;
var numBoxes = 3;
function toggle4(showHideDiv) {
var ele = document.getElementById(showHideDiv + counter);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
if(counter == numBoxes) {
document.getElementById("toggleButton").style.display = "none";
}
}
function toggle3(contentDiv) {
if (contentDiv.constructor == Array) {
for(i=0; i < contentDiv.length; i++) {
toggle2(contentDiv[i]);
}
}
else {
toggle2(contentDiv);
}
}
function toggle2(showHideDiv) {
var ele = document.getElementById(showHideDiv);
if(ele.style.display == "block") {
ele.style.display = "none";
}
else {
ele.style.display = "block";
}
}
<input id="toggleButton" type="button" value="Show me the money!" onclick="counter++; toggle4('box');">
<input type="button" value="Press me to toggle all 3 DIVs" onClick="toggle3(['box1', 'box2', 'box3']);">

Categories

Resources