Set value of element using an input variable - javascript

I have a js function that sets the value of id_2 based on the value of id_1. It looks like this below:
function set_value(id_1, id_2, url){
var id_1_value;
id_1_value = $(id_1).val();
var value;
...
/* calculation etc. */
document.getElementById(id_2).value = value;
};
The function is linked to the id_1 html element by an onchange method like this onchange='set_value(this, id_2)'.
If I change the value in id_1 the function doesn't work and I get the following error in the console:
Unable to set property 'value' of undefined or null reference
but if I hardcode document.getElementById('id_2') in the function it works fine. How do I write this function so I can pass an element id variable to it successfully? I want to reuse this function for different elements you see...

Your set_value function should be as below.
function set_value(id_1, id_2, url) {
var id_1_value = $(id_1).val();
/* calculation etc. */
if ($(id_2).length !== 0)
{
$(id_2).val(id_1_value);
}
}

Are you passing "#id_2" to the set_value parameter?
if so that means it would return null.
// The function should be called like this
var id_2 = "id_2";
set_value(this, id_2, blah...)

Change the call like this
onchange='set_value(this, "id_2")'
Second parameter should be passed as string.

try this following code:
function set_value(id_1, id_2, url){
var id_1_value = $(id_1).val();
var value;
...
/* calculation etc. */
document.getElementById(id_2).value = value;
};
and onchange function
onchange="set_value(this, 'id_2')"

Related

How to get current object reference inside a jquery callback function?

I have a javascript Object called aObject and a fucntion inside it is used as a jQuery Callback function like this:
var aObject = {
aVariable : 'whatever value',
test : function(e) {
// Trying to access property. But doesn't work as expected since I am getting the DOM element i.e form, not the aObject reference
var temp = this.aVariable;
}
}
$('document').ready(function(){
$('#some-html-form').submit(aObject.test);
});
When I call the test method in aObject, this refers to the form element that has been submitted. I want to access current object from the test callback function?
I tried the below code as described in this answer but it did not work for me
$(document).ready(function() {
$('#add_api_form').submit(api_cahce.handle_add_form_submit.bind(this));
});
bind with aObject then you can access the variable.
var aObject = {
aVariable : 'whatever value',
test : function(e) {
var temp = this.aVariable;
}
}
$('document').ready(function(){
$('#some-html-form').submit(aObject.test.bind(aObject));
});

JQuery loop through input elements inside javascript function

I'm new to JQuery so if this is a obvious question my apologies. I have a simple form which holds some input fields. On the change-event I want to change a pre-defined array. The change event is triggered, but in this change-event I want to loop through all input-element again to fill/change an array. However the iteration doesn't work.
<script>
jsonObj = [];
$(document).ready(function(){
$("input[class=domain]").change(function(){
refreshData();
});
$("input[class=domain]").each(function() {
var domain = $(this).attr("name");
var score = $(this).val();
item = {}
item ["domain"] = domain;
item ["score"] = score;
jsonObj.push(item);
});
});
function refreshData() {
alert("Text Changed"); <<-- This line is reached.
$(document)("input [class=domain]").each(function() {
//TO DO: Refresh jsonObj
alert(domain); /<<-- This line is not reached.
});
}
</script>
A second question would be if it is possible to shorten this code. Now I have two separate function in the document.ready-event Change and
each both on the input-element.
T.I.A.
$('.domain').each(function(){
alert(domain);
})
use this instead of $(document)("input [class=domain]").each
You are missing a . and probably a .find before .each. Below code is what it should look like:
$(document).find("input[class=domain]").each(function() {
//TO DO: Refresh jsonObj
alert(domain);
});
UPDATE
With respect to your second question I would have shortened the code as below if the lines inside your .each was same as it would be in refreshData function:
jsonObj = [];
$(document).ready(function(){
refreshData();//call once on DOM Load
$('.domain').change(refreshData); //attach it as named function to change event
});
function refreshData() {
//keep all this code here
$(".domain").each(function() {
var domain = $(this).attr("name");
var score = $(this).val();
item = {}
item["domain"] = domain;
item["score"] = score;
jsonObj.push(item);
});
}
I have done some rectification and you can shorten it like:
<script>
jsonObj = []; // array declaration
$(document).ready(function(){
$("input.domain").change(function(){ // <----better to use a class selector
refreshData($("input.domain")); // <----pass the object in the function
}).change(); //<----trigger it on load to execute
});
function refreshData(el) { // get the passed object in the func arg
$(el).each(function() { // <----have a loop on it this way
var domain = $(this).attr("name"); // extract the name on current object in collection
var score = this.value; // get the value of the current object in iteration
var item = {}; // declare a new object
item["domain"] = domain; // set new prop and assign value here
item["score"] = score; // set new prop and assign value here
jsonObj.push(item); // now push the object in the array.
});
}
</script>
This expression is wrong for some reasons:
$(document)("input [class=domain]")
A. There must be no space between input and [class=domain]. This is the difference between "input that has the class domain" (input[class=domain]) and "input that one of its sub-nodes has the class domain" (input [class=domain]).
B. In order to query inside a jQuery element you need to use the find method like this: $(document).find("input [class=domain]"). But because document is the root element, you can just write $("input [class=domain]").
P.S
In CSS-selectors (like jQuery) there is a special syntax for searching classes, so instead you can just write input.domain.
So this how the line should look at last:
$("input.domain").each...
You can read more about css selectors here.
Strange code...
$(document)("input [class=domain]").each
Try this:
$("input[class=domain]").each

