Checkbox Images - javascript

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>

Related

Find input value in other input fields

I need to check and find if a value of the current input field is found in other input fields on the page.
$(document).on("keyup", "input.card-label", function(){
var ths = $(this),
par = ths.closest(".inputContainer"),
val = ths.val();
if (ths.closest(".allInput").find("input.card-label").val() != val) {
par.removeClass("dupe");
} else {
par.addClass("dupe");
fle.prop("disabled", true);
}
});
I seem to have a partial success. When I edit a value that's a duplicate, the "dupe" class is removed, but when I intentionally enter a duplicate value, the "dupe" class is not added. What am I missing?
If I understand correctly, you want a class added when the value of an input is the same as the value of another input. The following code adds the keyup event to any input, then loops over all other inputs to determine if the current input's value is a duplicate, in which case it adds a CSS class.
I have gone for simplicity and just used the input selector. You should be able to tailor this to your needs.
$(function () {
$('input').on('keyup', function (e) {
// reference to this input
var input = $(e.currentTarget)
// get all inputs which are not this input
var allInputs = $('input').not(this)
// loop through all other inputs
for (var i = 0; i < allInputs.length; ++i) {
// if another input's value is the same as this, add the class
if ($(allInputs[i]).val() == input.val()) {
input.addClass('dup')
} else { // otherwise remove it (if it exists)
input.removeClass('dup')
}
}
})
})
.dup {
border-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />
<input type="text" />

Using javascript conditions to hide elements

In this code, I have two elements; an input box with id 'alpha' and a paragraph with id 'bravo'. What I'm trying to do is make bravo invisible when there is nothing in the input box alpha.
Here is what I have so far:
<html>
<head>
<script>
var a = document.getElementById("alpha");
var b = document.getElementById("bravo");
window.onload = function hidebravo() {
if (a.value == nil) {b.style.visibility = "hidden";}
}
a.onchange = function hidebravo() {
if (a.value == nil) {b.style.visibility = "hidden";}
}
</script>
</head>
<body>
<input id="alpha"/>
<p id="bravo">Hello!</p>
</body>
</html>
For sake of clarity, I have set the variables 'a' and 'b' to correspond to the JS selectors for the input box and the paragraph, respectively.
Now, as soon as the window is loaded I call the function 'hidebravo()' which is the function that makes bravo invisible if input box alpha is empty. I call the same function whenever the user changes the value of alpha, in case alpha contains a value which the user then deletes and it becomes empty once again.
But, for whatever reason, this isn't working as it should and I can't figure out why.
Please help!
You should use null instead of nil in Javascript.
Here's the code that works, without window.onload function:
JS:
function reloadBravo() {
var bravoParagraph = document.getElementById('bravo');
var alphaTextBox = document.getElementById('alpha');
var alphaText = alphaTextBox.value;
if (alphaText.length > 0) {
bravoParagraph.innerHTML = alphaText;
bravoParagraph.style.visibility = 'visible';
} else {
bravoParagraph.innerHTML = '';
bravoParagraph.style.visibility = 'hidden';
}
}
HTML:
<html>
<head>
</head>
<body>
<input id="alpha" onkeyup="reloadBravo()"/>
<p id="bravo"></p>
</body>
</html>
This help you :
<html>
<head>
</head>
<body>
<input id="alpha"/>
<p id="bravo">Hello!</p>
<script>
var a = document.getElementById("alpha");
var b = document.getElementById("bravo");
window.onload = function hidebravo() {
if (a.value == "")
b.style.visibility = "hidden";
else
b.style.visibility = "visible";
}
a.oninput = function hidebravo() {
if (a.value == "")
b.style.visibility = "hidden";
else
b.style.visibility = "visible";
}
</script>
</body>
</html>
JavaScript doesn't have special nil value. There is null. But the .value property of the HTMLInputElement is a DOMString and can't be null. You need to check the .length property of the DOMString. length of 0 indicates that there is no set value.
if (a.value.length === 0) { ... }
Note that as an space and a tab is considered a character, you need to trim the value for checking whether user has typed any visible characters or not:
if (a.value.trim().length === 0) { ... }
But that's not the only problem. load event is fired once and your code doesn't check the current value of the inputs. You should add an event handler for keyup/input/change/paste/... events fired for the input elements.
a.addEventListener('keyup', hidebravo);
b.addEventListener('keyup', hidebravo);

make an anchor toggle function which appends data to textarea on click and removes on reclick

i m trying to make an anchor toggle function which appends data to textarea on click and removes on reclick. here is the jsfiddle.
`
function btnsInit()
{
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i)
{
var str=document.getElementById('ta').value;
var index= str.indexOf(a[i]);
if(index!=-1)
{
a[i].onclick = btnClick;
}
else
{
str.replace(a[i],"_");
}
}
}
function btnClick(e)
{
document.getElementById('ta').value += this.firstChild.nodeValue + ',';
xPreventDefault(e);
return false;
}
`Please reply ASAP
Here is new js code, you can use it -
<div id='btns'>
<p>
<!-- adding id to element, helps to maintain the list
of element which have been clicked, and also helps in
distinguishing between two elements have same text.
Dont forget to add href="#' or href="javascript:void(0)"
else your page may refresh and form data will be lost -->
<a id="a1" href='#'>category</a>
</p>
<p>
<a id="a2" href='#'>url</a>
</p>
</div>
<textarea id='ta' rows='10' cols='20'></textarea></body>
Javascript -
window.onload = btnsInit;
var selected = {};//keeps list of selected links
function btnsInit() {
var i, a = document.getElementById('btns').getElementsByTagName('a');
for (i = 0; i < a.length; ++i) {
a[i].onclick = btnClick;
}
}
function btnClick(e) {
if (selected[this.id]) {
delete selected[this.id];//deleting if already been clicked
} else {
selected[this.id] = this.innerHTML;//adding to the selected list
}
updateTextArea();
xPreventDefault(e);
return false;
}
function updateTextArea() {
var ta = document.getElementById('ta');
var val = "";
for ( var id in selected) {
val += selected[id] + ",";
}
ta.value = val;//updating from selected list
}
function xPreventDefault(e) {
if (e && e.preventDefault)
e.preventDefault();
else if (window.event)
window.event.returnValue = false;
}
Problems with your code -
btnsInit was not actually assigning onclick listeners to <a> elements.
Re click on a link was not handled or not handled properly(if handled).
Use attribute/value href=' ' for a tag which is refreshing the page.
Update - questions asked in comments
Was my code not working as it was refreshing the page?
No, It was not. It was missing reclick handling and btnsInit was not working properly.
Is delete a predefined function?
delete is a JavaScript keyword, which delete an object property.
About delete keyword
What is the use of 'this'?
this is another keyword which holds the reference of the object in context, in this case it holds the element clicked.
More about this keyword

Show button if input is not empty

I am not much of a JavaScript guru, so I would need help with a simple code.
I have a button that clears the value of an input field.
I would like it (the button) to be hidden if input field is empty and vice versa (visible if there is text inside the input field).
The solution can be pure JavaScript or jQuery, it doesn't matter. The simpler, the better.
$("input").keyup(function () {
if ($(this).val()) {
$("button").show();
}
else {
$("button").hide();
}
});
$("button").click(function () {
$("input").val('');
$(this).hide();
});
http://jsfiddle.net/SVxbW/
if(!$('input').val()){
$('#button').hide();
}
else {
$('#button').show();
}
In it's simplest form ;)
to do this without jQuery (essentially the same thing others already did, just pure js). It's pretty simple, but I've also added a few comments.
<body>
<input type="text" id="YourTextBox" value="" />
<input type="button" id="YourButton" value="Click Me" />
<script type="text/javascript">
var textBox = null;
var button = null;
var textBox_Change = function(e) {
// just calls the function that sets the visibility
button_SetVisibility();
};
var button_SetVisibility = function() {
// simply check if the visibility is set to 'visible' AND textbox hasn't been filled
// if it's already visibile and the text is blank, hide it
if((button.style.visibility === 'visible') && (textBox.value === '')) {
button.style.visibility = 'hidden';
} else {
// show it otherwise
button.style.visibility = 'visible';
}
};
var button_Click = function(e) {
// absolutely not required, just to add more to the sample
// this will set the textbox to empty and call the function that sets the visibility
textBox.value = '';
button_SetVisibility();
};
// wrap the calls inside anonymous function
(function() {
// define the references for the textbox and button here
textBox = document.getElementById("YourTextBox");
button = document.getElementById("YourButton");
// some browsers start it off with empty, so we force it to be visible, that's why I'll be using only chrome for now on...
if('' === button.style.visibility) { button.style.visibility = 'visible'; }
// assign the event handlers for the change and click event
textBox.onchange = textBox_Change;
button.onclick = button_Click;
// initialize calling the function to set the button visibility
button_SetVisibility();
})();
</script>
</body>​
Note: I've written and tested this in IE9 and Chrome, make sure you test it in other browsers. Also, I've added this fiddle so you can see it working.
You can use $('selector').hide() to hide an element from view and $('selector').show() to display it again.
Even better, you can use $('selector').toggle() to have it show and hide without any custom logic.
First hide the button on page load:
jQuery(document).ready(function() {
jQuery("#myButton").hide();
});
Then attach an onChange handler, which will hide the button whenever the contents of the text-field are empty. Otherwise, it shows the button:
jQuery("#myText").change(function() {
if(this.value.replace(/\s/g, "") === "") {
jQuery("#myButton").hide();
} else {
jQuery("#myButton").show();
}
});
You will also need to hide the button after clearing the input:
jQuery("#myButton").click(function() {
jQuery("#myInput").val("");
jQuery(this).hide();
});

Compare onclick action of two html button using javascript

I have this two HTML Form buttons with an onclick action associated to each one.
<input type=button name=sel value="Select all" onclick="alert('Error!');">
<input type=button name=desel value="Deselect all" onclick="alert('Error!');">
Unfortunately this action changes from time to time. It can be
onclick="";>
or
onclick="alert('Error!');"
or
onclick="checkAll('stato_nave');"
I'm trying to write some javascript code that verifies what is the function invoked and change it if needed:
var button=document.getElementsByName('sel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
if( button.getAttribute("onclick") != "checkAll('stato_nave');" &&
button.getAttribute("onclick") != ""){
//modify button
document.getElementsByName('sel')[0].setAttribute("onclick","set(1)");
document.getElementsByName('desel')[0].setAttribute("onclick","set(0)");
} //set(1) and set(0) being two irrelevant function
Unfortunately none of this work.
Going back some steps I noticed that
alert( document.getElementsByName('sel')[0].onclick);
does not output the onclick content, as I expected, but outputs:
function onclick(event) {
alert("Error!");
}
So i guess that the comparisons fails for this reason, I cannot compare a function with a string.
Does anyone has a guess on how to distinguish which function is associated to the onclick attribute?
This works
http://jsfiddle.net/mplungjan/HzvEh/
var button=document.getElementsByName('desel')[0];
// I don't want to change it when it is empty or calls the 'checkAll' function
var click = button.getAttribute("onclick");
if (click.indexOf('error') ) {
document.getElementsByName('sel')[0].onclick=function() {setIt(1)};
document.getElementsByName('desel')[0].onclick=function() {setIt(0)};
}
function setIt(num) { alert(num)}
But why not move the onclick to a script
window.onload=function() {
var button1 = document.getElementsByName('sel')[0];
var button2 = document.getElementsByName('desel')[0];
if (somereason && someotherreason) {
button1.onclick=function() {
sel(1);
}
button2.onclick=function() {
sel(0);
}
}
else if (somereason) {
button1.onclick=function() {
alert("Error");
}
}
else if (someotherreason) {
button1.onclick=function() {
checkAll('stato_nave')
}
}
}
Try casting the onclick attribute to a string. Then you can at least check the index of checkAll and whether it is empty. After that you can bind those input elements to the new onclick functions easily.
var sel = document.getElementsByName('sel')[0];
var desel = document.getElementsByName('desel')[0];
var onclick = sel.getAttribute("onclick").toString();
if (onclick.indexOf("checkAll") == -1 && onclick != "") {
sel.onclick = function() { set(1) };
desel.onclick = function() { set(0) };
}
function set(number)
{
alert("worked! : " + number);
}
working example: http://jsfiddle.net/fAJ6v/1/
working example when there is a checkAll method: http://jsfiddle.net/fAJ6v/3/

Categories

Resources