Array printing results from data - javascript

I'm having trouble thinking of a JS function for the following idea. I want to have an array with 5 names. I also want to have a input box with a submit button. When I enter a number (1-5) I want to have it print the name that is assigned with that number from the array. Any ideas?
I have the button/input box setup but I'm not sure how the code would work.

Are you looking for something like this? JSFiddle attached https://jsfiddle.net/kgLnc6nd/
HTML
<input id='i1'/><br>
<button onclick='javascript:show()'>Click</button><br>
<div id='d1'></div>
JAVASCRIPT
var names = ['michael','henry','james','rebecca','allison'];
function show() {
var x = i1.value;
d1.innerHTML = names[x];
}

Related

How to refresh an Input field after changing its value with JQuery?

I have an Input element in HTML (and a Javascript template) with empty Value. Throught AJAX and JQuery, I update the said value to a list of words split by comma. Each word should become green retangulars with an 'X' to remove it from the field. The same list of words works perfectly when I write it down in the code.
The problem is that when I put this very same string in the Value attrib. using JQuery, it just doesn't work properly. I just get plain text, and those fancy green retangulars only appear when I click inside the input field and hit TAB key. Then They become one item only and when I finally click to remove it, then they got split(!).
I have already tried using fadeOut() and fadeIn() and refresh method. Did not work.
Any ideas about this?
HTML:
<input id="tags_1" type="text" class="tags form-control" value="" />
AJAX/JQUERY:
var tags_x = tags_x.replace(/\,/g, ', ');
var tags_x = tags_x.split(',');
$('#tags_1').val(tags_x);
$('#tags_1').attr('value', tags_x);
$('#tags_1').fadeOut();
$('#tags_1').fadeIn();
Your id of the input is tags_1 but you are selecting it like #tags_1_tag. Why is that? I think maybe that could be the reason.
And by the way when you use var tags_x = tags_x.split(','); tags_x is an array now. If you want to put it in a value convert it to a string and then try to put it in the value attr. You can see an example below:
var new_x = tags_x.join('')
$('#tags_1_tag').val(new_x);

How to get a string input and store it into a var

I know it's simple and there's probably something wrong with my syntax but I just don't understated it. I'm talking about the following:
//declaration of a string
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
str_input = $('input[name=po]').val();
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
That's it, can you help me to sort it out? The problem so far is that str_input is undefined regardless of what is written in the input, though, it saves its initial value.
Your html tag is invalid:
<input type"text" name = 'po' id="po" value="asd">
Should be:
<input type="text" name = 'po' id="po" value="asd">
// ^ Missing this character (=)
Ok, Now I understood, you can do 2 things, first, you can create a button than when the user clicks it calls the function to store the value in the variable like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$("#MyButton").click(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
<input type="button" id="MyButton" value="Click Here" />
Or the blur function when the user lose focus of the input text like this:
var str_input = "";
//this is supposed to get the new inputs and to store them in str_input
$(document).ready(function(){
$('input[name=po]').blur(function(){
str_input = $('input[name=po]').val();
})
});
//this is on html side, this should make an input field where the user to type in the needed
<input type"text" name = 'po' id="po" value="asd">
Ok, so here is the solution, though it's a little bit in "from Alf to Alf" style. So, yes, the code I've posted in the main post uses correctly the 'by default' value of the input but the problem comes from that nothing is checking for further changes in the input text field. I'm using $(document).ready... which as far as I know runs during the web project is opened and of course enables the use of some jquery methods within it. There is an interesting function called .change() which actually put the whole thing up for me. Take a glance at the following:
$(document).ready(function(){
$('input[type="text"]').change(function(){
str_input = $('input[name=polynom]').val();;
});
str_input = $('input[name=polynom]').val();
});
The second, third and fourth line make the magic actually, where the code in the .change() method updates str_input on each time a change have appeared in the input box field, whereas the str_input = $('input[name=polynom]').val(); outside of change() takes into account the initial value of the input. That's it... I knew I was forgetting something and yeah...
P.S. Another approach is to use a function and a button (a.k.a. an event-triggered function) which to 'update' the str_input on event. For this way check the post bellow this one.

How can I assign a submit button's id to a javascript variable

First post on Stack, thanks in advance.
I have a webpage that has 8 different forms, and on submit, I would like each one to display a different set of strings that I have stored in JavaScript arrays. The code to display the array works fine when used with only one form on the page, but I can't get it to work with all 8.
I have assigned each submit button an id, and am trying to assign that id to a variable called "chosen button" on submit. "chosen button" ultimately corresponds to the appropriate array, but only if the id is assigned to the variable. Here is html code:
<form id="ipsum-form" action="#" method="post">
<input type="submit" class="button" id="corporate" value="And So Forth.." />
And Javascript (my array variables and switch statement are obviously much longer):
var chosen_button = $("#ipsum-form submit").id;
var corporateIpsum = ["corporate jargon", "etc etc"];
switch (chosen_button){
case "corporate":
words = corporateIpsum;
break;
}
Is this the correct way to assign the submit button's ID to the variable? If not (or if this doesn't work for what I want), how can I make this work?
Cheers and I look forward to posting and learning more here in the future.
easy:
var chosen_button = $("#ipsum-form [type='submit']")[0].id;
or plain js:
document.forms[0].querySelectorAll('input[type="submit"]')[0].id;
Try var chosen_button = $('#ipsum-form .button').attr('id');. You can also use handlers to get the object (more useful in some situations) ex:
$('#ipsum-form input[type="submit"]').click(function () {
var chosen_button = $(this).attr('id');
// more code.
});
EDIT: Little bit more correct.