How to change external function variable from internal jquery event function?

How I can change external function variable from internal function?
Example:
function ExternalFunction() {
var $element = $('#my-element'); // Some jquery object
var my_variable = 'value';
$element.click(function() {
// Here I want to change "my_variable" value.
// But I can't change it with "my_variable = 'new value';".
})
}
How I can change my_variable in internal function?
Update1:
I haven't error, but I can't change variable from internal function. See example please:
http://jsfiddle.net/ye0qhu0v/4/
you cant use ExternalFunction() inside DOM ready,Declare the function outside DOM ready
Works perfectly,
function ExternalFunction() {
var $element = $('#my-element'); // Some jquery object
var my_variable = 'value';
$('#my-element').on('click', function() {
// Here I want to change "my_variable" value.
// But I can't change it with "my_variable = 'new value';".
my_variable = 'new value';//here we are assigning new value to the variable
console.log(my_variable);
})
}

js onclick function params

How can I pass an attribute of div into it's own onclick function?
For example, I have this div:
var join_button = document.createElement("div");
join_button.setAttribute("class", "join_button");
join_button.innerHTML = "join";
join_button.setAttribute("room_name", name);
join_button.setAttribute("onclick", "join_room()");
Now, in function join_room() I need to know the room name attribute of this join_button. Ofcourse, I have not only one join_button on my page, I dont know it's names and I need to handle all of them.
If I try to use this It tells me undefined is not a function
function join_room() {
this.getAttribute("room_name");
}
undefined is not a function
You can use this to read the objects attribute.
var join_room = function() {
var room_name = this.getAttribute('room_name);
}
then set the onclick like this.
join_button.onclick = join_room;
JSFIDDLE

JavaScript global variables declaration

The following script works correctly although I need to make few amends. In each function I am getting the values need for the different formulas. However I tend to replicate the same line of code in different functions.
Ex.
function one(){ var v1= document.getElementById('one').value; }
function two(){ var v1= document.getElementById('one').value; }
Full code
I would like to declare all of the variables once and than only use the ones I need for the specific functions. If I declare them right at the top than once they are called they still hold the original value so I need to update that value to the current one if changed of course.
Your code will be very hard to read if you do it like in your fiddle.
Instead do
var myVars;
window.onload=function() {
myVars = {
'list_price': document.getElementById('list_price'),
'negotiated': document.getElementById('negotiated'),
.
.
'lease_payment': document.getElementById('lease_payment')
}
now you can do
var price = myVars.list_price.value;
or perhaps add a function
function getVal(id) {
var val = document.getElementById(id).value;
if (val =="" || isNaN(val)) return 0;
return parsetInt(val,10);
}
now you can do
var price = getVal("list_price");
mplungjan's solution is a great one. If you're at all concerned by your global vars leaking into the window scope, wrap your code in an Immediately Invoked Function Expression to prevent that from happening:
(function(){
// code goes here
}());
There are two ways to go about this:
Update your variable when the value changes
Use a function that always returns the correct value
1) You can add a listener for the change event or the keyup event that changes your global variable:
// save initial value
var val = document.getElementById('one').value;
// update the value when input is changed
addEventListener(document.getElementById('one'), 'change', function() {
val = document.getElementById('one').value;
});
console.log(val);
2) You can use a function that always returns the current value:
var val = function() { return document.getElementById('one').value; };
console.log(val());
2b) If you hate parenthesis, you can define a property that uses the function above as a getter:
Object.defineProperty(window, 'one', {
get : function() { return document.getElementById('one').value; }
});
console.log(one);

Categories