I have an js object that is stored to variable
var data = {
"France":[
{
'population': "8M",
}
],
"Spain":[
{
'population': "18M",
}
]
}
and I have an input field that have some value (choosed from dropdown).
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France">
I am trying to compare that value of the input with key of the object, and then if that value is equal to the key, to display population number.
So far I tried to do like this
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data.c1[0].population); //if value is included, add population number to result
}
});
And I got undefined. I figure it out that I can not take value if I put variable c1 instead of name of the key. If I put name of the key France, everything works fine, but if I put c1 variable that is equal to France, then it is not working.
Any hint/help how to manage this to work.
Thanks.
Since c1 is a variable, use bracket notation which will allow you to use property name as variable:
Change
$(".country1-result h1").html(data.c1[0].population);
To
$(".country1-result h1").html(data[c1][0].population);
var data = { "France": [{ 'population': "8M", }], "Spain": [{ 'population': "18M", }] }
function myFunction(){}
$(".compare").click(function() {
var c1 = $(".first-country").val(); //take value from input
var zemlja = Object.keys(data); //take all keys from object
var n = zemlja.includes(c1); //check if value is included in object
if (n) {
$(".country1-result h1").html(data[c1][0].population); //if value is included, add population number to result
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="country1" onkeyup="myFunction()" placeholder="Select indicator" value="France" class="first-country">
<input type="button" class="compare" value="Click" />
<div class="country1-result">
<h1></h1>
</div>
$( ".compare button" ).click(function() {
var c1 = $( ".first-country input" ).val(); //take value from input
var result = data[c1] ? data[c1][0].population : '';
$(".country1-result h1").html(result);
});
Related
I'm currently working with 2 textboxes that copies each other values. But the thing is, my 1st textbox has an autocomma. How could I make my 2nd textbox ignore the comma?
For example. My first textbox value is 1,000 then my 2nd textbox
value should be 1000.
HTML
<input type="text" value="" id="textbox1"/>
<input type="text" value="" id="textbox2"/>
Script
//this function is for my autocomma
function updateTextView(_obj){
var num = getNumber(_obj.val());
if(num==0){
_obj.val('');
}else{
_obj.val(num.toLocaleString());
}
}
function getNumber(_str){
var arr = _str.split('');
var out = new Array();
for(var cnt=0;cnt<arr.length;cnt++){
if(isNaN(arr[cnt])==false){
out.push(arr[cnt]);
}
}
return Number(out.join(''));
}
$(document).ready(function(){
$('#textbox1').on('keyup',function(){
updateTextView($(this));
});
});
//this function copies the textbox1 values to textbox value 2
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
You modify the function updateTextView as below:
function updateTextView(_obj) {
var num = getNumber(_obj.val());
if (num == 0) {
_obj.val('');
$("#textbox2").val('');
} else {
$("#textbox2").val(num);
_obj.val(num.toLocaleString());
}
}
And then remove the following:
$("#textbox1").bind('input', function () {
var stt = $(this).val();
$("#textbox2").val(stt);
});
In plain JS:
Try the onkeyup() event added to the first textbox. Then replace all commas in the value of the first box with nothing using value.replace(/,/g, ""). And then copy the value of the first input
function update(input) {
var value = input.value.replace(/,/g, "");
document.getElementById("second-textbox").value = value;
}
<input onkeyup="(update(this))" />
<input id="second-textbox" />
to the second.
I have tried to use local storage to remember the input's value after refreshing page. but my code does not work.
here is the HTML code
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="name" onkeyup="saveValue(event)"/>
<input type="text" name="age" onkeyup="saveValue(event)"/>
and here is javascript
<script type="text/javascript">
var nameArr = ["name"];
var inputs = document.getElementsByName('name');
inputs.forEach(function(el){
el.value = getSavedValue(el);
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
</script>
if there is a way to solve this problem please tell me.
and if there is a way to do that with jquery I will be thankful to tell me that.
Here are couple of things. First instead of onkeyup use onblur so value will be saved in storage only when the focus is removed from the element.
Secondly use a common class inputs in this case and give separate name to each element.
Then get all the elements with same class, iterate through it and get value of name property using getAttribute. Use this value to check if there exist a key in localStorage
var nameArr = ["name"];
var inputs = [...document.getElementsByClassName('inputs')];
inputs.forEach(function(el) {
console.log()
el.value = getSavedValue(el.getAttribute('name'));
})
function saveValue(e) {
var name = e.target.name;
var val = e.target.value;
localStorage.setItem(name, val);
}
function getSavedValue(v) {
if (!localStorage.getItem(v)) {
return "";
}
return localStorage.getItem(v);
}
<input type="text" class='inputs' name="firstName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="lastName" onblur="saveValue(event)" />
<input type="text" class='inputs' name="age" onblur="saveValue(event)" />
On your code you are passing the input object as a parameter instead of its name (or value; you choose). As localStorage only stores String key-value pairs, it won't work as you're trying to find a key that is an object.
in the forEach instead of:
el.value = getSavedValue(el);
set:
el.value = getSavedValue(el.name);
or let the "getSavedValue" function accept an object as parameter, but to access localStorage you must pass a string as the key.
I can't figure out how to convert the text typed into a text input box (txtQuestion) into all lower case, i.e. typing "input" or "INpUt" will be read the same and output the same result.
Use toLowerCase() function. Eg: "INPuT".toLowerCase();
exampleFunction = function(){
//First we get the value of input
var oldValue = document.getElementById('input').value;
//Second transform into lowered case
var loweredCase = oldValue.toLowerCase();
//Set the new value of input
document.getElementById('input').value = loweredCase;
}
<input id="input" type="text" onkeyup="exampleFunction()" />
You have to choose the events that you want to watch and then return to the input the same value but lowercase:
function InputLowerCaseCtrl(element, event) {
console.log(element.value)
return element.value = (element.value || '').toLowerCase();
};
InputLowerCaseCtrl.bindTo = ['blur'].join(' ');
document.addEventListener('DOMContentLoaded', function() {
var input = document.querySelector('.input-lowercase');
return input.addEventListener(InputLowerCaseCtrl.bindTo, InputLowerCaseCtrl.bind(this, input));
});
<input class="input-lowercase" type="text" />
You can convert any string input to lowercase using the String.prototype.toLowerCase function
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase
For you example with an input for txtQuestion.
var inputStringLowerCase = inputTxtQuestion.value.toLowerCase();
https://jsfiddle.net/fbkq2po4/
I want to get an Object in javascript with values from my dynamically generated array in correct order so then later on I will be able to jsonencode that object and save it into my Database. (Maybe there is a different easier way of doing it)
Here is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<input type="submit" name="submit">
</form>
Here are functions that I use to create this array:
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<input type="text" class="ChampionInput">\
Add General Change\
<div class="GeneralChanges">\
</div>\
<div>');
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" class="GeneralChangeDescription"></textarea>\
</div>');
});
And below is what I've tried with no result. I was trying to loop through values of my array and then put it into an object I get the whole div instead of the actual value.
$( "#second_form" ).submit( function(event) {
$( "#ChampionInput.ChampionInput :input" ).each( function( index, value ) {
var _value = value;
var _index = index;
alert(value);
$(this).children( ".GeneralChangeDescription").each( function( index, value ) {
});
});
});
Here is a picture of how it could look like after adding some fields http://imgur.com/QXhWSHA
And here is working jSfiddle: http://jsfiddle.net/ss84agxv/
Try this code, I hope that I understood your question correctly.
$("#second_form").submit(function(event) {
//don't do the default action on submit
event.preventDefault();
//Your object as array for the champions
var object = [];
//Loop through each .Champion-div
$('.Champion').each(function() {
//Create a new object for this champion with the value from the input field and an array for the descriptions
var champion = {
'name': $(this).find(".ChampionInput").val(),
'description': []
};
//Loop through each description textfields of this champion
$(this).find('.GeneralChangeDescription').each(function() {
//add the description to the description array of the champion
champion.description.push($(this).val());
});
//finally put the champion in your champion array
object.push(champion);
});
//Thats just for you, an alert of the json-object
alert(JSON.stringify(object));
});
I want that the user can see the value of a variable by writing it's name in a textarea, simpliefied:
var money = "300$";
var input = "money"; //user wants to see money variable
alert(input); //This would alert "money"
Is it even possible to output (in this example) "300$"?
Thanks for help!
Instead of seprate variables, use an object as an associative array.
var variables = {
'money': '300$'
}
var input = 'money';
alert(variables[input]);
You can use an object and then define a variable on the go as properties on that object:
var obj = {}, input;
obj.money = "300$";
input = "money";
alert(obj[input]);
obj.anotherMoney = "400$";
input = "anotherMoney";
alert(obj[input]);
A simple way,you can still try this one :
var money = "300$";
var input = "money"; //user wants to see money variable
alert(eval(input)); //This would alert "money"
Here is an answer who use the textarea as asked.
JSFiddle http://jsfiddle.net/7ZHcL/
HTML
<form action="demo.html" id="myForm">
<p>
<label>Variable name:</label>
<textarea id="varWanted" name="varWanted" cols="30" rows="1"></textarea>
</p>
<input type="submit" value="Submit" />
</form>
<div id="result"></div>
JQuery
$(function () {
// Handler for .ready() called.
var variables = {
'money': '300$',
'date_now': new Date()
}
//Detect all textarea's text variation
$("#varWanted").on("propertychange keyup input paste", function () {
//If the text is also a key in 'variables', then it display the value
if ($(this).val() in variables) {
$("#result").html('"' + $(this).val() + '" = ' + variables[$(this).val()]);
} else {
//Otherwise, display a message to inform that the input is not a key
$("#result").html('"' + $(this).val() + '" is not in the "variables" object');
}
})
});