Need to run a function based on conditional - javascript

I'm trying to assign a function to a couple of checkboxes, but I only want them added based on a condition, in this case the step number of the form. This is a roundabout way of making the checkboxes readOnly AFTER they have been selected (or not). So, at step 1 I want the user to choose cb1 or cb2, but at step 2 I want to assign the function that will not let the checkboxes values be changed.
What am I doing wrong?
function functionOne() {
this.checked = !this.checked
};
if (document.getElementById("stepNumber").value == 2) {
document.getElementById("cb1").setAttribute("onkeydown", "functionOne(this)");
document.getElementById("cb2").setAttribute("onkeydown", "functionOne(this)");
}

You are passing the element in an argument, so use that:
function functionOne(elem) {
elem.checked = !elem.checked
};
You could also use properties:
document.getElementById("cb1").onkeydown = functionOne;
document.getElementById("cb2").onkeydown = functionOne;
function functionOne() {
this.checked = !this.checked
};

This is a solution that requires jquery but you can use the .click function to disable checkboxes once one is clicked.
Here is a working example:
http://jsfiddle.net/uPsm7/

Why not on the selection disable the checkbox?
Function onCheck(elm)
{
document.getElementById("cbValue").value = elm.value;
elm.disabled = true;
}
<input id="cbValue" type="hidden" />
Use the hidden input field to allow form to send data back to server.

Related

How can I apply localStorage to input checkbox?

Note: I'm using vanilla js only.
I currently have a working script to add/remove classes via select options as well localStorage. All works great, see jsfiddle here.
Now, I'm wanting to add two checkbox's to perform in the same way. My problem is I'm not sure how to add checkboxes to my current localStorage script.
Here are my checkbox's:
<input type="checkbox" name="checkbox1" id="checkbox1" onchange="checkbox1(this)">
<input type="checkbox" name="checkbox2" id="checkbox2" onchange="checkbox2(this)">
And add/remove class on check/uncheck for checkbox1:
var checkbox = document.getElementById('checkbox1');
checkbox.addEventListener("change", checkbox1, false);
function checkbox1() {
var isChecked = checkbox.checked;
if (isChecked) {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.add('classname');
});
} else {
[].map.call(document.querySelectorAll('body,.nc,.tags'), function(el) {
el.classList.remove('classname');
});
}
}
Works fine. Now I just need to add it to localStorage.
Here's my localStorage script that works for my select options (full example in my jsfiddle). How do I modify it to work for my checkbox's as well? I'm assuming I have to modify the second line to check for checkbox instead of options but I'm not sure how.
function selectTest(element) {
const a = element.options[element.selectedIndex].value;
setTest(a);
localStorage['test'] = a;
}
function setTest(a) {
if (a == "option1") {
//add+remove classes here
}
}
(function() {
if (localStorage['test'])
document.getElementById("test").value = localStorage['test'];
setTest(localStorage['test'])
})();
Here is the JS Fiddle if you just directly want to see the code https://jsfiddle.net/qctn08ym/44/
The idea is that since multiple checkboxes can be ticked and we need to preserve that we can store it as an array. Note that you can only store string in localStorage so you would need to convert the array to string and vice versa.
On any checkbox value changed we can call the function below that will set the localstorage
function checkboxChanged(e) {
//Get the id of all checked checkboxes and store them as array
// You can do this in loop as well by setting common class on checkboxes
var c = []
if(document.getElementById('checkbox1').checked) {
c.push('checkbox1');
}
if(document.getElementById('checkbox2').checked) {
c.push('checkbox2');
}
localStorage['test'] = c.toString();
}
Then you can just call the function below on document load
function checkOnLocalStorage() {
if(!localStorage['test']) return;
var checked = localStorage['test'].split(',');
checked.map((id) => {
document.getElementById(id).checked=true;
})
}

catch input on change event with javascript

