Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass & Display Javascript Variable in HTML Form Value

I am trying to pass a Javascript variable to an HTML textbox and want that variable to be visible before passing to an onclick function.

First I encode a php variable (passed from another script) to a javascript variable:

var id = <?php echo json_encode($id);?>

I then try to attempt to make the value of the textbox equal to the javascript id variable:

<input type="text" id="getfromweb" value="">
<input type="button" value="Get From Web..." onclick="getFromWeb(document.getElementById('getfromweb').value = id)"><br>

However I am not seeing the id var displaying as the value of the textbox?

I thought the solution was to pass the id as the value in the function:

onclick="getFromWeb(document.getElementById('getfromweb').value = id)

But this doesn't work, that is the variable does not appear in the text box.

The getfromweb function starts off like this:

function getFromWeb(webid)
    {
        var webid=document.getElementById('getfromweb').value;
        var http_request=false;
        http_request = new XMLHttpRequest();
        http_request.open('GET', 'getfromweb.php?id='+webid, false);

Any help appreciated.

like image 654
Hexana Avatar asked Mar 11 '26 03:03

Hexana


1 Answers

Theres a bunch of weird stuff going on here.

  1. The webid parameter in getFromWeb(webid) is lost when you overwrite it by declaring another variable with the same name: var webid=document.getElementById('getfromweb').value;
  2. onclick="getFromWeb(document.getElementById('getfromweb').value = id)" this code only gets called when you click the button. That's what onclick means. document.getElementById('getfromweb').value = id is not running until you click it, even though you said you want it displayed before you click it. It won't do anything on page load until its clicked.

But why not use php to echo it in the html value in the first place? Like this:

<input type="text" id="getfromweb" value="<?php echo $id ?>" />

Then you could simplify this:

 <input type="button" value="Get From Web..." onclick="getFromWeb();" />

And get rid of the parameter in this:

function getFromWeb()
{
    var webid=document.getElementById('getfromweb').value;
    ...
 }
like image 61
Ben Lorantfy Avatar answered Mar 12 '26 16:03

Ben Lorantfy