About scope in JavaScript - javascript

When I change the first checkbox, I want to change the var theSame, but it seems it doesn't change in if(theSame == 1);
but it changes in alert("b"+theSame). How to handle this?
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
var theSame = 1;
$("input[name='thesame']").change(function(){
theSame = $(this).is(":checked") ? 1 : 0;
alert("a"+theSame);
});
if(theSame == 1){
$(".check_list input").change(function(){
alert("b"+theSame);
});
}
});
</script>
</head>
<body>
<input type="checkbox" name="thesame">same
<br>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="son">ppp
<input type="checkbox" name="son">ppp
</div>
</body>
</html>
thank you,this what i want to achieve:
<!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>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("input[name='thesame']").change(function(){
var theSame = this.checked ? 1 : 0;
show(theSame)
});
function show(i){
if(i == 1){
$(".check_list input").change(function(){
var inputName = $(this).attr("name");
$("input[name=" + inputName + "]").attr("checked",this.checked)
});
}else{
$(".check_list input").unbind("change")
}
}
});
</script>
</head>
<body>
<input type="checkbox" name="thesame" class="check-all">same
<br>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
<hr>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
<hr>
<div class="check_list">
<input type="checkbox" name="son">ppp
<input type="checkbox" name="sister">ppp
<input type="checkbox" name="dog">ppp
</div>
</body>
</html>

This is not really a question of scope, but more of asynchrony. Let's step through your code:
$(document).ready(function(){
// Define function-scope variable `theSame`, assign it a value of `1`
var theSame = 1;
// Bind a `change` event handler to an element, this function will run later!
$("input[name='thesame']").change(function(){
theSame = +this.checked;
alert("a"+theSame);
});
// At this point, `theSame` has not changed from its original value!
if(theSame == 1){
$(".check_list input").change(function(){
// Here, however, `theSame` may have had its value changed
alert("b"+theSame);
});
}
});
So, as you can see, when the if statement runs it will always have a value of 1, because the value isn't changed until later, after this code has already been executed.
If you move the if statement to inside the event handler, you'll see different results:
$(".check_list input").change(function(){
if(theSame){
alert("b"+theSame);
}
});
Here, you'll only see the alert if theSame is 1.

Related

Using a checkbox to select files to be printed

I am trying to check on a checkbox to select one, many or all and send them to be printed when the user clicks on the "print me" button. I am lost on this one, has anyone done anything similar that I can see how it can be done right? Here is my test code for my issue.
<!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" />
<title>Select and Print</title>
<script src="/jquery-1.11.min.js"></script>
<script>
$(document).ready(function() {
$('#selecctall').click(function(event) {
if(this.checked) {
$('.checkbox1').each(function() {
this.checked = true; // select all checkboxes with class "checkbox1"
printDoc(docUrl);
});
}else{
$('.checkbox1').each(function() {
this.checked = false; // deselect all checkboxes with class "checkbox1"
});
}
});
});
function printDoc(gotUrl) {
var doc = window.open(gotUrl);
doc.print();
doc.close();
}
</script>
</head>
<body><form action="doit.pl" method="post">
</br>
<input type="checkbox" id="selecctall"/> Select All
<input class="checkbox1" type="checkbox" name="check[]" value="names.html"></br>
<input class="checkbox1" type="checkbox" name="check[]" value="copy.html"></br>
<input class="checkbox1" type="checkbox" name="check[]" value="card.html"></br>
<input class="checkbox1" type="checkbox" name="check[]" value="page.html"></br>
<input class="checkbox1" type="checkbox" name="check[]" value="test.html"></br>
<input type="submit" name="print me"></br>
</body></form>
</html>
Thanks for the Help!

How to show an alert box when i finish typing

