#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2

    Can a javascript variable be passed to a form?


    Hello. I have a javascript function that counts the rows in a db and returns a random number. The variable is named rand. How can I insert this as a hidden value into a form?

    My javascript code...

    Code:
    //find total number of rows
    t.executeSql('SELECT COUNT(*) AS count FROM notes LIMIT ?',
    [trNotes.limit],
    function(t, result) {
    var row2 = result.rows.item(0),
    opts = {};
                                    
                                    
    //get a random row
    var x = row2.count; 
    var rand = Math.floor(Math.random()*x) + 1;

    My html form it needs to go in...

    Code:
    <form name="answer" method="GET">
    <input type="text" id="ans" style="background: white;" value=""  />
                   
    <a href="#" data-role="button" data-theme="a" data-inline="true" onclick="sendVal(); return false;">Submit</a>
    
    </form>

    I have tried the following, putting the number into a div but that does not work.

    Javascript... (I added the alert to make sure that rand is being passed which it is. It is just not showing in the form correctly)

    Code:
    //alert("" + rand + "");
    $("#photonumber").html("" + rand + "");
    Html...

    Code:
    <input type="text" id="number" value='<div id="photonumber"></div>'>



    Thanks for any help!
  2. #2
  3. A Not To Shabby Code Smurf
    Devshed Beginner (1000 - 1499 posts)

    Join Date
    Aug 2008
    Posts
    1,169
    Rep Power
    184
    You need to use .val() and not .html(). You could also use .attr() to set the value attribute.
    Code:
    $("#number").val("<div id=\"photonumber\">" + rand + "</div>");
  4. #3
  5. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,127
    Rep Power
    4304
    You can't put HTML tags as the value of an element's attribute. While not the case here, if you just want them to be text, it would be better to use the "&lt;" and "&gt;" character entities.
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    38
    Rep Power
    2
    Thanks Papa Smurf, you steered me in the right direction. This is what I ended up using...

    document.answerform.number.value=rand;

IMN logo majestic logo threadwatch logo seochat tools logo