Passing elements as variables to function - javascript

I'm having an issue with an element object and a jQuery function:
HTML
<label for='state'>State</label>
<input id='state' name='state' type='text' value=''/>
<span class='info'><img class='tick' /><img class='cross' /></span>
JavaScript / jQuery
var state = $("#state");
function validatefield(myelement) {
if (myelement.val().length > 3) {
alert("word");
} else {
alert("sup");
}
}
state.blur(validatefield(state));
state.keyup(validatefield(state));
Nothing happens on page load, even when state has more than 3 chars entered.
Any ideas?
Awesome - learning new stuff ftw

No need for arguments at all, the event handler is bound to the element so that you can use the this keyword inside the function:
var state = $("#state");
function validatefield(event) {
if (this.value.length > 3) { // <-- use `this.value` instead
alert("word");
} else {
alert("sup");
}
}
state.blur(validatefield);
state.keyup(validatefield);
The way you're attempting it will actually call the function and use its return value as the event handler, which is why nothing was happening:
// validatefield(state) is executed immediately and the return value, "undefined"
// is passed as the first argument to state.blur()
state.blur(validatefield(state));
To fix other situations like this where the this keyword is not available, you should use an anonymous function:
state.blur(function () { validatefield(state) });

Wrap the function calls in anonymous functions.
$(document).ready(function(){
var state = $("#state");
state.blur(function() {validatefield(state)});
state.keyup(function() {validatefield(state)});
});
http://jsfiddle.net/eW8E8/1/

You should use an anonymous function as jQuery event handler, instead of
state.keyup(validatefield(state));
use
state.keyup(function() {
validatefield(state);
});

Shouldnt it be:
if(myelement.value.length > 3) {

state.keyup(validatefield.call(this, state))
should also work (see http://ejohn.org/apps/learn/#26)

Related

trying to update object attribute when checkbox is selected

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.

Change the button text/value on click with javascript

My goal is to include Element.ID within function and then, fetch their value or text. It is important to reduce code lines as well because there are many others buttons with the same rule.
So, I tried the below code and many others to get the appropriate results.
How do I fix it?
var el = document.getElementById("p1");
var id = document.getElementById("p1").id;
el.addEventListener("click", modifyText(id), false);
function modifyText(e) {
var x = e.value;
if (x < 40) {
e.value = 1;
}
};
<input id="p1" type="button" class="button" value=0>
<input id="pn" type="button" class="button" value=0>
Well, the second argument to .addEventListener() has to be a function reference, not "loose" code to execute. So, if you want to call another function and pass it an argument, the line should be:
el.addEventListener("click", function(){modifyText(id)}, false);
Now, you are making quite a bit out of the element's id, but you really only need the id to get your initial reference to the element. Once you've got that, you can just work with it.
You've got a lot of unnecessary code here. Also, I'm assuming (perhaps incorrectly) that you want both buttons to have the same click behavior, so that's what I'm proceeding with.
// You only need to get a reference to the element in question
var el1 = document.getElementById("p1");
var el2 = document.getElementById("pn");
// Set up each button to use the same click callback function
// The second argument needs to be a function reference
el1.addEventListener("click", modifyText);
el2.addEventListener("click", modifyText);
function modifyText(){
// When inside of an event handler, "this" refers to the element
// that triggered the event.
if (this.value < 40 ) {
this.value = 1;
}
}
<input id = "p1" type="button" class="button" value=0>
<input id = "pn" type="button" class="button" value=0>
Event listener callbacks tend to be executed with the execution context of the element (unless otherwise modified, or using Arrow functions). This means you can just use this keyword to refer to the element. So inside the callback you could use this.value / this.innerText (depending on type of element)
function modifyText() {
var x = this.value;
if ( x < 40 ) {
this.value = 1;
}
}
Also the way you called addEventListener was wrong.
.addEventListener("click", modifyText(id), false);
This will execute modifyText immediately and use the return value of the function as the callback. And since your function doesnt return anything nothing is set as the callback.
If you wanted to pass a variable to an event callback you would do it like the following
el.addEventListener("click", modifyText.bind(el,yourValue),false);
You would then need to modify the function definition
function modifyText(passedValue,event) {
}

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!

assigning click method to variable

I am creating an array & assigning the value to each index in a function through variables.
I also want to attach a jquery click method to each variable. However, I am getting 'undefined' in return when the click method is called.
var i = 0;
var eCreditTransactions = new Array(6); // 6 members created which will be recycled
function abc()
{
addingElements (i);
}
/* **** THE FOLLOWING IS THE PROBLEM AREA **** */
$(eCreditTransactions[i]).click (function () // if user clicks on the transaction box
{
creditTransactionSlideIn (eCreditTransactions[0], 150); //another function called
});
/* **** this is the function being called in the first function above **** */
function addingElements (arrayIndex) // func called from within the 'createCreditTransaction()' func
{
eCreditTransactions[i] = $(document.createElement('div')).addClass("cCreditTransaction").appendTo(eCreditSystem);
$(eCreditTransactions[i]).attr ('id', ('trans' + i));
$(eCreditTransactions[i]).html ('<div class="cCreditContainer"><span class="cCreditsNo">-50</span> <img class="cCurrency" src="" alt="" /></div><span class="cCloseMsg">Click box to close.</span><div class="dots"></div><div class="dots"></div><div class="dots"></div>');
creditTransactionSlideOut (eCreditTransactions[i], 666); // calling slideOut animation
counterFunc ();
return i++;
}
Try this:
$(document).ready(function() {
$(".cCreditTransaction").click(function() {
//do what you want on click event
});
});
Hope it helps
Given that it looks like each element you're adding to the array has a classname (cCreditTransaction) you can hookup the click events using something like
$(document).delegate(".cCreditTransaction", "click", function() {
// code to fire on click goes here.
});
or in jQuery 1.7+ you can use .on instead of .delegate
You don't then need to hook up n events, but just one event that matches all items in the selector (in your case, the class name)
You should also change $(document) to a container element that has an Id, so that the DOM traversal to find the classes is trimmed down as much as possible. Why? Because finding elements by class name is a relatively expensive procedure, as opposed to finding tags or even better, an ID.
it looks like there should be a loop in this part:
function abc()
{
addingElements (i);
}
there is a call to addingElements, and an 'i' parameter being passed, but 'i' is at that moment still defined as 0.
it should say something like
function abc()
{
for (i=0;i<=7;i++)
{
addingElements (i);
}
}

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.

Categories