jQuery toggle not work when the argument are functions - javascript

I'm trying to use toggle() to complete my click events. In this case, I read the API, and use toggle(function1, function2, ...). But it was weird. The tag a just hide when I click it, rather than execute those functions inside.
Here is my javascript code.
function clickMe(){
$("#lime").toggle(
function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = true;
}
}
},function(){
var names = document.getElementsByName("selectOne");
var len = names.length;
if (len > 0) {
var i = 0;
for (i = 0; i < len; ++i) {
names[i].checked = false;
}
}
}
) ;
}
And here is HTML code.
selectAll
<form>
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
<input type="checkbox" name="selectOne" /><br />
</form>
I'm waiting for the comments. Thanks advance!

This functionality has been removed in jQuery 1.9.
Use this instead (works for older versions too):
$(function ($) {
var inputs = $('input[name=selectOne]');
$("#lime").click(function () {
inputs.prop( 'checked', ! inputs.prop('checked') );
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/
As pointed out by #Andre, if the first is checked by hand, it will then uncheck all. If that's not what you want, use this:
$(function ($) {
var inputs = $('input[name=selectOne]'),
flag = true;
$("#lime").click(function () {
inputs.prop( 'checked', flag );
flag = ! flag;
});
});
Here's the fiddle: http://jsfiddle.net/3GQDU/1/

$(function(){
var check = true;
$("#lime").click(function(){
$('input[name=selectOne]').prop('checked', check);
check = !check;
});
});
By doing this, you won't need the 'onclick' attribute in #lime element. Just remove it, and let jQuery bind the click handler for you. This is usually a good thing, as it separates structure and behaviour.
Edit:
If you need a function that reproduces old jQuery toggle behaviour, here's it:
(function($){
$.fn.toggleHandlers = function(eventType){
var i = 0;
var handlers = $.makeArray(arguments).slice(1);
return this.bind(eventType, function() {
handlers[i].apply(this, arguments);
if(i < handlers.length -1)
i++;
else
i = 0;
});
};
})(jQuery);
The difference from jQuery toggle is that it gets one extra parameter (the first one), that is the event type. So, it works with events other than click. Call it as:
$("#myElement").toggleHandlers('click', handler1, handler2[, handler3]);
See fiddle: http://jsfiddle.net/andreortigao/j9MH2/

Related

Checkbox Images

I am trying to make a checkbox list form with only images and
I have this code from add an image to a html type input check box or radio :
<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';
//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
//get all the input fields on the page
inputs = document.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i<inputs.length; i++) {
//check if the input is a checkbox
if(inputs[i].getAttribute('type') == 'checkbox') {
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set image
img.onclick = new Function('checkClick('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
}
}
}
//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
inputs[i].checked = '';
document.getElementById('checkImage'+i).src=getImageUnchecked(i);
} else {
inputs[i].checked = 'checked';
document.getElementById('checkImage'+i).src=getImageChecked(i);
}
}
function getImageChecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
function getImageUnchecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
}
function startImages() {
}
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
But the images only start displaying after the first click.
Is there any work around I can do to start from the page load ?
I tried with the existing functions but achieved nothing.
you have attached the checkClick() to click event of images but you never actually load the images initially, so for that you will have to call checkClick(i) from for loop.
<html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';
//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
//get all the input fields on the page
inputs = document.getElementsByTagName('input');
//cycle trough the input fields
for(var i=0; i<inputs.length; i++) {
//check if the input is a checkbox
if(inputs[i].getAttribute('type') == 'checkbox') {
//create a new image
var img = document.createElement('img');
//check if the checkbox is checked
if(inputs[i].checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
//set image ID and onclick action
img.id = 'checkImage'+i;
//set image
img.onclick = new Function('checkClick('+i+')');
//place image in front of the checkbox
inputs[i].parentNode.insertBefore(img, inputs[i]);
//hide the checkbox
inputs[i].style.display='none';
checkClick(i);
}
}
}
//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
inputs[i].checked = '';
document.getElementById('checkImage'+i).src=getImageUnchecked(i);
} else {
inputs[i].checked = 'checked';
document.getElementById('checkImage'+i).src=getImageChecked(i);
}
}
function getImageChecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
function getImageUnchecked(input) {
if (input == 0)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
if (input == 1)
return "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
}
function startImages() {
}
</script>
</html>
<head>
</head>
<body>
<input type="checkbox" id="option1" checked/> Test<br>
<input type="checkbox" id="option2" checked/> two<br>
<button onclick="alert('option 1 is checked? ' + document.getElementById('option1').checked
+ 'option 2 is checked? ' + document.getElementById('option2').checked)">Check</button>
<script type="text/javascript">replaceChecks();</script>
</body>
You have a tremendous amount of unnecessary code and were setting initial image values to images that don't exist.
Also, your HTML was not valid (the <html> closing tag must be the last thing in the document).
Additionally, you should not use inline HTML event attributes (onclick, etc.) and instead completely separate your JavaScript from your HTML and follow modern, standards-based coding practices.
Also, unless you expect your HTML to have to be parsed as XML at some point (highly unlikely), you can omit the last slashes in your elements (<input ... /> can just be <input ... >). Along the same lines, you no longer need to specify type="text/javascript" in your script tags.
Below is a cleaned up and modernized working version of your code. Note how much less code there actually is (without the comments, it's really very little code) and how much simpler that code is. Please review the comments in the code for details on what is being done and why.
.hidden { display:none; }
<html>
<head>
<title>Checkbox and Images</title>
</head>
<body>
<input type="checkbox" id="option1" checked> Test<br>
<input type="checkbox" id="option2" checked> two<br>
<button id="btnOutput">Check</button>
<script>
// You should never make global variables as they can collide with other variables
// Instead, create a "scope" of your own to work in with an Immediately Invoked
// function expression (an unnamed function that invokes itself right after being
// declared)
(function(){
// Anything declared inside this function is not accessible outside of it
// Since we know these are the only two image paths needed, we can set them up as
// variables and completely do away with the extra functions that set them.
var imgFalse = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
var imgTrue = "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
// Get references to all the DOM elements you will need and then you don't
// have to scan for them again over and over.
var btnOutput = document.getElementById("btnOutput");
// .getElementsByTagName() returns a "live node" list that causes the DOM
// to be re-scanned for the elements everytime you reference the list.
// Use .querySelectorAll() for better efficiency and turn the node list that
// returns into a proper JavaScript array so that .forEach() can be used to
// iterate the elements later.
var checkboxes =
Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));
// Set up the click event handling function for the button
btnOutput.addEventListener("click", function(){
alert('option 1 is checked? ' + checkboxes[0].checked +
'option 2 is checked? ' + checkboxes[1].checked);
});
// Loop through the checkboxes array
checkboxes.forEach(function(checkbox, index){
// No need to test the input type because this array only contains checkboxes
// create a new image
var img = document.createElement('img');
// Show the right image based on the checked status of the clicked checkbox
if(checkbox.checked) {
img.src = imgTrue;
} else {
img.src = imgFalse;
}
img.id = 'checkImage' + index; // set image ID
img.checked = false;
// Set up image click event handler
img.addEventListener("click", function(){
// Toggle the checked state of the image.
// In JavaScript, the "checked" property is boolean. It has values of true and false,
// not "checked" and "" (those are the values to use in HTML attributes).
this.checked = !this.checked;
if(this.checked) {
img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.png";
} else {
img.src= "https://azooree.com/wp-content/uploads/2017/08/Logomakr_6HaICv.jpg";
}
});
// place image just prior to the checkbox in the DOM
checkbox.parentNode.insertBefore(img, checkbox);
// Hide the checkbox. Use CSS classes instead of inline styles
checkbox.classList.add("hidden");
});
})();
</script>
</body>
</html>

