首页 文章

Javascript:从两个文本输入和一个单选按钮输入生成一个URL

提问于
浏览
0

我有一个表单,其中包含两个仅限整数的文本框,一组单选按钮和一个提交按钮 . 我希望它采用这三个输入的值,并使用它们生成一个包含三个变量的URL,如下所示:

http://domain.com/file.php?var1=&var2=&var3=

编辑:为了澄清,输出在页面上,而不是在URL中 . 我已经创建了一个基于URL变量显示不同内容的php图像,并且该图像应该能够在用户认为合适的其他站点上使用 .

EDIT2:我的基本HTML:

<form>
<input type="text" id="var1" />

<input type="text" id="var2" />

<input type="radio" name="var3" value="1" />
<input type="radio" name="var3" value="2" />

<input type="button" id="URLGenerate" value="Generate" /> </form>

1 回答

  • 1

    那么,这是你如何解决这个问题:

    1.创建HTML

    您需要为每个文本框分配 id (文本框在html中定义为 <input type="text"/> . 然后您需要定义为 <input type="radio"/> 的单选按钮 . 确保所有单选按钮具有相同的 name 属性 . 这是short intro .

    2.使用Javascript获取值

    您可以通过其ID访问每个元素 .

    3.更改当前URL

    创建URL后,您可以通过在Javascript中分配 window.location 来更改它 .

    我想如果有人想让它变得更简单,他们必须为你输入代码! ;)

    Update

    使用您添加到问题中的代码,我创建了一个解决问题的javascript程序:

    //assign the button event handler
    document.getElementById( 'URLGenerate' ).addEventListener( 'click', onGenerate );
    
    //given the name of a radio button group, it returns the value of the selected radio button or null if none of them are selected
    function getRadioButtonValue ( name ) {
      var allRadios = document.getElementsByName( name );
      for ( var i = 0; i < allRadios.length; i++ ) {
        if ( allRadios[i].checked ) {
          return allRadios[ i ].value;
        }
      }
      return null;//or any other value when nothing is selected
    }
    
    function onGenerate() {
      //the base url
      var url = 'http://domain.com/file.php';
      //an array of all the parameters
      var params = [];
      //get the value from the edit box with id=var1
      params.push( 'var1=' + document.getElementById( 'var1' ).value );
      //get the value from the edit box with id=var2
      params.push( 'var2=' + document.getElementById( 'var2' ).value );
    
      //get the value of the radio box
      params.push( 'var3=' + getRadioButtonValue( 'var3' ) );
    
      //join all the parameters together and add to the url
      url += '?' + params.join( '&' );
      alert( url );
    }
    

    这是一个JSBin to try it live,你可以在这里看到HTML / JS:http://jsbin.com/itovat/3/edit

相关问题