如何从选择列表中获取值?

时间:2023-01-20 12:11:54

I am trying to get a value from a select list that will determine what my form method is, either get or post. I am having trouble doing this though. Any suggestions?

我试图从选择列表中获取一个值,该列表将确定我的表单方法是get还是post。我这样做有困难。有什么建议?

<select name ="optionlist" form ="form" id="test">
  <option value="get">GET</option>
  <option value="post">POST</option>
</select>

<form name="input" action="" method="" id="form">
    <input type="text" name="search">
    <input name="buttonExecute" type="submit" value="Submit"/>
</form>

JS

function myFunction(input){
    alert("You typed in : " + input);
}

function load(){
    alert("Page Loaded! This is the current text in the textbox : "+ document.getElementsByName('search')[0].value);
}

func

window.onload = load;

Any help will be greatly appreciated! Thanks!

任何帮助将不胜感激!谢谢!

2 个解决方案

#1


1  

First you add an event listener to your select element, to trigger a function when it's value changes:

首先,为select元素添加一个事件监听器,以便在值改变时触发一个函数:

document.getElementById('test').addEventListener('change', setFormMethod, true);

Second you make sure your triggered function changes the form's method attribute:

其次,确保触发的函数更改了表单的方法属性:

function setFormMethod(e) {
  document.getElementById('form').setAttribute('method', e.target.value);
}

EDIT

<html>
 <head>
 </head>
 <body>
  <!-- your HTML here -->
 <script>
  // my code here
 </script>
</body>

#2


0  

I believe this would work

我相信这会奏效

$("#yourDropdownId").change(function() {
    value = $( "#yourDropdownId option:selected").val()
    if (value === 'post')
        $("#yourFormId").attr("method", 'POST')
    else
        $("#yourFormId").attr("method", 'GET') 
});

#1


1  

First you add an event listener to your select element, to trigger a function when it's value changes:

首先,为select元素添加一个事件监听器,以便在值改变时触发一个函数:

document.getElementById('test').addEventListener('change', setFormMethod, true);

Second you make sure your triggered function changes the form's method attribute:

其次,确保触发的函数更改了表单的方法属性:

function setFormMethod(e) {
  document.getElementById('form').setAttribute('method', e.target.value);
}

EDIT

<html>
 <head>
 </head>
 <body>
  <!-- your HTML here -->
 <script>
  // my code here
 </script>
</body>

#2


0  

I believe this would work

我相信这会奏效

$("#yourDropdownId").change(function() {
    value = $( "#yourDropdownId option:selected").val()
    if (value === 'post')
        $("#yourFormId").attr("method", 'POST')
    else
        $("#yourFormId").attr("method", 'GET') 
});