Pam
Pam

Reputation: 9

How to store a javascript function value inside a php variable

function check_val(val) {
   document.getElementById("select_action")=val; 
   alert(val);
   return val;
}

this is my javascript function

<select name='select'  id='select'   onchange='check_val(this.value)'> 
<option value='0'><------select------></option>
<option value='4'>apple</option>
<option value='5'>mango</option>
<option value='6'>berry</option>
</select>
<?php <input type=hidden name='select' value=???> //by using javascript I need the value

this is my select tag now I want to put the values inside a hidden field

Upvotes: 0

Views: 704

Answers (2)

Amien
Amien

Reputation: 974

Pam, you don't need php at all for this, just set the value of the hidden input in your javascript function with the manipulated val

function check_val(val) {
    val++;  // do things to val (add 1) 
    document.getElementById("hidden_input").value=val; //set value in the hidden input
    return;
}

Make sure your hidden input has an ID

<select name="select" id="select" onchange="check_val(this.value)"> 
    <option value='0'><------select------></option>
    <option value='4'>apple</option>
    <option value='5'>mango</option>
    <option value='6'>berry</option>
</select>

<input id="hidden_input" type="hidden" name="hidden_input" value="0">

On the page that you are posting to, you will access the data in PHP with

echo $_POST['hidden_input'];
// or
echo $_REQUEST['hidden_input'];

Upvotes: 0

Bobert123
Bobert123

Reputation: 113

a few things here:

  1. to post into a different page from javascript, you could use .post(...) or $.ajax({ type: 'post',... there's an example of the latter in the answer here

  2. hidden html inputs are useful for storing values, but they do not need to be inside php tags, which I think is what adeneo was pointing out

  3. your hidden input does not have an id, only a name, and the name is the same as your select box

  4. you are trying to reference something using getElementById("select_action"), but you don't have anything with that id.

Upvotes: 1

Related Questions