I have a form like this:
<form id="form1" method="post" action="">
<input maxlength="75" size="90" type="text" id="textfield2"/>
</form>
How to show an alert box message when i finish typing?
Thanks
edit
<!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>
<script type="text/javascript" src="jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function() {
var course_data;
$.get('math.xml', function(data) {
course_data = data;
var that = $('#courses');
$('course', course_data).each(function() {
$('<option>').text($(this).attr('title')).appendTo(that);
});
}, 'xml');
$('#courses').change(function() {
var val = $(this).val();
var that = $('#times').empty();
$('course', course_data).filter(function() {
return val == $(this).attr('title');
})
.find("lesson").each(function() {
$("#lesson").val($(this).text());
});
});
});
</script>
<script type="text/javascript">
function keyPressed(event, input) {
if (event.keyCode == 8) {
return true;
}
var char = event.which ? event.which : event.keyCode;
char = String.fromCharCode(char);
var exerc = ["aaaa aaaa aaaa aaaa","bbbb bbbb bbbb bbbb"];
for (i=0;i<exerc.length;i++){
var option=document.getElementById("courses").selectedIndex;
}
return (exerc[option - 1].charAt(input.value.length) == char);
}
</script>
</head>
<body>
<form name="form1" method="post" action="">
<input type="text" maxlength="70" size="90" id="lesson"/>
</form>
<form name="form2" method="post" action="">
<input maxlength="59" size="90" type="text" onkeypress="return keyPressed(event, this);"/>
</form>
<form name="form1">drop1
<select style="width:100px" id='courses'>
<option selected="selected">choose...</option>
</select>
</form>
</body>
</html>
xml:
<courses>
<course title="chap 1">
<lesson>aaaa aaaa aaaa aaaa</lesson>
</course>
<course title="chap 2">
<lesson>bbbb bbbb bbbb bbbb</lesson>
</course>
</courses>
I have two input fields and i use a keypress function to enter only specific chars in the second input. I can enter until the chars from the first field finished. So, when i finished typing i want to appear an alert message like:
alert(ok finish!);
it is possible?
With JQuery you could do this:
$('#textfield2').bind('blur',function() {
alert('I guess i finished typing cause I left the field!?');
});

Simple jQuery script works fine in Chrome and it fails in Firefox

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/

Set cursor position in an input text field

After a lot of search I found the following threads:
define cursor position in form input field
jQuery Set Cursor Position in Text Area
Unfortunately in none of the posts a complete form embed code or a real example is given. Now I just don't know how to include nemisj's code (on the first link) or Mark's code (on the second link) into my form:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
I wonder if someone could kindly help me with this as I'm badly stuck!
Many thanks in advance!
Here's the edited code, but it still doesn't work:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript" src="http://dev.jquery.com/view/trunk/plugins/validate/jquery.validate.js"></script>
<script>
function setCursor(node,pos){
var node = (typeof node == "string" || node instanceof String) ? document.getElementById(node) : node;
if(!node){
return false;
}else if(node.createTextRange){
var textRange = node.createTextRange();
textRange.collapse(true);
textRange.moveEnd(pos);
textRange.moveStart(pos);
textRange.select();
return true;
}else if(node.setSelectionRange){
node.setSelectionRange(pos,pos);
return true;
}
return false;
}
$(document).ready(function(){
$("#site").focus(function(){
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
});
});
</script>
</head>
<body>
<form action="#" method="post">
<input id="name" type="text" name="name" value="Name" /><br />
<input id="site" type="text" name="mail" value="Website" /><br />
<input type="submit" value="Send">
</form>
</body>
</html>
Inside your <script></script> tag is where your JavaScript goes (although we prefer putting it in a separate file, so that no JavaScript lives on the HTML page itself).
Inside that, you have a call to $(document).ready(), which passes a function() { ... }. Inside that function is all the code that will be executed when your document has loaded.
Inside that function you have a call to $('#site').focus() which itself provides a function — this time one that will be called whenever the #site element gains focus. And presumably that's where you want to change the cursor position.
So, taking the setCursor function from Set cursor at a length of 14 onfocus of a textbox you can put that anywhere in your <script></script> and then inside that innermost function of yours you can write:
if( this.value == this.defaultValue ) {
$(this).val("http://");
var node = $(this).get(0);
setCursor(node,node.value.length);
}
I think I found the error in your setCursor method. The moveStart and moveEnd methods expect two arguments, the first being the unit it should use. Also, the end position appears to be relative to the start position. So I think instead of
textRange.moveEnd(pos);
textRange.moveStart(pos);
you want
textRange.moveStart('character', pos);
textRange.moveEnd('character', 0);
See: http://msdn.microsoft.com/en-us/library/ie/ms536623(v=vs.85).aspx
Oh, this one's easier done than said!
<script>
function setCursorInputPosition(e, pos) {
e.setSelectionRange(pos, pos);
}
</script>
<input onfocus="setCursorInputPosition(this, this.value.length);">

jQuery .change() on Radio Button

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.

Categories

Resources