First of all, I'm using this function:
jQuery(document).on('propertychange change click keyup input paste', 'input[name="wager_id_111"]', function(){
var thisValue = jQuery(this).val();
var amountReal = jQuery('.amount_visible');
if ( thisValue != '' ){
var amount_in_btc = thisValue / 1000;
amount_in_btc = amount_in_btc.toFixed(5);
amount_in_btc = parseFloat(amount_in_btc);
amountReal.show(1, function(){
amountReal.find('span').html('= ' + amount_in_btc);
});
} else {
amountReal.hide();
}
});
and it works when user types amount it the input. The problem is, when input value is being changed via code, so I can't detect it was changed. Becouse there is buttons how much amount add to input (like 1, 10, 50, 100) and when users selects one of those, input value is being changed jQuery('input[name="wager_id_111"]').val(newVal); but as I said the function I showed below can't catch this. What the option would be to make it work?
Fiddle:
fiddle link
you can add this line of code: $('input[name="wager_id_111"]').trigger('change'); to your .click() function
demo: http://jsfiddle.net/et3gsf9w/1/
The solution is to place the code that operates the input value into a function, and call it two times, one when the event is raised and the other one via code.

How to know with jQuery that a "select" input value has been changed?

I know that there is the change event handling in jQuery associated with an input of type select. But I want to know if the user has selected another value in the select element ! So I don't want to run code when the user select a new element in the select but I want to know if the user has selected a different value !
In fact there are two select elements in my form and I want to launch an ajax only when the two select elements has been changed. So how to know that the two elements has been changed ?
You can specifically listen for a change event on your chosen element by setting up a binding in your Javascript file.
That only solves half your problem though. You want to know when a different element has been selected.
You could do this by creating a tracking variable that updates every time the event is fired.
To start with, give your tracking variable a value that'll never appear in the dropdown.
// Hugely contrived! Don't ship to production!
var trackSelect = "I am extremely unlikely to be present";
Then, you'll need to set up a function to handle the change event.
Something as simple as:-
var checkChange = function() {
// If current value different from last tracked value
if ( trackSelect != $('#yourDD').val() )
{
// Do work associated with an actual change!
}
// Record current value in tracking variable
trackSelect = $('#yourDD').val();
}
Finally, you'll need to wire the event up in document.ready.
$(document).ready(function () {
$('#yourDD').bind('change', function (e) { checkChange() });
});
First of all you may use select event handler (to set values for some flags). This is how it works:
$('#select').change(function () {
alert($(this).val());
});​
Demo: http://jsfiddle.net/dXmsD/
Or you may store the original value somewhere and then check it:
$(document).ready(function () {
var val = $('#select').val();
...
// in some event handler
if ($('#select').val() != val) ...
...
});
First you need to store previous value of the selected option, then you should check if new selected value is different than stored value.
Check out the sample!
$(document).ready(function() {
var lastValue, selectedValue;
$('#select').change(function() {
selectedValue = $(this).find(':selected').val();
if(selectedValue == lastValue) {
alert('the value is the same');
}
else {
alert('the value has changed');
lastValue = selectedValue;
}
});
});​
You can save the value on page load in some hidden field.
like
$(document).ready(function(){
$('hiddenFieldId').val($('selectBoxId').val());
then on change you can grab the value of select:
});
$('selectBoxId').change(function(){
var valChng = $(this).val();
// now match the value with hidden field
if(valChng == $('hiddenFieldId').val()){
}
});
$("select").change(function () {
var str = "";
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("div").text(str);
})
.change();
http://docs.jquery.com/Events/change

Check/Uncheck checkbox with JavaScript