Radio button returning undefined value in javascript

http://jsfiddle.net/jngpjbjm/
Have a look at the fiddle link attached. Radio button value is returning a undefined value. I don't why. Please help with this.
<input type="radio" name="arv" value="1">1
<br>
<input type="radio" name="arv" value="2">2
var radio = document.getElementsByName('arv');
radio[0].addEventListener('click', check());
radio[1].addEventListener('click', check());
function check() {
for (var i = 0; i < radio.length; i++) {
var rcheck = radio[i].checked;
if (!rcheck) {
alert(rcheck.value);
}
}
}
Try this: http://jsfiddle.net/jngpjbjm/3/
It should be:
alert(radio[i].value);
Maybe you need something like this?
function check() {
alert( event.target.value );
}
http://jsfiddle.net/jngpjbjm/9/
I have tried to remove all excessive code from your original script as being unnecessary (kind of), whats left are the bare essentials. thanks #mplungjan
Try this:
var radio = document.getElementsByName('arv');
// here is how to add event listeners like the pros over at MDN
radio[0].addEventListener('click', check, false);
radio[1].addEventListener('click', check, false);
function check(e) {
//simply grab the event by passing it as "e" and capturing its target.value
var rcheck = e.target.value;
alert(rcheck);
}
Use this
var radio = document.getElementsByName('arv');
radio[0].addEventListener('click', check);
radio[1].addEventListener('click', check);
function check() {
for (var i = 0; i < radio.length; i++) {
var rcheck = radio[i].checked;
if (!rcheck) {
alert(radio[i].value);
}
}
}
This version will work in all browsers.
window.onload=function() {
var radios = document.getElementsByName('arv');
for (var i=0;i<radios.length;i++) {
radios[i].onclick=function() {
alert(this.value);
}
}
}
onclick
Because it was essentially part of DOM 0, this method is very widely supported and requires no special cross–browser code; hence it is normally used to register event listeners dynamically unless the extra features of addEventListener() are needed.