JS Replacing form inputs with user input

I'm a novice with javascript, and am struggling with my final project for a class. We're essentially making an online quiz. It's a math quiz, and I've set up forms with text input fields for the answer, and those forms are within div containers. I'm trying to create a function that, upon clicking a submit button, will pull the value of the user's input, and use that value to replace the form as the inner html of the div. This way the answer will be committed and cannot be changed after the user submits their answer. One key step of this is that the digits of the answer are entered individually - a field for the tens column, a field for the ones. I'm trying to pull those separately, concatenate them, and then compare them with the calculated actual answer. The actual answer will replace the submit button, color coded to reflect whether the user was correct or not. Here's what I have:
var firstNumber = Math.floor((Math.random()*50)+1);
var secondNumber = Math.floor((Math.random()*50)+1);
var generate = function(){
document.getElementById("addends1").innerHTML=firstNumber;
document.getElementById("addends2").innerHTML=secondNumber;
};
var evaluate = function(){
var result = firstNumber+secondNumber;
document.getElementById("button").innerHTML=result;
var tens = document.getElementById("result10s").value;
var ones = document.getElementById("result1s").value;
var entry = tens + ones;
document.getElementById("resultContainer").innerHTML=entry;
var cO = document.getElementById("cO").value;
document.getElementById("carryOverContainer").innerHTML=cO;
var answer = parseFloat(entry);
if (answer===result) {
document.getElementbyID("resultContainer").style.color="#b2f078";
} else {
document.getElementbyID("resultContainer").style.color="#e87c73";
}
};
document.getElementById("button").onclick=evaluate();
(the first function is called in the html tag, onload for the button image)
Thanks!
Edit: My problem is just that my code isn't doing anything at all. I don't know if that has to do with how I'm calling the "evaluate" function, or the function itself. I want to replace all form fields with their entered values, and then also replace the button with the correct answer to the addition problem. Here's my html:
<body>
<div id="carryOverContainer">
<form>
<input type="text" name="carryOver" id="cO"/>
</form>
</div>
<div id="addends1" class="addends"> </div>
<div id="addends2" class="addends"> </div>
<div id="resultContainer">
<form>
<input type="text" id="result10s" class="result">
<input type="text" id="result1s" class="result">
</form>
</div>
<div id="button" onclick=evaluate();>
<img src="next.png" alt="next" onload="generate();"/>
</div>
</body>
I'm suspecting the problem may lie in how I'm trying to pull and store the values from the form fields?
As there are potentially many issues, I'll help you in steps rather than try to give you the whole solution. (It's the weekend now, so I can respond more frequently.)
The first issue is in the way you're defining and using functions. Your syntax, i.e.
var evaluate = function() {
// ...
}
defines an anonymous function assigned to the variable generate. For comparison, here's how regular functions are defined:
function evaluate() {
// ...
}
Your syntax can work if called properly, but you're calling it like a regular function:
document.getElementById("button").onclick=evaluate();
What's happening is, whereas for a regular function, the function evaluate() would get assigned to the onclick event, for an anonymous function, evaluate and () are interpreted as call the anonymous function in this variable. Therefore, evaluate() is getting called right away, instead of onclick! Here's a JSFiddle that shows how your form fields are immediately replaced.
Once you've fixed this issue, update your question and comment on my answer to grab my attention, and we'll take it from there.
By the way, if you're using Chrome, hit CtrlShiftI and go to the Console tab to see if your Javascript is throwing any issues. Firefox has a similar feature—look for developer tools in the menu.

Inserting values into input tag via buttons

I am making a calculator just for fun to learn about Javascript (I know HTML & CSS very well)and I have the basis of the calculator made. I wanted to make it so that you just use the buttons. The buttons work and all. But for example if I wanted to insert 11, that wouldn't be possible because I can only insert single digits and I don't know why :(
Here is the button you press to insert the number 1.
<button type="button" onclick="no1 ()">1</button>
This is the javascript to insert he number 1 into the input tag:
var currentinput= document.getElementById("firstnumber");
var answer= document.getElementById("answer");
function no1 ()
{
currentinput.value=1;
answer.value=1;
}
How would I able to insert 11 instead of just 1?
if you want to add something at the end of variable, you could use something like this:
function no1 ()
{
currentinput.value = currentinput.value+"1";
answer.value=1;
}
this will take numbers already in the currentinput.value and add 1 at the end.

Categories