Javascript - How To Show Value From Object By Matching User Input To Its Key?
I want to make conversion tool which converts one code (user input) to another (predefined). I decided to use Javascript object as a container for codes, and my function will take
Solution 1:
You can use []
after calling the object to get the key value pair:
GardinerToUnicodeCodePoint[userInput]
Change your code to:
var userInput = $("#userInput").val; /*for example 'A1'*/if (userInput inGardinerToUnicodeCodePoint) {
alert(GardinerToUnicodeCodePoint[userInput]);
} else {
alert("No code found!");
}
See jsfiddle: https://jsfiddle.net/wy70s3gj/
Solution 2:
functiongetReturnCodeUsingKey(keyFromUserInput)
{
varGardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"etc"
};
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
return returnVal ? returnVal : "error: no match found";
}
Pass that function your string input
from the user, and it'll return what you want I think.
So, you're full solution would look like this:
$(document).ready(function() {
$("#convert").click(function(){
var userInput = $("#userInput").val(); /*for example 'A1'*/// a call to our new function keeping responsibilities seperatedreturngetReturnCodeUsingKey(userInput);
});
});
functiongetReturnCodeUsingKey(keyFromUserInput)
{
varGardinerToUnicodeCodePoint = {
"A1" :"995328",
"A1A" :"995329",
"A1B" :"995330",
"A1C" :"995331",
"A2" :"995332",
"A2A" :"995333",
"A3" :"995334",
"A3A" :"995335",
"A3B" :"995336",
"A4" :"995337",
"A4A" :"995338",
"A4B" :"995339",
"A4C" :"995340",
"A4D" :"995341",
"A4E" :"995342",
"A5" :"995343",
"A5A" :"995344",
"A5B" :"995345",
"A5C" :"995346",
"A6" :"995347",
};
// set a variable to hold the return of the object query
returnVal = GardinerToUnicodeCodePoint[keyFromUserInput];
//return valid value from object, or string if undefinedreturn returnVal ? returnVal : "error: no match found";
}
Solution 3:
The issue here as expresed in the comments by @epascarello is that you should use $("#userInput").val();
with the parenthesis
Code example:
$('#convert').click(function() {
varGardinerToUnicodeCodePoint = {
A1: '995328',
A1A: '995329',
A1B: '995330',
A1C: '995331',
A2: '995332',
A2A: '995333',
A3: '995334',
A3A: '995335',
A3B: '995336',
A4: '995337',
A4A: '995338',
A4B: '995339',
A4C: '995340',
A4D: '995341',
A4E: '995342',
A5: '995343',
A5A: '995344',
A5B: '995345',
A5C: '995346',
A6: '995347'
};
var userInput = $('#userInput').val();
var result = userInput inGardinerToUnicodeCodePoint
? 'Value of key \'userInput\' -> ' + userInput
: 'No code found!';
console.log(result);
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text"id="userInput"><buttonid="convert">Submit</button>
Post a Comment for "Javascript - How To Show Value From Object By Matching User Input To Its Key?"