How can a checkbox be checked/unchecked using JavaScript?
Javascript:
// Check
document.getElementById("checkbox").checked = true;
// Uncheck
document.getElementById("checkbox").checked = false;
jQuery (1.6+):
// Check
$("#checkbox").prop("checked", true);
// Uncheck
$("#checkbox").prop("checked", false);
jQuery (1.5-):
// Check
$("#checkbox").attr("checked", true);
// Uncheck
$("#checkbox").attr("checked", false);
Important behaviour that has not yet been mentioned:
Programmatically setting the checked attribute, does not fire the change event of the checkbox.
See for yourself in this fiddle:
http://jsfiddle.net/fjaeger/L9z9t04p/4/
(Fiddle tested in Chrome 46, Firefox 41 and IE 11)
The click() method
Some day you might find yourself writing code, which relies on the event being fired. To make sure the event fires, call the click() method of the checkbox element, like this:
document.getElementById('checkbox').click();
However, this toggles the checked status of the checkbox, instead of specifically setting it to true or false. Remember that the change event should only fire, when the checked attribute actually changes.
It also applies to the jQuery way: setting the attribute using prop or attr, does not fire the change event.
Setting checked to a specific value
You could test the checked attribute, before calling the click() method. Example:
function toggle(checked) {
var elm = document.getElementById('checkbox');
if (checked != elm.checked) {
elm.click();
}
}
Read more about the click method here:
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/click
to check:
document.getElementById("id-of-checkbox").checked = true;
to uncheck:
document.getElementById("id-of-checkbox").checked = false;
We can checked a particulate checkbox as,
$('id of the checkbox')[0].checked = true
and uncheck by ,
$('id of the checkbox')[0].checked = false
Try This:
//Check
document.getElementById('checkbox').setAttribute('checked', 'checked');
//UnCheck
document.getElementById('chk').removeAttribute('checked');
I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.
So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.
Using vanilla js:
//for one element:
document.querySelector('.myCheckBox').checked = true //will select the first matched element
document.querySelector('.myCheckBox').checked = false//will unselect the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
//iterating over all matched elements
checkbox.checked = true //for selection
checkbox.checked = false //for unselection
}
function setCheckboxValue(checkbox,value) {
if (checkbox.checked!=value)
checkbox.click();
}
<script type="text/javascript">
$(document).ready(function () {
$('.selecctall').click(function (event) {
if (this.checked) {
$('.checkbox1').each(function () {
this.checked = true;
});
} else {
$('.checkbox1').each(function () {
this.checked = false;
});
}
});
});
</script>
For single check try
myCheckBox.checked=1
<input type="checkbox" id="myCheckBox"> Call to her
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
Buy wine: <input type="checkbox" class="imChecked"><br>
Play smooth-jazz music: <input type="checkbox"><br>
Shave: <input type="checkbox" class="imChecked"><br>
If, for some reason, you don't want to (or can't) run a .click() on the checkbox element, you can simply change its value directly via its .checked property (an IDL attribute of <input type="checkbox">).
Note that doing so does not fire the normally related event (change) so you'll need to manually fire it to have a complete solution that works with any related event handlers.
Here's a functional example in raw javascript (ES6):
class ButtonCheck {
constructor() {
let ourCheckBox = null;
this.ourCheckBox = document.querySelector('#checkboxID');
let checkBoxButton = null;
this.checkBoxButton = document.querySelector('#checkboxID+button[aria-label="checkboxID"]');
let checkEvent = new Event('change');
this.checkBoxButton.addEventListener('click', function() {
let checkBox = this.ourCheckBox;
//toggle the checkbox: invert its state!
checkBox.checked = !checkBox.checked;
//let other things know the checkbox changed
checkBox.dispatchEvent(checkEvent);
}.bind(this), true);
this.eventHandler = function(e) {
document.querySelector('.checkboxfeedback').insertAdjacentHTML('beforeend', '<br />Event occurred on checkbox! Type: ' + e.type + ' checkbox state now: ' + this.ourCheckBox.checked);
}
//demonstration: we will see change events regardless of whether the checkbox is clicked or the button
this.ourCheckBox.addEventListener('change', function(e) {
this.eventHandler(e);
}.bind(this), true);
//demonstration: if we bind a click handler only to the checkbox, we only see clicks from the checkbox
this.ourCheckBox.addEventListener('click', function(e) {
this.eventHandler(e);
}.bind(this), true);
}
}
var init = function() {
const checkIt = new ButtonCheck();
}
if (document.readyState != 'loading') {
init;
} else {
document.addEventListener('DOMContentLoaded', init);
}
<input type="checkbox" id="checkboxID" />
<button aria-label="checkboxID">Change the checkbox!</button>
<div class="checkboxfeedback">No changes yet!</div>
If you run this and click on both the checkbox and the button you should get a sense of how this works.
Note that I used document.querySelector for brevity/simplicity, but this could easily be built out to either have a given ID passed to the constructor, or it could apply to all buttons that act as aria-labels for a checkbox (note that I didn't bother setting an id on the button and giving the checkbox an aria-labelledby, which should be done if using this method) or any number of other ways to expand this. The last two addEventListeners are just to demo how it works.
I agree with the current answers, but in my case it does not work, I hope this code help someone in the future:
// check
$('#checkbox_id').click()

Change an element's onfocus handler with Javascript?

I have a form that has default values describing what should go into the field (replacing a label). When the user focuses a field this function is called:
function clear_input(element)
{
element.value = "";
element.onfocus = null;
}
The onfocus is set to null so that if the user puts something in the field and decides to change it, their input is not erased (so it is only erased once). Now, if the user moves on to the next field without entering any data, then the default value is restored with this function (called onblur):
function restore_default(element)
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
It just so happened that the default values were the names of the elements so instead of adding an ID, I just manipulated the name property. The problem is that if they do skip over the element then the onfocus event is nullified with clear_input but then never restored.
I added
element.onfocus = "javascript:clear_input(this);";
In restore_default function but that doesn't work. How do I do this?
Use
element.onfocus = clear_input;
or (with parameters)
element.onfocus = function () {
clear_input( param, param2 );
};
with
function clear_input () {
this.value = "";
this.onfocus = null;
}
The "javascript:" bit is unnecessary.
It looks like you don't allow the fields to be empty, but what if the user puts a single or more spaces in the field? If you want to prevent this, you need to trim it. (See Steven Levithans blog for different ways to trim).
function trim(str) {
return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}
If you really want to capitalize the strings you could use:
function capitalize(str) {
return str.substr(0, 1).toUpperCase() + str.substr(1).toLowerCase();
}
By clearing the onfocus event you have created a problem that should not have been there. An easier solution is to just add an if-statement to the onfocus event, so it only clears if it is your default value (but I prefer to select it like tvanfosson suggested).
I assume that you on your input-elements have set the value-property so that a value is shown in the input-elements when the page is displayed even if javascript is disabled. That value is available as element.defaultValue. Bonuses by using this approach:
You only define the default value in one place.
You no longer need to capitalize any value in your handlers.
The default value can have any case (like "John Y McMain")
The default value no longer needs to be the same as the name of the element.
.
function clear_default(element) {
if (trim(element.value) == element.defaultValue ) { element.value = ""; }
}
function restore_default(element) {
if (!trim(element.value).length) { element.value = element.defaultValue;}
}
I would suggest that you handle it a little differently. Instead of clearing the value, why not just highlight it all so that the user can just start typing to overwrite it. Then you don't need to restore the default value (although you could still do so and in the same way if the value is empty). You also can leave the handler in place since the text is not cleared, just highlighted. Use validation to make sure the value is not the original value of the input.
function hightlight_input(element) {
element.select();
}
function restore_default(element) // optional, do we restore if the user deletes?
{
if(element.value == '')
{
element.value = element.name.substring(0, 1).toUpperCase()
+ element.name.substring(1, element.name.length);
}
}
<!-- JavaScript
function checkClear(A,B){if(arguments[2]){A=arguments[1];B=arguments[2]} if(A.value==B){A.value=""} else if(A.value==""){A.value="Search"}}
//-->
<form method="post" action="search.php">
<input type="submit" name="1">
<input type="text" name="srh" Value="Search" onfocus="checkClear(this,'Search')" onblur="checkClear(this,' ')">
</form>

Categories

Resources