trying to update object attribute when checkbox is selected - javascript

I have an object with many attributes, one of them is a boolean called "is_mandatory". Whenever an object of this sort is instantiated, "is_mandatory" is initially set to false.
I want to set this attribute to true/false whenever a certain checkbox is clicked.
objectID.is_mandatory = (function() {
$("#checkboxID").change(function() {
if ($("#checkboxID").prop("checked")) {
return true;
} else {
return false;
}
});
})();
I'm new to JavaScript and jQuery. I'm new to front-end development altogether. I've tried many variations of the above code, can't seem to get this work.

use the on change event to update your object.
run snippet below
let myObject = {is_mandatory: false};
$( document ).ready(function() {
render();
$('#container').on('change', '#checkboxID', () => {
myObject.is_mandatory = $('#checkboxID:checked').length ? true : false;
render();
});
});
function render(){
$('#container').empty().append(`<input type="checkbox" id="checkboxID" ${myObject.is_mandatory ? 'checked' : ''}/>`)
console.log(myObject);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
</div>

Have you tried
objectID.is_mandatory = $("#checkboxID").prop("checked");

$(document).on('change','#checkboxID',function(){
var cb = document.getElementById("checkboxID");
myObject.is_mandatory = cb.checked;
});

Basically, "$" is a function that return an jquery object, jquery has several methods in your case "change" method.
"change" method most likely return void since it is actually a shortform of addEventListener("change").
Thus your code need to be modified. instead of returning value. It should access myObject, and set the property manually instead of returning.
or use other method like "prop" which return the value of the DOM Element.

Related

Javascript - Function to use onclick?

I want to create a function and then use with onclick method, for example:
one = document.getElementById("oneID");
then instead of writing function for each onclick():
one.onclick = function(x) {
tempStack.push(parseFloat(one.value));
viewTemp.value += one.value;
}
I want to use a single function:
one.click = input(one);
but I'm not sure how to do it in the correct way for example the below I tried, doesn't work:
var input = function(x) {
tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;
}
Lastly, no external JavaScript libraries to aid this question, vanilla JavaScript.
You'll need to pass a function as a reference, not call it:
one.onclick = input;
In this case you won't be able to pass an argument, but you can use this as a reference for the DOM element on which event is fired:
function input() {
tempStack.push(parseFloat(this.value));
viewTemp.value += this.value;
}
Here's a method with using JavaScript's .addEventListener(), as a previous answer mentioned, using this to pass through the DOM Node Element to use within the inputFunction.
<input type="text" value="64.23" id="bt" />
<script>
function inputFunction( x ) {
console.log( x.value ); //Console Logs 64.23
}
var bt = document.getElementById("bt");
bt.addEventListener( 'click', function(){ inputFunction( this )}, false );
</script>
Fiddle: http://jsfiddle.net/Lhq6t/
Think about functions as a normal objects, so the way is:
function input (event) {
// Process the event...
// event is my event object
// this is the object which trigger the event
// event.target is my button
}
on.onclick = input;
You must assign the input function as a normal variable.
The function input will receive an event object as parameter. Also you can refer to the button clicked with this.
Maybe the mozilla developer network or the real w3c site would explain it better.
Your requirement can be achieved by following:
Add this method in your script tag:
function input(x) {
/*tempStack.push(parseFloat(x.value));
viewTemp.value += x.value;*/
alert(x.id);
}
And then call this method onClick event of your buttons / anchors like:
<input type="button" id="oneID" value="oneID" onClick="input(this);"/>
<input type="button" id="twoID" value="twoID" onClick="input(this);"/>
threeID
See working example: http://jsfiddle.net/Avd5U/1/
ok, so just create a function with a parameter in it like:
function setValue(input){
tempStack.push(parseFloat(input.value));
viewTemp.value += input.value;
}
and then call the function on the click of that element like:
var one = document.getElementById("oneID");
one.click = setValue(one);
Good luck!

How Store and Disable Event of another element Temporary

I am looking for a way to manage the events. I have a hover function for element A, and click function for element B. I want to disable A`s hover function temporary while the second click of B.
I am looking for a way that not necessary to rewrite the hole function of A inside of B. Something very simply just like "Store and Disable Event, Call Stored Function"
I found some technique like .data('events') and console.log. I tired but failed, or maybe I wrote them in a wrong way.
Please help and advice!
$(A).hover();
$(b).click(
if($.hasData($(A)[0])){ // if A has event,
//STORE all the event A has, and disable
}else{
//ENABLE the stored event for A
}
);
Try this
var hoverme = function() {
alert('Hover Event Fired');
};
$('.A').hover(hoverme);
var i = 0;
$('.B').on('click', function(){
if(i%2 === 0){
// Unbind event
$('.A').off('hover');
}
else{
// Else bind the event
$('.A').hover(hoverme);
}
i++;
});
Check Fiddle
I think that what you want to do is something like this (example for JQuery 1.7.2):
$("#a").hover(function(){alert("test")});
$("#a")[0].active=true;
$("#b").click(function(){
if($("#a")[0].active){
$("#a")[0].storedEvents = [];
var hoverEvents = $("#a").data("events").mouseover;
jQuery.each(hoverEvents , function(key,handlerObj) {
$("#a")[0].storedEvents.push(handlerObj.handler);
});
$("#a").off('hover');
}else{
for(var i=0;i<$("#a")[0].storedEvents.length;i++){
$("#a").hover($("#a")[0].storedEvents[i]);
}
}
$("#a")[0].active = ($("#a")[0].active)==false;
});​
JSFiddle Example
But there are a couple of things that you must have in consideration:
This will only work if you add the events with JQuery, because JQuery keeps an internal track of the event handlers that have been added.
Each version of JQuery handles data("events") differently, that means that this code may not work with other version of JQuery.
I hope that this helps.
EDIT:
data("events") was an internal undocumented data structure used in JQuery 1.6 and JQUery 1.7, but it has been removed in JQuery 1.8. So in JQuery 1.8 the only way to access the events data is through: $._data(element, "events"). But keep in mind the advice from the JQuery documentation: this is not a supported public interface; the actual data structures may change incompatibly from version to version.
You could try having a variable that is outside the scope of functions a and b, and use that variable to trigger the action to take in function b on function a.
var state;
var a = function() {
if(!state) {
state = true;
// Add hover action and other prep. I'd create a third function to handle this.
console.log(state);
};
var b = function() {
if(state) {
state = false;
// Do unbinding of hover code with third function.
} else {
state = true;
// Do whatever else you needed to do
}
}
Without knowing more about what you're trying to do, I'd try something similar to this.
It sounds like you want to disable the click hover event for A if B is clicked.
$("body").on("hover", "#a", function(){
alert("hovering");
});
$("#b").click( function(){
$("body").off("hover", "#a", function() {
alert("removed hovering");
});
});
You can use the jQuery off method, have a look at this fiddle. http://jsfiddle.net/nKLwK/1/
Define a function to assign to hover on A element, so in b click, call unbind('hover') for A element and in second click on b element define again a function to hover, like this:
function aHover(eventObject) {
// Todo when the mouse enter object. You can use $(this) here
}
function aHoverOut(eventObject) {
// Todo when the mouse leave the object. You can use $(this) here
}
$(A).hover(aHover, aHoverOut);
// ...
$(b).click(function(eventObject) {
if($.hasData($(A)[0])){ // if A has event,
$(A).unbind('mouseenter mouseleave'); // This is because not a event hover, jQuery convert the element.hover(hoverIn, hoverOut) in element.bind('mouseenter', hoverIn) and element.bind('mouseleave', hoverOut)
}else{
$(A).hover(aHover, aHoverOut);
}
});
There are provably better ways to do it, but this works fine, on document ready do this:
$("#a")[0].active=false;
$("#b").click(function(){
$("#a")[0].active = ($("#a")[0].active)==false;
if($("#a")[0].active){
$("#a").hover(function(){alert("test")});
}else{
$("#a").off('hover');
}
});
JSFiddle example
You can use .off function from jQuery to unbind the hover on your "a" element.
function hoverA() {
alert('I\'m on hover');
}
$('#a').hover( hoverA );
var active = true;
$('#b').on('click', function(){
if(active){
$('#a').off('hover');
active = false;
} else{
$('#a').hover(hoverA);
active = true;
}
});
Live demo available here : http://codepen.io/joe/pen/wblpC

HTML: listen for *all* changes to an input, not just keyboard-driven changes?

For example, if I've got an input like this:
<input id="myInput" type="text" />
How can I be notified when the value is changed programatically (for example, as a result of $("#myInput").val("new value"))?
An example: http://jsfiddle.net/2ax9y/
Edit: please note, the question is asking how to listen for changes, not “how to manually dispatch changes”. I'm well aware that I can manually dispatch change events, but I'm trying to avoid that.
You can change the $ prototype to always trigger change() events whenever val(value) is called:
$.prototype.changeval = $.prototype.val;
$.prototype.val = function(v) {
if (v) {
$(this).changeval(v);
$(this).change();
} else {
return $(this).changeval();
}
}
Trigger the change: http://jsfiddle.net/maniator/2ax9y/1/
A little differently: http://jsfiddle.net/maniator/2ax9y/2/
You can't reliably subscribe to every change on an input element, but you can check if there has been a change since you last checked and do that within some desired time granularity.
Make a checker function and loop it with your desired time granularity—100ms is a good start, adjust to your needs.
Hypothetical untested implementation:
var last_value = null;
function handle_changed() {
// Do something here
}
function check_value() {
var v = $("#myelement").val();
if(v !== last_value) {
last_value = v;
handle_changed();
}
}
setInterval(check_value, 100);
I don't think this is an inherent ability of the change event. You could manually trigger the change event when you programmatically change the value.
$("#myInput").val(+(new Date())).change();

plugin save var inside each returned click

You guys mind checking out this jsfiddle I made to help you understand my issue. http://jsfiddle.net/kr1zmo/DqbeX/8/:
item
item 2
item 3
item 4
<p id="result"></p>
<script language="javascript" type="text/javascript">
(function($) {
$.fn.liveBindTest = function() {
return this['live']('click', function() {
var savedvar;
if (!savedvar || savedvar == 0) {
// is false, do false things.
savedvar = 1;
jQuery('#result').append(savedvar);
} else {
// is true, do true things.
jQuery('#result').append(savedvar);
savedvar = 0;
}
return false;
});
};
})(jQuery);
jQuery(document).ready(function() {
$('a.cref').liveBindTest();
});
</script>
I want to save a variable for each click.
Take a look at this example.
Did you want to toggle which bit of code to execute? If you want to hold the value in a closure, you'll need to declare it outside of the live event handler function.
If the value needs to be held for each element matched by the selector, then you could use $(elem).data() to store the value like in this example.
You declared your variable inside the event handler, creating a separate local variable for each handler.
You need to declare the variable outside the function.
If you want a separate variable for each element, you can declare the variable and add the handler in an each call, or use jQuery's .data function.

How to get previous and new selected value from a option DOM element with JavaScript?

How can I retrieve the new selected value and the previous selected value with JavaScript when onChange or similar event is called?
<select size="1" id="x" onchange="doSomething()">
<option value="47">Value 47</option>
...
function doSomething() {
var oldValue = null; // how to get the old value?
var newValue = document.getElementById('x').selected.value;
// ...
Thank you! :)
Using straight JavaScript and DOM, something like this (live example):
var box, oldValue;
// Get a reference to the select box's DOM element.
// This can be any of several ways; below I'll look
// it up by ID.
box = document.getElementById('theSelect');
if (box.addEventListener) {
// DOM2 standard
box.addEventListener("change", changeHandler, false);
}
else if (box.attachEvent) {
// IE fallback
box.attachEvent("onchange", changeHandler);
}
else {
// DOM0 fallback
box.onchange = changeHandler;
}
// Our handler
function changeHandler(event) {
var index, newValue;
// Get the current index
index = this.selectedIndex;
if (index >= 0 && this.options.length > index) {
// Get the new value
newValue = this.options[index].value;
}
// **Your code here**: old value is `oldValue`, new value is `newValue`
// Note that `newValue`` may well be undefined
display("Old value: " + oldValue);
display("New value: " + newValue);
// When done processing the change, remember the old value
oldValue = newValue;
}
(I'm assuming all of the above is inside a function, like a page load function or similar, as in the live example, so we're not creating unnecessary global symbols [box, oldValue, 'changeHandler`].)
Note that the change event is raised by different browsers at different times. Some browsers raise the event when the selection changes, others wait until focus leaves the select box.
But you might consider using a library like jQuery, Prototype, YUI, Closure, or any of several others, as they make a lot of this stuff a lot easier.
Look here: Getting value of select (dropdown) before change
I think the better,
(function () {
var previous;
$("select").focus(function () {
// Store the current value on focus, before it changes
previous = this.value;
}).change(function() {
// Do something with the previous value after the change
alert(previous);
});
})();
The following code snippet may help
<html>
<script type="text/javascript">
this.previousVal;
function changeHandler(selectBox)
{
alert('Previous Val-->'+selectBox.options[this.previousVal].innerHTML)
alert('New Val-->'+selectBox.options[selectBox.selectedIndex].innerHTML)
this.previousVal=selectBox.selectedIndex;
}
</script>
<body>
<select id="selectBox" onchange="changeHandler(this)">
<option>Sunday</option><option>Monday</option>
<option>Tuesday</option><option>Wednesday</option>
</select>
<script type="text/javascript">
var selectBox=document.getElementById("selectBox")
this.previousVal=selectBox.selectedIndex
</script>
<body>
</html>
Below worked for me.
Add below two events to your select HTML tag:-
onFocus='this.oldValue = this.value'; //if required in your case add this line to other events like onKeyPressDown and onClick.
onChange = 'alert(this.oldValue); this.value=this.oldValue'

Categories