Use function parameters as a variable call - javascript

what has already been described in the title, but basically I want to send a function perimeter and use it to call one of the three different variables. Also so it doesn't come to a miss understanding the "$('#'+id)" part of the code works all I need is the correct syntax for the "id =" part (if even possible). And I know there is a workaround but I am trying to minimize code and this seems like the most optimal solution.
my code:
<div class="one">
<p>ime:</p>
<input type="text" id="name">
<p>kraj:</p>
<input type="text" id="city">
<p>starost:</p>
<input type="text" id="age">
<p id="one_output"></p>
</div>
var name = "1";
var city = "2";
var age = "3";
function statement(id) {
id = $('#'+id+'').val();
$("#one_output").text("Sem " + name + " in živim v " + city + ". Star sem " + age);
};
$('.one input[type="text"]').keyup(function() {
switch($(this).attr("id")) {
case "name":
statement(the_id);
break;
case "city":
statement(the_id);
break;
case "age":
statement(the_id);
break;
}
});

ok, I think I finally understood what you're after
so you're passing a variable name and want to dynamically call it, instead of going the global way using this, I would recommend to do it by having all your vars in just one global one, for example
var formInputs = { name: '1', city: '2', age: '3' }
and then you can easily read/write them with formInputs[ var_name_here ]
so your example, would be written as
var formInputs = { name: '1', city: '2', age: '3' }
function statement(name, val) {
formInputs[name] = val
var txt = `Sem ${formInputs.name} in živim v ${formInputs.city}. Star sem ${formInputs.age}`
$("#one_output").text(txt)
}
$('.one input[type="text"]').keyup(function() {
var elm = $(this)
statement(elm.attr("id"), elm.val())
})
var formInputs = { name: '...', city: '...', age: '...' }
var statement = function(name, val) {
formInputs[name] = val // assign value to variable
var txt = `Sem <b>${formInputs.name}</b> in živim v <b>${formInputs.city}</b>. Star sem <b>${formInputs.age}</b>` // the new text
$("#one_output").html(txt) // output
}
$('.one input[type="text"]').keyup(function() {
var elm = $(this) // our key element
statement(elm.attr("id"), elm.val()) // pass id and why not the value, so we dont need the element again
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<p>ime: <input type="text" id="name"></p>
<p>kraj: <input type="text" id="city"></p>
<p>starost: <input type="text" id="age"></p>
<p id="one_output"></p>
</div>

If you want to minimize your code, you can start by doing this:
id = $(`#${id}`).val();
Instead of this:
id = $('#'+id+'').val();
Modify your keyup callback to a more cleaner code:
$('.one input[type="text"]').keyup(function() {
var myId = $(this).attr("id"));
var id = $('#'+myId+'').val();
$("#one_output").text("Sem " + name + " in živim v " + city + ". Star
sem " +
age);
});

Related

Can an object name be a number?

I am trying to create an object and have the name of each object be unique. The objects will have a name, a number and a second number that is null (this I intend to calculate later).
Is it possible to have an object named after a variable of 1 then at the end of the function increase the variable so that the next object is 2?
I am being alerted the value of the id number and it comes out as NaN
In my fiddle, I have a button to append each object in the array to a list so I can inspect them. They come out as [ object Object ].
Should this be an object of objects instead of an array of objects if I later want to use the number field in each object to perform calculations?
The format I have my sample object in is what I believe I want to stick with (unless there is a reason to do it better another way) because it follows the example on w3schools.
What am I doing wrong?
Fiddle here.
HTML:
<input type="text" placeholder="Name" id="name"> <input type="text" placeholder="Number" id="number">
<br>
<button id="makeObject">Make Object</button>
<button id="show">Show Me The Objects</button>
<ul id="list"></ul>
JavaScript:
/*Sample ideal object
1 = {
name: John Doe
number: 52
newNumber: null
}
*/
var arrayOfObjects = [];
var id = 1;
$(document).ready(function(){
$('#makeObject').on('click', function(){
var number = (parseInt($('#Number').val()));
var name = $('#Name').val();
arrayOfObjects.push(id = {
number: number,
name: name,
newNumber: null
});
id++;
alert("The id is now: " + id);
$('#Number').val("");
$('#Name').val("");
});
$('#show').on('click', function(){
$('#list').html("");
for (i = 0; i < arrayOfObjects.length; i++) {
$('#list').append("<li>" + arrayOfObjects[i] + "</li>");
};
});
});
What you are looking for would be an object key, not its name (which cannot start with a number as Quantastical states)
Anyway, your assignment is a little weird. This way shoud be the way you intended it:
arrayOfObjects[id] = {
number: number,
name: name,
newNumber: null
};
have a look at http://jsfiddle.net/ej3z9ncd/3/ to confirm it's working
Object names are strings.
I realized that the unique name doesn't matter for the object itself, I just went with "student." Instead, I put the name of the student, which is unique, as a field within the object.
Fiddle here.
<input type="text" id="name" placeholder="Name">
<input type="text" id="score" placeholder="Score">
<br>
<br>
<button id="push">Push to Array</button>
<button id="show">Show</button>
<button id="doMath">Do Math</button>
<ul id="list"></ul>
<p id="sum"></p>
<p id="mean"></p>
CSS:
input:hover {
border: 1px solid black;
}
JavaScript:
var myArray = [];
var sumOfScores;
var mean;
$(document).ready(function () {
$('#push').on('click', function () {
var name = $('#name').val();
var score = parseInt($('#score').val());
myArray.push((student = {
name: name,
score: score,
newScore: null
}));
console.log(student);
$('#name').val("");
$('#score').val("");
});
$('#show').on('click', function () {
$('#list').html("");
for (i = 0; i < myArray.length; i++) {
$('#list').append("<li>" + myArray[i].name + " received a score of " + myArray[i].score + "</li>");
};
});
$('#doMath').on('click', function(){
sumOfScores = 0;
for (i = 0; i < myArray.length; i++) {
sumOfScores += myArray[i].score;
};
$('#sum').html("The sum is: " + sumOfScores);
mean = (sumOfScores / myArray.length);
$('#mean').html("The mean score is: " + mean);
});
});

filtering HTML table with JavaScript - no plugins

UPDATE:
I am still unable to render any data. My basic strategy, which has worked with sorting is to write a function to filter named filterCats and then call it as a callback in getFilterBreed. This approach seems to do nothing. This approach is below:
function getFilterBreed(){
$.getJSON('cats.json', function(cats) {
var cats = cats;
filterCats(cats, criteria);
});
}
function filterCats(cats, criteria){
//renderData(cats.filter(function(c){return c.breed === criteria;}));
var criteria = document.getElementById('filter').value;
var filteredData = cats.filter(function(c){return c.breed === criteria;});
renderData(filteredData);
}
And the HTML:
<label for="filter">Filter</label>
<input type="text" name="filter" value="" id="filter" onchange="filterBreed()" />
I have also tried this approach which makes the data in my table disappear:
function filterCats(){
$.getJSON('cats.json', function(result) {
var cats = result; // redundant, but kept for readability
var criteria = document.getElementById('filter').value;
var filteredData = cats.filter(function(c){return c.breed === criteria;});
renderData(filteredData);
});
}
<label for="filter">Filter</label>
<input type="text" name="filter" value="" id="filter" onchange="filterCats()" />
My JSON file named cat.json looks like this but is much bigger:
[{
"breed" : "Abyssinian",
"country" : "Ethiopia",
"coffeePreference" : "espresso",
"picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/9/9b/Gustav_chocolate.jpg/100px-Gustav_chocolate.jpg"
}, {
"breed" : "Aegean",
"country" : "Greece",
"coffeePreference" : "medium roast, cream and sugar",
"picture" : "https://upload.wikimedia.org/wikipedia/commons/thumb/5/51/Aegean_cat.jpg/100px-Aegean_cat.jpg"
}]
Lastly I am rendering the data accordingly, which works:
function renderData(cats){
var output='<table id="indextable" border="1" cellpadding="10" cellspacing="0" style="border-collapse:collapse;">';
output+="<thead>"
output+="<tr>";
output+="<th> HeadShot </th>";
output+="<th><button onclick='getSortedBreedData()'>Breed</button></th>";
output+="<th><button onclick='getSortedCountryData()'>Country</button></th>";
output+="<th><button onclick='getSortedCoffeeData()'>CoffeePreference</button></th>";
output+="</tr>";
output+="</thead>"
for (var i in cats) {
output+="<tbody>"
output+="<tr>";
output+="<td><img src='" + cats[i].picture+"' alt='missing cat picture'></td>"
output+="<td>" + cats[i].breed + "</td>"
output+="<td>" + cats[i].country + "</td>"
output+="<td>" + cats[i].coffeePreference + "</td>"
output+="</tr>";
output+="</tbody>"
}
output+="</table>";
document.getElementById("catTable").innerHTML=output;
}
Any help would be greatly appreciated.
Alright, so this is your input that calls the filter function (note: no function arguments):
<input type="text" name="filter" value="" id="filter" onchange="filterCats()" /></br></br>
Next, this is your filter function, yet it takes one argument:
function filterCats(cats){
$.getJSON('cats.json', function(cats) {
var cats = cats;
var criteria = document.getElementById("filter").value;
var filteredData = cats.filter(function(cats){return cats.breed === "criteria";});
renderData(cats);
});
}
Then, in your getJSON callback, you have a parameter with the same name as the outer function argument; the same thing happens one more time in the inner filter function.
Another thing: return c.breed === "criteria"; This is comparing the breed value to the string literal "criteria", not the criteria value you got from the filter input, so unless your cat breed is "criteria" this will never evaluate to true - it should be: return c.breed === criteria; instead.
Finally, after getting rid of many cats and fixing the criteria, we have something like:
function filterCats(){
$.getJSON('cats.json', function(result) {
var cats = result; // redundant, but kept for readability
var criteria = $('#filter').val();
var filteredData = cats.filter(function(c){return c.breed === criteria;});
renderData(filteredData);
});
}
This code is not tested, but it should work.
You can furtherly optimize this code by passing the criteria value directly to the function:
<input type="text" name="filter" value="" id="filter" onchange="filterCats(this.value)" />
function filterCats(criteria){
$.getJSON('cats.json', function(cats) {
renderData(cats.filter(function(c){return c.breed === criteria;}));
});
}
Simple live example:
var improvizedCatsObject = [
{name: 'shomz', breed: 'answerer'},
{name: 'robinette',breed: 'questioner'},
{name: 'not pure js',breed: 'jquery'},
{name: 'is a library',breed: 'jquery'}
];
function filterCats(criteria) {
renderData(improvizedCatsObject.filter(function(c) {
return c.breed == criteria;
}));
}
function renderData(res) {
var out = '';
for (var i = 0; i < res.length; i++) {
out += '<p>' + res[i].name + '</p>';
}
$('#res').html(out);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="filter" value="" id="filter" onkeyup="filterCats(this.value)" />
<span>Try inputting "answerer" or "questioner" (no quotes)</span>
<div id="res"></div>

Extract data using regular expression

I have these text fields.
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Here tab_4_*_li_data is a <li> html of tab , and tab_4_0_li_div_content is id of <div> which will be show on <li> click.
Now I want to extract data from this input fields using regular expression. For example
client,lab
as key
and
<p>aaaaaaaaaaa</p>,<p>dddd</p>
as value of key.
If you see these are related to each others.
tab_4_0_li_div_content tab_4_0_li_data
<p>aaaaaaaaaaa</p> lab
tab_4_1_li_div_content tab_4_1_li_data
<p>dddd</p> client
Div content part can content any thing, It's an text area.
So how we do this?
There is no reason to have to use a regular expression to parse HTML. One thing, you are not going to have a good time going it. Second, use the power of the DOM
var contents = $("[id$=content]"); //find the elements that have an id that end with content
var datas = $("[id$=data]"); //find the elements that have an id that end with data
var details = {}; //object to hold results
datas.each( function(i) { details[datas[i].value] = contents[i].value; }); //start looping and generate the object with the details you are after
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content"><input type="text" value="lab" id="tab_4_0_li_data"><input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content"><input type="text" value="client" id="tab_4_1_li_data">
Now that code assumes the data and content elements are in the same order, if not, than it would require a little processing, but it is not that hard to do.
var datas = $("[id$=data]");
var details = {};
datas.each(function(i, elem) {
var id = elem.id;
var val = $("#" + id.replace("data", "div_content")).val();
details[elem.value] = val;
});
console.log(details); //Object {lab: "<p>aaaaaaaaaaa</p>", client: "<p>dddd</p>"}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" value="<p>aaaaaaaaaaa</p>" id="tab_4_0_li_div_content">
<input type="text" value="lab" id="tab_4_0_li_data">
<input type="text" value="<p>dddd</p>" id="tab_4_1_li_div_content">
<input type="text" value="client" id="tab_4_1_li_data">
You can do it like this:
function getValuesById(id1,id2){
var vals = {};
if(id1 === undefined)
id1 = "\\d+";
if(id2 === undefined)
id2 = "\\d+";
$("input").each(function (index, value) {
console.log(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
var match = value.id.match(new RegExp('tab_(' + id1 + '_' + id2 + ')_li_data'));
if (match) {
vals[value.value] = $("#tab_" + match[1] + "_li_div_content").val();
}
});
return vals;
}
Here I search through all input fields and match against tab_DIGITS_DIGITS_li_div_data and put that as a key and corresponding li_div_content as value in object values.
Check it out here: JSFiddle
UPDATE: I have updated the code to a function where you can send in a parameter to your two numerical values and will use any number if not supplied, i.e. use as getValuesById(4) for values like tab_4_*_li

get parent element attribute value

this is my xml document:-
<root>
<child_1 entity_id = "1" value="india">
<child_2 entity_id = "2" value="gujarat">
<child_3 entity_id = "3" value="Ahemdabad"/>
<child_4 entity_id = "4" value="Surat"/>
<child_5 entity_id = "5" value="Rajkot"/>
</child_2>
</child_1>
</root>
this is my javascript html code:-
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
var xml;
var ind_sex;
$.get(
"code.xml",
null,
function (data) {
xml = data;
},
"xml"
);
function get_list() {
var city = $('#name').val();
alert(city);
var xPath = '//*[#value = "city"]' +
'/../../#value';
var iterator = xml.evaluate(xPath, xml.documentElement, null,
XPathResult.UNORDERED_NODE_ITERATOR_TYPE, null);
var thisNode = iterator.iterateNext();
var str = '';
while (thisNode) {
if (str) {
str += ', ';
}
str += thisNode.textContent;
thisNode = iterator.iterateNext();
}
$("#result").text(str);
}
</script>
</head>
<body>
<input type="text" id="name"></input>
<input type="button" name="button" value="Search" onclick="get_list()">
<div id="result">
</div>
</body>
</html>
here i am try to input in textbox city name if its match on my xml file then its return me there country name.
i dont get any error but not getting result.
i think problem in my xPath pleasae help me out of this.
Use:
var xPath = '//*[#value = "' + city + '"]/../../#value';
An equivalent expression is:
var xPath = '//*[*/*[#value = "' + city + ']]/#value';
As far as I remember, lists don't work like that... they're variables associated with a given value, so it's more like:
list($a, $b, $c) = [1, 2, 3];
Anyway, why don't you take a look at the 'Lists' section in the phpredis page? It's one of the recommended PHP clients for Redis, and its examples are quite clear

Dependent observables with two view models?

I am working with the wonderful Knockout.js library. I am using javascript classes to capture the structure. For example, one of several classes is:
function OverridableFormItemText(defaultId, defaultText, defaultHelpText, overrideId, overrideText, overrideHelpText)
{
this.DefaultFormItemTextId = ko.observable(defaultId);
this.DefaultText = ko.observable(defaultText);
this.DefaultHelpText = ko.observable(defaultHelpText);
this.OverrideFormItemTextId = ko.observable(overrideId);
this.OverrideText = ko.observable(overrideText);
this.OverrideHelpText = ko.observable(overrideHelpText);
}
If I have two view models in the page and want to add a dependent observable property to my class OverridableFormItemText, then do I need to do this twice due to the requirement to pass to view model to the function?
viewModel1.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel1);
viewModel2.OverridableFormItemText.SomeDependentProperty = ko.dependentObservable(function() {
return this.DefaultText() + " " + this.OverrideText();
}, viewModel2);
Yes, but you could make it more maintainable with the DRY principle, have a look at this example with the following view:
<p>First name: <span data-bind="text: viewModel2.firstName"></span></p>
<p>Last name: <span data-bind="text: viewModel2.lastName"></span></p>
<h2>Hello, <input data-bind="value: viewModel2.fullName "/>!</h2>
<p>First name: <span data-bind="text: viewModel.firstName"></span></p>
<p>Last name: <span data-bind="text: viewModel.lastName"></span></p>
<h2>Hello, <input data-bind="value: viewModel.myFullName "/>!</h2>
And this code:
var viewModel = {
firstName: ko.observable("Planet"),
lastName: ko.observable("Earth")
};
var viewModel2 = {
firstName: ko.observable("Exoplanet"),
lastName: ko.observable("Earth")
};
function FullNameDependentObservable(viewmodel, f, property) {
viewmodel[property] = ko.dependentObservable(f, viewmodel);
}
var AddNames = function() {
return this.firstName() + " " + this.lastName();
};
FullNameDependentObservable(viewModel, AddNames, "myFullName");
FullNameDependentObservable(viewModel2, AddNames, "fullName");
ko.applyBindings(viewModel);
ko.applyBindings(viewModel2);
OP here. Found that if you use classes as above, you can refer to 'this' when creating a dependent property, so this means I don't need to define the dependent property for each view model:
function OverridableFormItemText(defaultId, defaultText, defaultHelpText, overrideId, overrideText, overrideHelpText)
{
this.DefaultFormItemTextId = ko.observable(defaultId);
this.DefaultText = ko.observable(defaultText);
this.DefaultHelpText = ko.observable(defaultHelpText);
this.OverrideFormItemTextId = ko.observable(overrideId);
this.OverrideText = ko.observable(overrideText);
this.OverrideHelpText = ko.observable(overrideHelpText);
this.SomeDependentProperty = ko.dependentObservable(function() { return ('Dependent' + this.DefaultText() )}, this);
}

Categories

Resources