JS Replacing form inputs with user input - javascript

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.

Related

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.

Javascript variable equal a textbox value

I am getting a problem when I try to pass a the pop_size variable equal to the value of the textbox. This variable will be used in along the script with the value of textbox. When I click on the button the value change and update the value of variable and then I reload the page and the variable is set to the value in the textbox.
<form name="myform1" action="" method="get">
Input the number of populations<br />
<input type="number" name="pop" id="pop" value=5 /><br />
<input type="button" name="b1" id="b1" value="Click to set"
onClick="setValue()" /><br />
</form>
function setValue() {
var test, test1;
test=parseInt(document.getElementById('pop').value);
pop_size = test;
}
If I'm understanding you properly, you're having a variable set that works fine until you reload, but then gets lost.
There are two basic strategies I know of for making a variable survive a page reload.
The first one I'll list seems more complicated. I'll give you the basics of it, and can tell you more if you need. Once you have the value, append it to the address of the web page within the query string. It would be something like window.location += "?pop_size=" + pop_size; but that has a lot of inherent difficulties: you'll have to have a script that checks for the query string and extracts pop_size from it, and you should replace any existing pop_size in the query string when you update it. It can work, and you can find plenty of web pages that discuss query strings and javascript, but there are easier ways.
If you're using HTML5, the much easier solution is to use sessionStorage. It's currently supported in all major browsers, but the first link I provided (to MDN) gives you a polyfill that can give you backward compatibility. It will let you store variables on the browser that will stay live until the user closes the browser window.
To save the value, MDN recommends that you do:
sessionStorage.setItem("pop_size", pop_size);
and retrieve the values on pageLoad with:
document.getElementById('pop').value = sessionStorage.getItem("pop_size") || 5; // if it's not found, default back to 5.
Honestly, I've never seen that syntax, and I'm not sure why MDN recommends it. The more standard usage of the sessionStorage object is even easier:
sessionStorage.pop_size = pop_size;
...
document.getElementById('pop').value = sessionStorage.pop_size || 5; // if it's not found, default back to 5.

How to use HTML forms without a server

