Javascript variable equal a textbox value -


i getting problem when try pass pop_size variable equal value of textbox. variable used in along script value of textbox. when click on button value change , update value of variable , reload page , variable set value in textbox.

<form name="myform1" action="" method="get">      input number of populations<br />     <input type="number" name="pop" id="pop" value=5 /><br />     <input type="button" name="b1" id="b1" value="click set"             onclick="setvalue()" /><br />  </form>   

function setvalue() {      var test, test1;     test=parseint(document.getelementbyid('pop').value);     pop_size = test; }  

if i'm understanding properly, you're having variable set works fine until reload, gets lost.

there 2 basic strategies know of making variable survive page reload.

the first 1 i'll list seems more complicated. i'll give basics of it, , can tell more if need. once have value, append address of web page within query string. window.location += "?pop_size=" + pop_size; has lot of inherent difficulties: you'll have have script checks query string , extracts pop_size it, , should replace existing pop_size in query string when update it. can work, , can find plenty of web pages discuss query strings , javascript, there easier ways.

if you're using html5, easier solution use sessionstorage. it's supported in major browsers, first link provided (to mdn) gives polyfill can give backward compatibility. let store variables on browser stay live until user closes browser window.

to save value, mdn recommends do:

sessionstorage.setitem("pop_size", pop_size); 

and retrieve values on pageload with:

document.getelementbyid('pop').value = sessionstorage.getitem("pop_size") || 5;  // if it's not found, default 5. 

honestly, i've never seen syntax, , i'm not sure why mdn recommends it. more standard usage of sessionstorage object easier:

sessionstorage.pop_size = pop_size; ... document.getelementbyid('pop').value = sessionstorage.pop_size || 5; // if it's not found, default 5. 

Comments

Popular posts from this blog

java.util.scanner - How to read and add only numbers to array from a text file -

rewrite - Trouble with Wordpress multiple custom querystrings -