I am trying to make a search using an input submit type field. Once user enters something, it should look through the value in the divs. If it matches one of them then it should highlight that div background in yellow, if it doesnt we add the new value in the bottom of the div list.
I was able to highlight the background when it matches, but the highlight only stays for a second and disappears.Also, it doesn't match the second element of the list "Machine Learning". For the second part for adding in the bottom of the list, I tried push the new value in the list but that didn't work either.
Any suggestions ?
HTML and JS:
`
function searchList() {
var searchCourse = document.getElementById("search").value;
var courseList = document.getElementById("courselist").getElementsByTagName("DIV");
for(var i=0; i<courseList.length; i++) {
var course = courseList[i];
var coursecheck = course.innerHTML;
if(searchCourse == coursecheck){
course.style.backgroundColor = 'yellow';
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title> SOEN 287 NEW Exercise </title>
<style type="text/css">
fieldset {border:0px;}
#courselist {width:300px;}
#courselist div {border: 1px black solid;padding:10px;}
</style>
</head>
<body>
<div id="container">
<h2>Search a Course</h2>
<form action="" method="post" onsubmit="return searchList()">
<fieldset>
Enter the Course Name<br />
<input type="text" id="search" size="20" /><br />
<input type="submit" value="Search List" id="sub" />
<br /><br />
</fieldset>
</form>
<div id="courselist">
<div id="first"> </div>
<div> Machine Learning </div>
<div> Image Processing</div>
<div>Design and Analysis of Algorithms</div>
<div>Web Programming II </div>
<div>Advanced JAVA</div>
<div>Pattern Recognition</div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Please try this:
function searchList() {
var searchCourse = document.getElementById("search").value,
courseList = document.getElementById("courselist").getElementsByTagName("div"),
found = false;
for (var i = 0; i < courseList.length; i++) {
var course = courseList[i];
//Get the the div content (course) and trim it
var coursecheck = course.innerHTML.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, "");
if (searchCourse === coursecheck) {
course.style.backgroundColor = 'yellow';
//Match found so we don't need to add new element
found = true;
} else {
//Reset the background color
course.style.backgroundColor = 'transparent';
}
}
//New element add it to the list
if(!found) {
var newDiv = document.createElement("DIV");
newDiv.innerHTML = searchCourse;
document.getElementById("courselist").appendChild(newDiv);
}
return false;
}
Demo: https://jsfiddle.net/iRbouh/jpor2eb3/
I hope this will help.
Please check this code.
JavaScript
function searchList() {
var searchCourse = document.getElementById("search").value;
var courseList = document.getElementById("courselist").getElementsByTagName("DIV");
for (var i = 0; i < courseList.length; i++) {
var course = courseList[i];
var coursecheck = course.innerHTML;
console.log(coursecheck)
if (searchCourse == coursecheck) {
course.style.backgroundColor = 'yellow';
}
}
return false;
}
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title> SOEN 287 NEW Exercise </title>
<style type="text/css">
fieldset {border:0px;}
#courselist {width:300px;}
#courselist div {border: 1px black solid;padding:10px;}
</style>
</head>
<body>
<div id="container">
<h2>Search a Course</h2>
<form action="" method="post" onsubmit="return searchList()">
<fieldset>
Enter the Course Name<br />
<input type="text" id="search" size="20" /><br />
<input type="submit" value="Search List" id="sub" />
<br /><br />
</fieldset>
</form>
<div id="courselist">
<div id="first"> </div>
<div>Machine Learning </div>
<div>Image Processing</div>
<div>Design and Analysis of Algorithms</div>
<div>Web Programming II </div>
<div>Advanced JAVA</div>
<div>Pattern Recognition</div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Can you add a data-value attribute on the divs? if so you can do something like this:
function searchList() {
var searchCourse = document.getElementById("search").value,
highlight = document.querySelectorAll("[data-value='" + searchCourse + "']")[0] // <~~ only want the first
highlight.style.backgroundColor = 'yellow';
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title> SOEN 287 NEW Exercise </title>
<style type="text/css">
fieldset {border:0px;}
#courselist {width:300px;}
#courselist div {border: 1px black solid;padding:10px;}
</style>
</head>
<body>
<div id="container">
<h2>Search a Course</h2>
<form action="" method="post" onsubmit="return searchList()">
<fieldset>
Enter the Course Name<br />
<input type="text" id="search" size="20" /><br />
<input type="submit" value="Search List" id="sub" />
<br /><br />
</fieldset>
</form>
<div id="courselist">
<div id="first"> </div>
<div data-value='Machine Learning'>Machine Learning </div>
<div data-value='Image Processing'>Image Processing</div>
<div data-value='Design and Analysis of Algorithms'>Design and Analysis of Algorithms</div>
<div>Web Programming II </div>
<div>Advanced JAVA</div>
<div>Pattern Recognition</div>
</div>
</div>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
If you make the button a link with an href='#something' then it won't page reload, or add an event listener to the button and do event.preventDefault()
Related
I know this is a basic questions, but I am working on making a dynamic form and was having a bit of trouble figuring out how to delete elements that share the same class. I have looked around on the web and other posts for a means to accomplish this, but still was unable to figure it out.
I am new to this so I apologize for the basic question. Below, I have pasted the relevant code and my attempt at this. Would anyone be able to assist me?
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName){
if (ingCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement('directionSet');'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName){
if (dirCounter == limit) {
alert("You have reached the add limit");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
<!-- Required program scripts -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<!-- Style Sheets-->
<link rel="stylesheet" href="/styles/navBarStyle.css">
<link rel="stylesheet" href="/styles/myRecipesStyle.css">
<link rel="stylesheet" href="/styles/createRecipeStyle.css">
<link rel="stylesheet" href="/styles/errorMessageStyle.css">
</head>
<body>
<!-- Background image -->
<img id="background" src="/images/foodBackground.jpg" alt="">
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<%- include('../_partial/_messages'); -%>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage"/>
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
<!-- Required scripts to run app -->
<script src="/controls/newRecipeControl.js"></script>
<script src="/controls/errorMessageControl.js"></script>
</html>
Thanks for any help.
In your code you are using getElementById but there is no id called directionSet its a class.
You can simply use parentElement and remove to remove the newly added dynamic inputs by calling an onClick function.
In the onClick function removeElement() - this refers to the elements we have clicked and it will remove from the form.
var ingCounter = 1;
var dirCounter = 1;
var limit = 10;
function addIngredient(divName) {
if (ingCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='ingredientSet'><input class='ingredientInput' type='text' name='ingredients[]'><button class='deleteIngredientButton' type='button' onClick='removeElement(this);'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
ingCounter++;
}
}
function addDirection(divName) {
if (dirCounter == limit) {
alert("You have reached the add limit");
} else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "<div class='directionSet'><input class='directionInput' type='text' name='directions[]'><button class='deleteDirectionButton' onClick='removeElement(this);' type='button'>X</button></div>";
document.getElementById(divName).appendChild(newdiv);
dirCounter++;
}
}
function removeElement(elementId) {
// Removes an element from the document
elementId.parentElement.remove()
}
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Homemade</title>
</head>
<body>
<!-- Background image -->
<div id="newRecipeContainer">
<div id="closeButtonContainer">
<div id="backButton"><a id="back" href="/recipes/myRecipes">← My Recipes</a></div>
</div>
<form id="createRecipeForm" action="/recipes/createRecipe" method="POST" enctype="multipart/form-data">
<label id="formSubHeading">Create Your Homemade Recipe</label>
<div id="recipeNameContainer">
<label id="recipeNameLabel">Title</label>
<input id="recipeNameInput" type="text" name="recipeName">
</div>
<div id="recipeImage">
<label id="recipeImageLabel">Add An Image of Your Meal</label>
<input id="recipeImageInput" type="file" accept="image/*" name="recipeImage" />
<label id="recipeImageInputLabel" for="recipeImageInput" name="recipeImage">Choose A File</label>
</div>
<div id="recipeDescription">
<label id="recipeDescriptionLabel">Description</label>
<textarea id="recipeDescriptionInput" name="recipeDescription" cols="30" rows="10" maxlength="2000"></textarea>
</div>
<div class="ingredientsContainer">
<label id="ingredientsLabel">Ingredients</label>
<button id="addIngredientButton" type="button" onClick="addIngredient('allIngredients');">Add Another Ingredient</button>
<div id="allIngredients">
<div class="ingredientSet">
<input class="ingredientInput" type="text" name="ingredients[]">
</div>
</div>
</div>
<div class="directionsContainer">
<label id="directionsLabel">Directions</label>
<button id="addDirectionButton" type="button" onClick="addDirection('allDirections');">Add Another Direction</button>
<div id="allDirections">
<div class="directionSet">
<input class="directionInput" type="text" name="directions[]">
</div>
</div>
</div>
<div id="createRecipeButtonContainer">
<button id="createRecipeButton" type="submit">Create Recipe</button>
</div>
</form>
</div>
</body>
</html>
Here is the JS code:
function flag(){
document.getElementById("f1").value = "country1";
document.getElementById("f1").value = "country2";
}
function clean(){
document.getElementById("country1").value = "";
document.getElementById("country2").value = "";
}
HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flag name</title>
<script src="flag.js"></script>
<script src="C:\Users\DELL\Desktop\jq\jquery.3.js"></script>
<link rel="stylesheet" text="text/css" href="flag.css">
</head>
<body>
<img src="C:\Users\DELL\Desktop\flag1.png" id="flag1" onmouseover="flag()" onmouseout="clean()">
<img src="C:\Users\DELL\Desktop\flag2.png" id="flag2" onmouseover="flag()" onmouseout="clean()">
<form action="#" method="GET">
<input type="text" name="Flag1" id="f1">
<input type="text" name="Flag2" id="f2">
</form>
</body>
</html>
How to get the result in separate text box when mouse is hovered over the image of a country flag.
I want only the output on which mouse is present.
<script type="text/javascript">
jQuery(document).ready(function( $ ) {
$("#flag1").mouseover(function() {
$("#f1").val("country1");
});
$("#flag1").mouseleave(function() {
$("#f1").val("");
});
$("#flag2").mouseover(function() {
$("#f2").val("country2");
});
$("#flag2").mouseleave(function() {
$("#f2").val("");
});
});
</script>
<!DOCTYPE html>
<html>
<head>
<title>Flag name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<img src="images/banner1.png" id="flag1">
<img src="images/mobile.png" id="flag2">
<form action="#" method="GET">
<input type="text" name="Flag1" id="f1">
<input type="text" name="Flag2" id="f2">
</form>
</body>
</html>
Hi and welcome to Stackoverflow, i think this could be a more generic solution for you:
function flag(element) {
document.getElementById(element.getAttribute('data-target')).value = element.id;
}
function clean(element) {
document.getElementById(element.getAttribute('data-target')).value = ''
}
img {
width: 150px;
}
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" id="country1" data-target="f1" onMouseOver="flag(this)" onMouseOut="clean(this)">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAHd3dwAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==" id="country2" data-target="f2" onMouseOver="flag(this)" onMouseOut="clean(this)">
<form action="#" method="GET">
<input type="text" name="Flag1" id="f1">
<input type="text" name="Flag2" id="f2">
</form>
onMouseOver
function flag(id){
document.getElementById("f1").value = id;
}
function clean(){
document.getElementById("country1").value = "";
document.getElementById("country2").value = "";
}
HTML code
<!DOCTYPE html>
<html>
<head>
<title>Flag name</title>
<script src = "flag.js"></script>
<script src = "C:\Users\DELL\Desktop\jq\jquery.3.js"></script>
<link rel = "stylesheet" text = "text/css" href = "flag.css">
</head>
<body>
<img onmouseover="flag(this.id))" src = "C:\Users\DELL\Desktop\flag1.png" id = "flag1" onmouseout = "clean()">
<img onmouseover="flag(this.id))" src = "C:\Users\DELL\Desktop\flag2.png" id = "flag2" onmouseout = "clean()">
<form action = "#" method = "GET">
<input type = "text" name = "Flag1" id = "f1">
<input type = "text" name = "Flag2" id = "f2">
</form>
</body>
</html> onmouseover="bigImg(this)"
How is the structure of you project?
flag.js has to be in the same folder that index.html. Also link your javascript scripts at the end of the body.
And then you have a couple of errors with the document.getElementById, you are using the wrong ids.
function flag(){
document.getElementById("f1").value = "country1";
document.getElementById("f2").value = "country2";
}
function clean(){
document.getElementById("f1").value = "";
document.getElementById("f2").value = "";
}
<!DOCTYPE html>
<html>
<head>
<title>Flag name</title>
<link rel="stylesheet" text="text/css" href="flag.css">
</head>
<body>
<img src="C:\Users\DELL\Desktop\flag1.png" id="flag1" onmouseover="flag()" onmouseout="clean()">
<img src="C:\Users\DELL\Desktop\flag2.png" id="flag2" onmouseover="flag()" onmouseout="clean()">
<form action="#" method="GET">
<input type="text" name="Flag1" id="f1">
<input type="text" name="Flag2" id="f2">
</form>
<script src="flag.js"></script>
<script src="C:\Users\DELL\Desktop\jq\jquery.3.js"></script>
</body>
</html>
you can use o onmouseover = "flag()" the parameter this.id like
<img src="C:\Users\DELL\Desktop\flag1.png" id="flag1" onmouseover="flag(this.id)" onmouseout = "clean()">
and after make a if to put the value
if (parameter == flag'){
put one flag
}else{
put the other flag
}
You need to pass your event or this inside of onmouseover and onmouseout event
You can find the textfield by using document.querySelector() and set value inside of onmouseover/onmouseout
You can get the you target attribute value using getAttribute() method.
DEMO
function flag(tag) {
document.querySelector(`[name=${tag.id}]`).value = tag.getAttribute('value');
}
function clean(tag) {
document.querySelector(`[name=${tag.id}]`).value = '';
}
<img src="C:\Users\DELL\Desktop\flag1.png" value="Country 1" id="flag1" onmouseover="flag(this)" onmouseout="clean(this)">
<img src="C:\Users\DELL\Desktop\flag2.png" value="Country 2" id="flag2" onmouseover="flag(this)" onmouseout="clean(this)">
<form action="#" method="GET">
<input type="text" name="flag1">
<input type="text" name="flag2">
</form>
When I use form action URL with 'www' prefix, by pressing the submit button (or enter key) the form does not work: submits but won't send any variables. It does work, however, with JS submit by clicking the magnifier, even though JS code does not affect the URL (at least as far as I know).
When I remove 'www' it works both ways. Any idea what the reason is behind this?
http://www.hasznaltfaiparigep.hu/fr/index2.php
I made a gray div above the form to display POST variables.
Here's my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<html>
<head>
<title>Bonjour! :)</title>
<meta http-equiv="content-language" content="hu" />
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="tabs.css">
<link rel="shortcut icon" href="images/favicon.ico?v=1.2">
<script>
function addElementAndSubmitForm(formName,actionUrl,elName,elValue) {
var form = document.forms[formName];
form.action = actionUrl;
var el = document.createElement("input");
el.type = "hidden";
el.name = elName;
el.value = elValue;
form.appendChild(el);
form.submit();
}
</script>
</head>
<body>
<div id="page-wrap">
<form name="myForm" method="POST" action="http://www.hasznaltfaiparigep.hu/fr/index2.php">
<div id="debug" style="border:solid 1px black;padding:10px;margin:10px;background:#ccc;color:#555;width:96%">
<font style="font-weight:bold">POST vars:</font>
<?php
if( count($_POST) > 0 ) {
echo "<br/><span style=\"padding-left:4px\"> ";
print_r($_POST); echo "</span>";
}
?>
</div>
<div style="float:left;">
Chercher un mot: <input type="text" id="cherfield" name="chercher" />
<img style="padding: 0 5px; margin: 0 0 -8px 0;" src="images/chercher.jpg" onClick="javascript:addElementAndSubmitForm('myForm','#','chercher',document.getElementById('cherfield').value);"/>
<br />
<input type="submit" value="envoi" />
</div>
<input type="hidden" name="hidden_input" value="whatever">
</form>
</div>
</body>
</html>
Have been trying to add a custom button for about 2 hours and I just can't get it to work. I don't know much about javascript maybe that's why. I did manage to get the button to show up and open a popup, but that's as far as I got.
I want the button to insert t he following into the HTML section of tinymce:
'
Here is my dialog.js file:
tinyMCEPopup.requireLangPack();
var InsertQuoteDialog = {
init: function () {
var s = tinyMCEPopup.editor.selection.getContent({ format: 'text' });
if (s.trim().length > 0) {
document.forms[0].blizzQuote.value = s.trim();
}
},
insert: function () {
var s1 = '<p class="blizzardQuote" ';
s1 += Encoder.htmlEncode(document.forms[0].blizzQuote.value.trim()) + '</p>';
tinyMCEPopup.editor.execCommand('mceInsertContent', false, s1);
tinyMCEPopup.close();
}
};
String.prototype.trim = function () {
return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
tinyMCEPopup.onInit.add(InsertQuoteDialog.init, InsertQuoteDialog);
And my Dialog.htm file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>{#example_dlg.title}</title>
<script type="text/javascript" src="../../tiny_mce_popup.js"></script>
<script type="text/javascript" src="js/dialog.js"></script>
</head>
<body>
<form onsubmit="InsertQuoteDialog.insert();return false;" action="#">
<p>Blizzard Quote</p>
<p>Blizzard Quote: <input id="blizzQuote" name="blizzQuote" type="text" class="text" /></p>
<div class="mceActionPanel">
<div style="float: left">
<input type="button" id="insert" name="insert" value="{#insert}" onclick="InsertQuoteDialog.insert();" />
</div>
<div style="float: right">
<input type="button" id="cancel" name="cancel" value="{#cancel}" onclick="tinyMCEPopup.close();" />
</div>
</div>
</form>
</body>
</html>
Basically when I click on insert nothing happens.
Thanks.
A quick look at the javaScript console should show you that you are getting a JavaScript error on the dialog with the Encoder object not being known.
Simply include the JS file that defines Encoder on your dialog and it should all be good.
I have this code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The management panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type="text/javascript">
function markPercentages(){
var checked = $(':checked');
var percentage = Math.round((1 / checked.length) * 100);
checked.siblings('.percentage').html(percentage);
$('input[type=checkbox]').not(checked).siblings('.percentage').html('0');
}
</script>
</head>
<body>
<form>
Building<br /><div><input type="checkbox" onclick='markPercentages()' name="6" value="6"> Susilo 2A-13 (<span class='percentage'>0</span>%)</div><br />
<div><input type="checkbox" onclick='markPercentages()' name="7" value="7"> Susilo 2A-12 (<span class='percentage'>0</span>%)</div>
<br />Category<br /><select name="title"><option value="Wages">Wages</option><option value="Listrik">Listrik</option><option value="Iuran Bulanan">Iuran Bulanan</option></select><br />
On<br /><input type=text name=date id=date /><br />
Notes<br /><input type=text name=note /><br />
Value<br /><input type=text name=cost onChange="addDecimalPoints(this.id)" id=cost /><br />
<input type=submit value="Save" />
</form>
</body>
</html>
It shows a percentage right next to the building (Susilos) of the cost that it's adding. In simplest terms, if one is checked it shows 100%, if two are checked it shows 50% on the first and 50% on the second and so on.
It works fine in Chrome but in Firefox when I check just one, it shows 50% on that, like there are checked two. When I check two it shows 33% on those, like I checked three of them. Why this happen and how I should fix this?
Anyway , deleting a part of the code that's beyond that code makes that works also:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The management panel</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type="text/javascript">
function markPercentages(){
var checked = $(':checked');
var percentage = Math.round((1 / checked.length) * 100);
checked.siblings('.percentage').html(percentage);
$('input[type=checkbox]').not(checked).siblings('.percentage').html('0');
}
</script>
</head>
<body>
<form>
Building<br /><div><input type="checkbox" onclick='markPercentages()' name="6" value="6"> Susilo 2A-13 (<span class='percentage'>0</span>%)</div><br />
<div><input type="checkbox" onclick='markPercentages()' name="7" value="7"> Susilo 2A-12 (<span class='percentage'>0</span>%)</div>
</form>
</body>
</html>
Thanks
http://jsfiddle.net/sjRAu/ - working all browsers
HTML:
<div>
<input type='checkbox' />Susilo 2A-13 (<span class='percentage'>0</span>%)
</div>
<div>
<input type='checkbox' />Susilo 2A-14 (<span class='percentage'>0</span>%)
</div>
<div>
<input type='checkbox' />Susilo 2A-15 (<span class='percentage'>0</span>%)
</div>
JS:
$(document).ready(function() {
$('input').click(function(){
markPercentages();
});
function markPercentages(){
var checked = $(':checked');
var percentage = Math.round((1 / checked.length) * 100);
checked.siblings('.percentage').html(percentage);
$('input[type=checkbox]').not(checked).siblings('.percentage').html('0');
}
});
If you have more inputs on the page just give your checkboxes a class like 'markbox' and change 'input' to '.markbox' in your JS
what about use like this one
$(function(){
$('input[type=checkbox').click(function(){
var checked = $('input[type=checkbox]').attr('checked');
var percentage = Math.round((1 / checked.length) * 100);
checked.siblings('.percentage').html(percentage);
$('input[type=checkbox]').not(checked).siblings('.percentage').html('0');
});
});
Try this code. I basically rewrote all of your logic:
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.min.js'></script>
<script type="text/javascript">
$(document).ready(function() {
$(':checkbox').change(function() {
var num_checked = $(':checkbox:checked').length;
if (num_checked == 0) {
$(':checkbox').each(function() {
$(this).siblings('.percentage:eq(0)').text('0');
});
return;
}
var percentage = Math.round(100 / num_checked);
$(':checkbox').each(function() {
if ($(this).is(':checked')) {
$(this).siblings('.percentage:eq(0)').text(percentage);
} else {
$(this).siblings('.percentage:eq(0)').text('0');
}
});
});
});
</script>
</head>
<body>
<div>
<input type='checkbox'/>Susilo 2A-13 (<span class='percentage'>0</span>%)
</div>
<div>
<input type='checkbox' />Susilo 2A-14 (<span class='percentage'>0</span>%)
</div>
<div>
<input type='checkbox' />Susilo 2A-15 (<span class='percentage'>0</span>%)
</div>
</body>
</html>
Demo: http://jsfiddle.net/NKuHS/3/