JQuery loop through input elements inside javascript function - javascript

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

Related

Set value of element using an input variable

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')"

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);

JavaScript object is undefined

I need some help please with a javascript object. it goes like this:
I call this function addFilter(element) with a html DOM element.
The function looks like this:
function MyList() {
this.arr = new Array();
this.index = 0;
}
MyList.prototype.add = function(filter) {
this.arr[this.index++] = filter;
//alert(this.arr[0] + ' mylist arr');
}
function Filter(element) {
this.setElement(element);
}
Filter.prototype.setElement = function (element) {
this.element = element;
this.kinorid = $(element).attr('id');
}
function addFilter(element) {
filters.Add(new Filter(element));
}
var filters = new MyList();
Now with in another function that in my case the function creates the jquery UI Slider, and every time the slider changes i need to get the parent element of that element that was sent to addFilter like i said in the beginning. so then i try doing
var value = filters.arr[0];
but like i said it id undefined.
Can any one please help me by reviewing the code, and tell me whats wrong.
Thank you very much.
You still haven't said where or how you're using filters.arr[0], without which it's very difficult to help you.
Assuming your code using it looks something like this:
AddFilter($("#theElement"));
display(typeof filters.arr[0]);
filters.arr[0].element.css("color", "blue");
It should be working; live example.
My only thought is if AddFilter and filters are not defined within the same scope. You're using filters within AddFilter, so AddFilter must be defined in the same scope as filters (or in a sub-scope). So this would be fine:
var filters;
function AddFilter() { ... }
And this
function AddFilter() { ... }
var filters;
And this
var filters;
$(function() {
function AddFilter() { ... }
});
But not
function AddFilter() { ... }
$(function() {
var filters;
// ...
});
...because in that last case, AddFilter is defined outside the scope in which filters is defined.
Your code is very convoluted, I don't understand it at all. Anyway, you are looking for (I think):
var value = filters.arr[0].element;
since you assign the element reference to arr[this.index].
Incidentally, if you are passing an element, then:
$(this).attr('id');
is an awfully slow way to do:
this.id;
Edit
The code I used (where there was a div with id 'd0' in the DOM):
var filters = new MyList();
AddFilter(document.getElementById('d0'));
alert(filters.arr[0].element);

Passing a variable from created in function a to function b when function b is inside function a

I have a function for the class .myclassA, inside this function I capture the id of the particular element chose and I put it inside a variable inputid. This function also brings another function for another class(.myclassB), which is inside the first function. Do you guys have any idea how I can pass the variable inputid from the first function to the function inside it?
Thanks for all your help
$('.myclassA').click(function(){
var inputid = $(this).attr('id');
$('.myclassB').click(function(inputid){
var thisid = $(this).attr('id');
$(inputid).val(thisid);
});
//$('seqa').click();
});
//$('#empcriddi').focus();
You don't need to "pass" it, just don't name the local variable with the same name, like this:
$('.myclassA').click(function(){
var inputid = $(this).attr('id');
$('.myclassB').click(function(){
var thisid = $(this).attr('id');
$(inputid).val(thisid);
});
});
Though this won't quite work either, and there's no reason to go a lookup of an element you already have so just maintain a reference, for example:
$('.myclassA').click(function(){
var input = $(this);
$('.myclassB').click(function(){ //you may want to also .unbind('click') here
input.val(this.id);
});
});

Categories