Can I use a function to let all checkbox checked or unchecked(not use click trigger)?

I want to use a function to let all checkboxes checked or unchecked,but not use a button click to trigger.How to do it?
<input type="checkbox" name="list" id="checkbox_<%=rs.getString("id")%>" onclick="check_marker(this)" checked="checked" />
You didn't clearify when do you want to that check happen, but there's function for that. It uses for loop for setting checkstate to all checkboxes. You can use it whenever you want in the code.
function checktoggle(state) { // state is true or false(true = checked, false = unchecked)
var boxes = document.getElementsByName('list');
for(var i = 0; i < boxes.length; i++) {
boxes[i].checked = state;
}
}

Setting maxlength of textbox with JavaScript or jQuery

I want to change the maxlength of a textbox with JavaScript or jQuery: I tried the following but it didn't seem to help:
var a = document.getElementsByTagName('input');
for(var i=0; i<a.length; i++) {
if((a[i].type!= 'radio')||(a[i].type!= 'checkbox'))
a[i].maxlength = 5;
}
document.getElementsByTagName('input')[1].maxlength="3";
$().ready(function()
{
$("#inputID").maxlength(6);
});
What am I doing wrong?
Not sure what you are trying to accomplish on your first few lines but you can try this:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
The max length property is camel-cased: maxLength
jQuery doesn't come with a maxlength method by default. Also, your document ready function isn't technically correct:
$(document).ready(function () {
$("#ms_num")[0].maxLength = 6;
// OR:
$("#ms_num").attr('maxlength', 6);
// OR you can use prop if you are using jQuery 1.6+:
$("#ms_num").prop('maxLength', 6);
});
Also, since you are using jQuery, you can rewrite your code like this (taking advantage of jQuery 1.6+):
$('input').each(function (index) {
var element = $(this);
if (index === 1) {
element.prop('maxLength', 3);
} else if (element.is(':radio') || element.is(':checkbox')) {
element.prop('maxLength', 5);
}
});
$(function() {
$("#ms_num").prop('maxLength', 6);
});
without jQuery you can use
document.getElementById('text_input').setAttribute('maxlength',200);
set the attribute, not a property
$("#ms_num").attr("maxlength", 6);
$('#yourTextBoxId').live('change keyup paste', function(){
if ($('#yourTextBoxId').val().length > 11) {
$('#yourTextBoxId').val($('#yourTextBoxId').val().substr(0,10));
}
});
I Used this along with vars and selectors caching for performance and that did the trick ..
For those who are facing problem like me with accepted answer:
$(document).ready(function()
{
$("#ms_num").attr('maxlength','6');
});
You may use on focus instead of ready function:
$(document).on('focus', '#ms_num', function() {
{
$(this).attr('maxlength','6');
});
This will make sure to set the maxlength attribute when the input field is focused or selected.
You can make it like this:
$('#inputID').keypress(function () {
var maxLength = $(this).val().length;
if (maxLength >= 5) {
alert('You cannot enter more than ' + maxLength + ' chars');
return false;
}
});
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>
<head>
<script type="text/javascript">
function SetMaxLength () {
var input = document.getElementById ("myInput");
input.maxLength = 10;
}
</script>
</head>
<body>
<input id="myInput" type="text" size="20" />
</body>

Focus Input Box On Load

How can the cursor be focus on a specific input box on page load?
Is it posible to retain initial text value as well and place cursor at end of input?
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" value = "initial text" />
There are two parts to your question.
1) How to focus an input on page load?
You can just add the autofocus attribute to the input.
<input id="myinputbox" type="text" autofocus>
However, this might not be supported in all browsers, so we can use javascript.
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
2) How to place cursor at the end of the input text?
Here's a non-jQuery solution with some borrowed code from another SO answer.
function placeCursorAtEnd() {
if (this.setSelectionRange) {
// Double the length because Opera is inconsistent about
// whether a carriage return is one character or two.
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
// This might work for browsers without setSelectionRange support.
this.value = this.value;
}
if (this.nodeName === "TEXTAREA") {
// This will scroll a textarea to the bottom if needed
this.scrollTop = 999999;
}
};
window.onload = function() {
var input = document.getElementById("myinputbox");
if (obj.addEventListener) {
obj.addEventListener("focus", placeCursorAtEnd, false);
} else if (obj.attachEvent) {
obj.attachEvent('onfocus', placeCursorAtEnd);
}
input.focus();
}
Here's an example of how I would accomplish this with jQuery.
<input type="text" autofocus>
<script>
$(function() {
$("[autofocus]").on("focus", function() {
if (this.setSelectionRange) {
var len = this.value.length * 2;
this.setSelectionRange(len, len);
} else {
this.value = this.value;
}
this.scrollTop = 999999;
}).focus();
});
</script>
Just a heads up - you can now do this with HTML5 without JavaScript for browsers that support it:
<input type="text" autofocus>
You probably want to start with this and build onto it with JavaScript to provide a fallback for older browsers.
$(document).ready(function() {
$('#id').focus();
});
function focusOnMyInputBox(){
document.getElementById("myinputbox").focus();
}
<body onLoad="focusOnMyInputBox();">
<input type="text" size="25" id="myinputbox" class="input-text" name="input2" onfocus="this.value = this.value;" value = "initial text">
A portable way of doing this is using a custom function (to handle browser differences) like this one.
Then setup a handler for the onload at the end of your <body> tag, as jessegavin wrote:
window.onload = function() {
document.getElementById("myinputbox").focus();
}
very simple one line solution:
<body onLoad="document.getElementById('myinputbox').focus();">
Working fine...
window.onload = function() {
var input = document.getElementById("myinputbox").focus();
}
Try:
Javascript Pure:
[elem][n].style.visibility='visible';
[elem][n].focus();
Jquery:
[elem].filter(':visible').focus();
This is what works fine for me:
<form name="f" action="/search">
<input name="q" onfocus="fff=1" />
</form>
fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.
<body onload="if(!this.fff)document.f.q.focus();">
<!-- ... the rest of the page ... -->
</body>
From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html
If you can't add to the BODY tag for some reason, you can add this AFTER the Form:
<SCRIPT type="text/javascript">
document.yourFormName.yourFieldName.focus();
</SCRIPT>
Add this to the top of your js
var input = $('#myinputbox');
input.focus();
Or to html
<script>
var input = $('#myinputbox');
input.focus();
</script>

Categories

Resources