将JavaScript变量传递到HTML输入框和(在PHP文件中使用)


pass JavaScript variable to HTML input box and (to use in PHP file)

我正试图将一个JavaScript变量传递给一个隐藏输入按钮的值,以便在我的PHP文件输出中使用。

我的HTML是:

<input type = "hidden"  id = "location2" name = "location2" value = ""/>

我在"提交表单"输入中使用onclick="myFunction();"来运行该函数,因为它无法在窗口中完成。load()

我下面的JavaScript正在从另一个函数调用索引,并将文本分配给变量"location"(我知道这听起来很奇怪,但这是我迄今为止唯一能让它工作的方法):

function myFunction() {
var x = document.getElementById("box2").selectedIndex;
var y = document.getElementById("box2").options;
var location=(y[x].text);
 document.getElementById("location2").value=(location);
 }

任何帮助都将不胜感激,因为我真的很挣扎,并且已经为此工作了一段时间(你可能知道,我真的不知道我在做什么)-我只需要将这个变量的值调用到我的PHP文件输出中,我的大部分web表单就完成了。

非常感谢

Marcus

我刚刚更改了HTML如下我已经从提交中删除了myFunction

我添加了以下HTML按钮:

 <button onclick="myFunction();" id = "location2" name = "location2" value="">Click me</button>

变量现在正在传递!!!!唯一的问题是,当我按下onclick按钮时,它现在正在提交我的表单!!

我可以用这个代码替换我以前的提交按钮吗??

感谢大家在这方面的帮助!!

我不确定您在做什么,但下面的示例可能会对您有所帮助。它将发布值以及选项文本。

这里我们使用print_r从AJAX请求中打印$_POST数组。使用此方法,您应该能够调试该问题。

<!DOCTYPE html>
<html>
<body>
<?php if($_POST) { 
    print_r($_POST); die;
} ?>
<form name="" id="" method="post" >
Select a fruit and click the button:
<select id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>
<input type = "hidden"  id = "location2" name = "location2" value = ""/>
<input type = "hidden"  id = "locationname" name = "locationname" value = ""/>
<button type="submit" id="submit">Display index</button>
</form>
<script>
function myFunction() {
    var x = document.getElementById("mySelect").selectedIndex;
    var y = document.getElementById("mySelect").options;
        //alert("Index: " + y[x].index + " is " + y[x].text);
    document.getElementById("location2").value=(y[x].index);
        document.getElementById("locationname").value=(y[x].text);
    //alert($("#location2").val());
}
var submit = document.getElementById('submit');
submit.onsubmit = function(e){
    myFunction();
};

</script>
</body>
</html>

我假设您的表单方法是"POST",并且操作值与您希望看到"location2"隐藏输入值的php页面相同,如果是这样的话,您可以使用$_POST['location2']在该php页面中获取值。

是的,默认情况下可以使用按钮标记,它的作用就像表单标记中的提交按钮。您还可以通过使用属性type='button'使其表现为按钮(不会提交表单)。

已编辑

buttoninput type='submit'只能在form放置在form标记内时提交(无javascript)。

<form action='http://www.stackoverflow.com/'>
  <button>stackoverflow</button> <!-- this works -->
</form>

<form action='http://www.stackoverflow.com/'></form>
<button>stackoverflow</button><!-- this won't work -->

var go = function() {
  document.forms[0].submit();
};
<form action='http://www.stackoverflow.com/'></form>
<button onclick='go()'>stackoverflow</button><!-- still works -->