Javascript variable equal a textbox value - javascript

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.

Related

Insert the value retrieved from localstorage to the input field

I am using localStorage where in I am able to store in previous page and retrive it in this page. (Checked it using alert).
name12=localStorage.getItem("content");
Now my requirement is to display it into the input field and make it non-editable.
Please help me out with it. I have tried different things but I am not able to get it right.
Used onblur="localStorage.setItem(this.name, this.value) in the input tag
and also tried to use
if name_2.value = name12; in script tag
To make a field uneditable, you can use the html attribute disabled on the input field. http://www.w3schools.com/tags/att_input_disabled.asp
To set a default value for a field, you can use the html attribute value. In your case since the value is dynamic, you probably want do not want to do that inline in the html. One possible solution is to set the value attribute through javascript like below.
<script type="text/javascript">
var name2 = document.getElementById("name_2");
name2.value = localStorage.getItem("content");;
</script>
Set the value of an input field
You have to assign the value to input using javascript.
<input username" id="name_2" type="text" placeholder="name" name="name_2" required="required" autofocus="autofocus">
<script>
var n = "5"; // read from storage here
var inpt = document.getElementById("name_2");
inpt.value = n;
inpt.disabled = true;
</script>
There are many places to find this information. Try reading the jquery documentation when you get stuck. For example, here is a page that describes how to set the value of an input element. StackOverflow also has many questions about this topic. A quick google search brings up this question about setting the value of input elements. We can also find SO questions about disabling input elements easily, like this one.
I encourage that you attempt to use more resources to find what you need before bringing your questions here.
Based on the answers to the questions I linked, we can set the input and then disable it to keep the value from changing:
$('#input').val(name12);
$('#input').prop('disabled', true);

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.

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='';
}
}

javascript cannot call an element in array

Ok, let me explain more... the goal is to make the checkbox checked if there's a change on select. The actual code was:
function checkit(date)
{
document.forms[0].date.checked = true;
}
<input type="checkbox" name="date[]" value="2008-08-14">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
<input type="checkbox" name="date[]" value="2008-08-15">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
<input type="checkbox" name="date[]" value="2008-08-16">Aug 14, 2008<br>
<select name="slot[]" size="1" onchange="checkit(date[]);"/>
<option value="2008-08-15;0900;1700">9am to 5pm</option>
<option value="2008-08-15;1330;1730">1:30pm to 5:30pm</option>
</select>
In PHP, if it sees a variable with [ ], it automatically creates an array. In Javascript, I expected that Javascript would recognize the [] and execute based on the current element. For example, if I select a value in the second checkbox, it should fire an event to check that element box. I don't want to name the variable like date1, date2, date3, date4... I hope this clarifies more. I know I am missing out something... I tried "this" keyword to make it "this current element" but it doesn't seem to work but it could be that I used the improper syntax.
What I expected was that onchange event, it should fire its argument which is "date[]" but I would assume that Javascript should know which element in date[] it will use instead of expliciting calling it date[1] and so on. The checkit function gets the "date[]" name and checks that date[] checkbox.
BTW, many thanks for the supplementary answers (I learned something new!)
It doesn't work because (as dreas said) your HTML-code has errors and you are naming your variables in a way that conflicts with javascript syntax.
The name of your input is date[1] and the [ and ] have special meaning in javascript code.
In this code:
document.forms[0].date.checked = true;
you are trying to access the documents first form (document.forms[0]) and then tries to access a field called date, but there aren't any. According to your HTML-markup you have fields called "date[1]", "date[2]" and "date[3]".
But you can't access them like this:
document.forms[0].date[1].checked = true;
Why? Because date[1] tries to index the date with 1, and in this case your date is not an array.
You can access it if you enclose it in quotes:
document.forms[0]["date[1]"].checked = true;
Note that now "date[1]" is used as a string.
What exactly are you trying to do with this code ?
According to your piece of code (which has some syntax errors), you are checking a checkbox, then calling a js function that will check the checkbox again...?
What exactly are you trying to achieve?
Try this code:
function checkit(date)
{
var date = document.getElementById(date);
date.checked = true;
}
<input type="checkbox" id="date[1]" value="2008-08-14" onchange="checkit('date[1]')");/>Aug 14, 2008<br />
<input type="checkbox" id="date[2]" value="2008-08-14" onchange="checkit('date[2]')");/>Aug 14, 2008<br />
<input type="checkbox" id="date[3]" value="2008-08-14" onchange="checkit('date[3]')");/>Aug 14, 2008<br />
PHP has the syntax arr[] = something to put something at the next available index in an array.
Javascript doesn't have that syntax; if you want to put something at the next available index in an array use arr.push(something) instead.
But the portion of your example you're referring to is in HTML, not Javascript. Javascript accesses it but the form fields themselves are created in HTML... so you have to give it your own name rather than an automatically-incremented name.
If you are creating the HTML dynamically through DOM calls (e.g. for each input element, document.createElement('input'), assign attributes and then appendChild() to the main form), then you could automatically name the form fields... but that's a whole other method of generating HTML & has a bunch of pitfalls to watch out for.
First, you're wanting to use a PHP-specific feature in Javascript. No, there is no such feature so far as I can tell.
Second, I'd strongly advise not using HTML input names like "date[1]" ... that might be legal HTML (I'd have to try it in a few browsers to be sure it was effectively allowed), but it is almost 100% a likely source of errors in the maintenance cycle.
I'm assuming this code is either auto-generated for you or you just want to take a blok and copy/paste in your editor. If it is the former, I'd name the elements "date_1" in the autogen code and be done with it. If the latter then you can either maintain the number in your code (ie, manually type in date_1 through date_257) or use a Javascript document.write call to generate the HTML with less effort. I'd ONLY do the latter (document.write out HTML) if there is really no other way. If you're talking about 10-25 copies, handling this manually by hand is less likely to have a problem than using document.write; if you have more than 25 such instances then maybe it makes sense to automate the element generation.

Categories