I am not a web-developer and want to understand the better way to pass variables. In the past I have used various ways to pass things to java script functions. I have never used forms as I always associated them with server and databases. I have a website in which user selections change the contents of the website.
I am wondering if you can use forms without any server just as a way to pass a few things to a javascript function where they are used to change the page content. For basic example, if someone selects male the page background becomes blue, if they choose female the background becomes pink. Would forms be the way to go and just onsubmit call a javascript function? How would I actually pass the form contents to the javascript function?
Yes you absolutely can use forms/inputs/any kind of html element and never talk to a server, just don't expect to store that data! You're right about using events (like the onsubmit one you mentioned) to trigger Javascript functions.
Here is a quick and dirty example (heavy on the dirty) that does sorta kinda what you'd like. Note that instead of waiting for the form to be submitted before the color change, I go ahead and do it immediately after they choose a gender from the dropdown.
http://jsfiddle.net/wG8K4/1/
You wouldn't pass the parameters. You could have "onsubmit" call a javascript function, and then within the function use javascript to access the actual controls that the user has selected. You could use the GetElementById function to retrieve a certain element, and then determine the value of that element.
If all you wanted to do was change the background color, you could use javascript to change the backgroundColor property of the body tag or any tag on the page.
You'd have to remember to return false from your function, though -- otherwise, the form would be submitted.
You don't need servers / databases to use forms. Forms are simply a method from passing variables from one file to another, regardless if that is an html file or some php script or what have you. If you stick to using GET forms, your form will naturally pack its data into the URL of your page at which time you can access them. For instance (borrowed from http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/):
<script language="javascript">
function $_GET(q,s) {
s = s ? s : window.location.search;
var re = new RegExp('&'+q+'(?:=([^&]*))?(?=&|$)','i');
return (s=s.replace(/^?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
}
var usersName = $_GET('username');
if(typeof(usersName)!='undefined'){
document.write('<h1>Hi there, '+usersName+'</h1>');
}
</script>
<form>
<input type="text" name="username" />
<input type="submit" value="Say my name" />
</form>
The basic event you're going to look for is the form's submit event. If you're okay with just using event handlers, you can just do something like this:
var myForm = document.getElementById('myForm');
myForm.onsubmit = function () {
// ...
};
Because you're just using JavaScript, you don't want the form to actually submit. (Side point: Because you're using JS, you should just build this form and add it to the page with JS, but that's a completely different issue.) You can cancel the form's default action like so:
myForm.onsubmit = function () {
// ...
return false;
};
Before we get into accessing data, make sure that you grab the elements you're going to need. It makes things a little faster, because you don't have to select the entire element from the DOM every time the form is submitted. For example:
var myForm = document.getElementById('myForm'),
myTextField = document.getElementById('myTextField'),
mySelectBox = document.getElementById('mySelectBox'),
// ...
Depending on what kind of form elements you have, there are different ways to access their data. Text inputs, text areas, and select boxes are really easy:
var textValue = myTextField.value,
selectValue = mySelectBox.value;
Radio buttons and check boxes are a little more complicated, because you have to go through every single one and see which one(s) is/are checked and which one(s) isn't/aren't, like so:
var isOneChecked = checkboxOne.checked,
isTwoChecked = checkboxTwo.checked;
Going with your example of blue/pink background, you would probably want something similar to this:
var myForm = document.getElementById('myForm'),
maleBox = document.getElementById('maleBox');
myForm.onsubmit = function () {
var isMale = maleBox.checked;
if (isMale) {
document.body.style.backgroundColor = 'manlyBlue';
} else {
document.body.style.backgroundColor = 'sexistPink';
}
};
Notes
If you do decide to go with event handlers, keep in mind that only one can be applied to your form at a time. If you want to attach a different function to the submit event as well, you'll have to go with event listeners, which is a completely different ball game and introduces problems of its own.
The final example only checks the value of the "I'm a guy" element, because (presumably) you're using radio buttons and you only have two options. If "I'm a guy" is not checked, then the other one should be. But if the form starts out with neither option checked, then that could be considered a bug.
The final example also uses inline styles to change the body's background color. It hurt me to type. A much more bearable method would be to add/remove classes as needed, but again, that's kind of beyond the scope of this question.
Form elements can be used as a form of global variables - holding state that can be used and shared by all the javascript in a single page.
However, this could result in brittle and difficult to understand code.
I suggest keeping with passing parameters to functions, so long as you are in the context of a single page.
If you need to pass data to another page, then forms can make life easier - using a GET form, the values on the form will be passed to the page referenced in the form action attribute as key-value pairs. If you use the POST method they will be transferred in the headers.
If your desire is to iterate through form elements using Javascript you can easily do this using the DOM since the form will have a length property and each input will be represented as an index of this array-like object:
So for:
<form id="f" action="">
Male<input type="radio" name="gender" value="male" />
Female<input type="radio" name="gender" value="female" />
<input type="submit" value="submit" />
</form>
You could do something like this:
var f = document.getElementById('f');
f.onsubmit = function (e) {
e = e || window.event;
var et = e.target || e.srcElement,
gender;
if (e.preventDefault) { e.preventDefault(); } else { e.returnValue = false; }
for (var i = 0, il = et.length; i < il; i++) {
if (et[i].name = 'gender' && et[i].checked) {
gender = et[i].value;
}
}
if (gender == 'male') {
document.body.style.backgroundColor = 'cyan';
} else if (gender) {
document.body.style.backgroundColor = 'pink';
}
};
See example →

Clear default values using onsubmit

I need to clear the default values from input fields using js, but all of my attempts so far have failed to target and clear the fields. I was hoping to use onSubmit to excute a function to clear all default values (if the user has not changed them) before the form is submitted.
<form method='get' class='custom_search widget custom_search_custom_fields__search' onSubmit='clearDefaults' action='http://www.example.com' >
<input name='cs-Price-2' id='cs-Price-2' class='short_form' value='Min. Price' />
<input name='cs-Price-3' id='cs-Price-3' class='short_form' value='Max Price' />
<input type='submit' name='search' class='formbutton' value=''/>
</form>
How would you accomplish this?
Read the ids+values of all your fields when the page first loads (using something like jquery to get all "textarea", "input" and "select" tags for example)
On submit, compare the now contained values to what you stored on loading the page
Replace the ones that have not changed with empty values
If it's still unclear, describe where you're getting stuck and I'll describe more in depth.
Edit: Adding some code, using jQuery. It's only for the textarea-tag and it doesn't respond to the actual events, but hopefully it explains the idea further:
// Keep default values here
var defaults = {};
// Run something like this on load
$('textarea').each(function(i, e) {
defaults[$(e).attr('id')] = $(e).text();
});
// Run something like this before submit
$('textarea').each(function(i, e){
if (defaults[$(e).attr('id')] === $(e).text())
$(e).text('');
})
Edit: Adding some more code for more detailed help. This should be somewhat complete code (with a quality disclaimer since I'm by no means a jQuery expert) and just requires to be included on your page. Nothing else has to be done, except giving all your input tags unique ids and type="text" (but they should have that anyway):
$(document).ready(function(){
// Default values will live here
var defaults = {};
// This reads and stores all text input defaults for later use
$('input[type=text]').each(function(){
defaults[$(this).attr('id')] = $(this).text();
});
// For each of your submit buttons,
// add an event handler for the submit event
// that finds all text inputs and clears the ones not changed
$('input[type=submit]').each(function(){
$(this).submit(function(){
$('input[type=text]').each(function(){
if (defaults[$(this).attr('id')] === $(this).text())
$(this).text('');
});
});
});
});
If this still doesn't make any sense, you should read some tutorials about jQuery and/or javascript.
Note: This is currently only supported in Google Chrome and Safari. I do not expect this to be a satisfactory answer to your problem, but I think it should be noted how this problem can be tackled in HTML 5.
HTML 5 introduced the placeholder attribute, which does not get submitted unless it was replaced:
<form>
<input name="q" placeholder="Search Bookmarks and History">
<input type="submit" value="Search">
</form>
Further reading:
DiveintoHTML5.ep.io: Live Example... And checking if the placeholder tag is supported
DiveintoHTML5.ep.io: Placeholder text
1) Instead of checking for changes on the client side you can check for the changes on the client side.
In the Page_Init function you will have values stored in the viewstate & the values in the text fields or whichever controls you are using.
You can compare the values and if they are not equal then set the Text to blank.
2) May I ask, what functionality are you trying to achieve ?
U can achieve it by using this in your submit function
function clearDefaults()
{
if(document.getElementById('cs-Price-2').value=="Min. Price")
{
document.getElementById('cs-Price-2').value='';
}
}

Categories