I have the following 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>
<style type="text/css">
body {background-color:Gray;}
body {text-align:left;}
</style>
<title>My First Project</title>
</head>
<body>
<form>
<table border="1" align="center">
<u><h5>Size</h5></u>
<tr><td><input type="radio" name="size" id="small" />Small</td></tr>
<tr><td><input type="radio" name="size" id="medium" />Medium</td></tr>
<tr><td><input type="radio" name="size" id="large" />Large</td></tr>
</table>
<br />
<script type="text/javascript">
if (document.getElementById('small').checked) {
document.getElementById('total').innerHTML = '$1.00';
}
else {
}
</script>
<div id="total">$0.00</div>
</form>
</body>
</html>
I wanted the script to change the text within div total to $1.00 instead of $0.00 when the radiobutton with id small was checked. However, nothing happens when I select it. What am I missing?
You've to invoke a function on some event -- JS basically runs on events!!
<input type="radio" name="size" id="small" onclick="yourFxn()" />Small</td>
In your script
function yourFxn(){
if (document.getElementById('small').checked) {
document.getElementById('total').innerHTML = '$1.00';
}
else {
}
}
scripts are read sequentially. When your javascript runs, there is no element with id total on the page because it is below the script.
But even if you move the code below, it still won't work because there is no click event atached to the radiobutton. your script only checks if the radiobutton is somehow magically selected on page load and changes the text. for exemple this code will change the text but it requires you to hardcode the checked radiobutton:
<!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>
<style type="text/css">
body {background-color:Gray;}
body {text-align:left;}
</style>
<title>My First Project</title>
</head>
<body>
<form>
<table border="1" align="center">
<u><h5>Size</h5></u>
<tr><td><input type="radio" name="size" id="small" checked="checked" />Small</td></tr>
<tr><td><input type="radio" name="size" id="medium" />Medium</td></tr>
<tr><td><input type="radio" name="size" id="large" />Large</td></tr>
</table>
<br />
<div id="total">$0.00</div>
<script type="text/javascript">
if (document.getElementById('small').checked) {
document.getElementById('total').innerHTML = '$1.00';
}
else {
}
</script>
</form>
</body>
</html>
What I think you really want to do is to attach a "click" EVENT to the radiobutton.
You can read more here:
http://www.w3schools.com/jsref/event_onclick.asp
The reason why you are not getting $1.00 is that - code inside will execute on page load. but what you need is to set the div's value on some event of a radio and NOT ON page load event.
so use your code in some function and call that function on radio button's click event
Here is a working example based on the critical parts of your code: http://jsfiddle.net/9hxDq/
You need to execute your code in response to an event (such as a click, a load event, or in response to an input being clicked)
Some of your markup was invalid (U tag inside of a TABLE)
HTML
<table border="1" align="center">
<tr><td><input type="radio" name="size" id="small" />Small</td></tr>
<tr><td><input type="radio" name="size" id="medium" />Medium</td></tr>
<tr><td><input type="radio" name="size" id="large" />Large</td></tr>
</table>
<input type="button" value="Calculate" onclick="calculate()" />
<div id="total">$0.00</div>
JavaScript
function calculate()
{
if (document.getElementById('small').checked)
{
document.getElementById('total').innerHTML = '$1.00';
}
else
{
alert("not checked!");
}
}
Tie the click event on the radio button to your code via:
var small = document.getElementById('small');
if (small.addEventListener) {
small.addEventListener('click', calc, false);
} else if (small.attachEvent) {
small.attachEvent('onclick', calc);
}
function calc() {
if (document.getElementById('small').checked) document.getElementById('total').innerHTML = '$1.00';
};
jsFiddle example.
The reason it isn't updating is because the script appears in the code before the <div id='total'>. And, more importantly, because the script gets executed immediately when it appears in the page, so it is run before the total element is added to the DOM.
To fix this, you need to either move the script lower in your HTML code, or make the script run only after the page has finished loading. The first of those options is a quick fix to get you up and running; the latter is probably the more recommended option.
To get it to run only after the page has finished loading, wrap it into a function, and use the onload event on the page to trigger it. Alternatively, if you're using JQuery, add it as a $(document).ready() function.
Related
I am new to Javascript (like I really know nothing) and I have to program a Picross game for my school. My teachers gave me an HTML home page for the game and I can't touch it. This page has a form with action pointing on itself but with parameters on the URL. Here is the code :
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
My job is to only work on picross.js and I have no idea how to render a blank page (or a grid) if the form has been submitted because when I try to detect the submit, the HTML page renders just after my catch. I also have to do it on the same page, when no parameters are given it's the home page from my teachers but when the form is submitted, the game opens in the same picross.html but with ?lines=x&cols=y or something like this. Here is what I've tried :
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
console.log("catch");
console.log(e);
}
This writes catch in the console for a tenth of a sencond and then the HTML renders just after. So what I'm looking for is when the form is submitted, the JS code should render a grid (or a blank page, I can work on the grid later) to play the picross game.
Thank for your help
JavaScript is really easy and fun, you can always google anything you want to make and/or learn in javascript/html or any web technology.
As I understood from your question, you want to open a new window when the button is clicked, so to do that you have to first turn off the default behavior of the form, and to do that you can use the parameter e that passed in the event callback submitted.
JavaScript events
e.preventDefault()
This will prevent the page from reloading.
Next, to open a new window, you can use window object.
Window object.
window.open(....)
Full example:
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(e) {
e.preventDefault();
console.log("catch");
var myWindow = window.open("", "Yaay", "width=200,height=100");
myWindow.document.write("<p>Peace begins with a smile</p>");
}
<!doctype html>
<html>
<head>
<title>Picross editor & player</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="picross.css" type="text/css">
<script src="picross.js"></script>
</head>
<body>
<nav>
<section>
<h2>Create a grid</h2>
<form action="picross.html" method="get">
<input type="hidden" name="edit">
<table>
<tr><td>Lignes :</td><td><input type="number" name="lines" value="10" min="5" max="20"></td></tr>
<tr><td>Colonnes :</td><td><input type="number" name="cols" value="10" min="5" max="20"></td></tr>
</table>
<input type="submit" value="Create !">
</form>
</section>
</nav>
</body>
</html>
I hope I explained clearly.
Note: Run code snippet might not work, because popups are not allowed.
How to Call JavaScript function on checkbox click event in Asp.Net MVC
This code is not working
#{
ViewBag.Title = "Employee";
Layout = "~/Views/Shared/_MasterLayout.cshtml";
}
<head>
<script type="text/javascript">
function Myfunction()
{
alert("Hello");
}
</script>
</head>
<body>
<input type="checkbox" id="chk1" onclick="Myfunction()" />
</body>
You should have your js code inside Body tag (at bottom). As Js can't able to get any Dom element as it loaded first Before Whole DOM itself.
Ex :-
<!DOCTYPE html>
<html>
<body>
<h1>Test</h1>
<input type="checkbox" id="chk1" onclick="Myfunction()" />
<script>
function Myfunction()
{
alert("Hello");
}
</script>
</body>
</html>
Also you can use Third party Lib to make productivity Fast
USING ( jQuery )
<input type="checkbox" id="checkbox1" />
$("#checkbox1").click( function(){
// YOUR FUNCTION CODE
});
Just Refer this link,you will get complete idea about it
Hope it helps..Cheers
https://jsfiddle.net/a6cedoj0/
I have a basic table that I am creating from text input and when you click the "addTask" button it adds a tr with an empty text box and clicking the "delTask" button should delete the rows from the table that have checkboxes checked.
Everything works perfectly in JSFiddle (except the line to render last textbox readonly which only works outside of JSFiddle) but when I try to test the code out live the "delTask" button does not work correctly. It will delete all rows except the first one in the table.
I'm fairly new to JQuery so please don't judge if it's something simple but I have really searched for an answer and tried everything I could find. Can anyone help me figure out what is wrong here? Thanks in advance.
EDIT I have fixed the initial issue of the delTask button not working at all by changing $(":checkbox[checked='true']") to $(".checkbox:checked") when testing outside of JSFiddle but still cant get the button to delete the first row on the table in a live test.
JSFiddle link: http://jsfiddle.net/2aLfr794/14/
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td><input type="checkbox"></td>
<td><input type="text" class="text"></td>
</tr>
</table>
<br>
<input type="button" id="addTask" value="Add Task" />
<input type="button" id="delTask" value="Delete Tasks" />
<script>
$("#addTask").click(function(){
var newTxt = $('<tr><td><input type="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$("#delTask").click(function(){
$(".checkbox:checked").each(function(){
var curTask = $(this).parents('tr');
curTask.remove();
});
});
</script>
</body>
</html>
Your Issues:
1.You are not assigning class checkbox to default checkbox and dynamically created checkboxes.
2.To access a checked element the syntax is $(".checkbox[checked='checked']")
Your Updated Code:
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<body>
<table id="tasks" cellpadding="3" cellspacing="3" border="0">
<tr>
<td>
<input type="checkbox" class="checkbox">
</td>
<td>
<input type="text" class="text">
</td>
</tr>
</table>
<br />
<input type="button" id="addTask" value="Add Task" class="addSubmit" />
<input type="button" id="delTask" value="Delete Selected Tasks" />
<script>
$("#addTask").click(function() {
var newTxt = $('<tr><td><input type="checkbox" class="checkbox"></td><td><input type="text" class="text"></td></tr>');
$(".text").last().prop("readonly", true);
$("#tasks").append(newTxt);
});
$(document).ready(function() {
$("#delTask").click(function() {
console.log($(".checkbox[checked='checked']"))
$(".checkbox:checked").each(function() {
var curTask = $(this).parents('tr');
curTask.remove();
});
});
});
</script>
</body>
if you get "$ is not defined" error, try writing
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> as <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Note the "http:" before "//cdnjs" which is needed when you are running those from local machine, and not a webserver. At least it was always required for me.
$("input[type=checkbox]:checked")
worked for me
I have a script where I use checkboxes and javascript to display additional items if the checkboxes are checked.
This seems to be working just fine most of the time.
There is one checkbox however that is giving problems.
I assume because of the javascript magic associated with it.
When checking it and then unchecking it, the checkbox always returns isset after post.
Never checking the checkbox and submitting returns not set as it should.
Checking and submitting returns checked as it should
checking, unchecking and submitting returns ... checked!
I have set up an example on http://vampke.uphero.com/tst.php
Here is the code:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
if(isset($_POST['se_currentitem'])) echo "CHECKBOX = ISSET";
else echo "CHECKBOX = NOT SET";
}
echo <<< EOD
<!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>test</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<style type="text/css">
.hiddenDiv {display: none;}
.visibleDiv{display: block;}
</style>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
var currentitem = 0;
function toggle_currentitem(){
mydiv = document.getElementById("currentitemcontainer");
if (document.getElementById('se_currentitem').checked){
mydiv.className = "visibleDiv";
if(currentitem==0){
addcurrentitem();
}
}
else {
mydiv.className = "hiddenDiv";
}
}
function addcurrentitem(){
currentitem++;
var newitem = document.createElement('div');
newitem.id = currentitem;
newitem.innerHTML= "<p><strong><em>new item</em></strong><br /><label>select a number:</label><select name='se_currentitem[]'><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option></select></p>";
document.getElementById('currentitem').appendChild(newitem);
}
//-->
</script>
<form action ="" method="post">
<input type="checkbox" id="se_currentitem" name="se_currentitem" value="1" onchange="toggle_currentitem()" /><label for="se_currentitem">click the checkbox to activate the items</label> <br />
<div id="currentitemcontainer" class="hiddenDiv">
<div id="currentitem"></div>
<a id='addnewcurrent' onclick='addcurrentitem()'>add item</a>
</div>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
does anyone know what's going on?
The checkbox is named se_currentitem and the select menu is named se_currentitem[]. PHP's $_POST array treats these as the same.
When you check the box, you create the select menu.
When you uncheck the box, you hide the select menu, but it remains in the DOM, and is submitted by the browser. Notice in the Network inspector (or tcpflow, etc.). that the browser submits both se_currentitem and se_currentitem[].
You should rename the checkbox so it is not called se_currentitem (or rename the select menu so it is not called se_currentitem[]).
I must be missing something obvious here... I can't get .change() to fire on radio buttons? I have the code below live here!
<!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>Radio Button jQuery Change</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
console.log("parsed");
$("input[name='rdio']").change(function() {
console.log("changed");
if ($("input[name='rdio']:checked").val() == 'a')
$("output").text("a changed");
else if ($("input[name='rdio']:checked").val() == 'b')
$("output").text("b changed");
else
$("output").text("c changed");
});
</script>
</head>
<body>
<div>
<input type="radio" name="rdio" value="a" checked="checked" /> a <br/>
<input type="radio" name="rdio" value="b" /> b <br/>
<input type="radio" name="rdio" value="c" /> c
</div>
<h3>Output:</h3>
<div id="output"></div>
</body>
</html>
Can anyone see what I've missed?
Thanks,
Denis
You must put the code inside the dom-ready event...
$(document).ready(function(){
// Your code here
});
or else the script gets executed before the HTML-elements have been loaded. Thus, no radioboxes exist.
Your
$("output").text("a changed");
should also be
$("#output").text("a changed");
because it is an id you are matching against.