【问题标题】:Radio button with an "other" text box not inputting value properly using javascript带有“其他”文本框的单选按钮未使用 javascript 正确输入值
【发布时间】:2011-01-26 19:01:24
【问题描述】:

我正在使用 html 表单控件和 javascript 创建一个表单,以帮助简化工作中的一些流程。我暂时把表格放到网上here

在表单的一个部分中,我有一个与单选按钮关联的文本框。当点击页面底部的“显示”按钮时,该部分中的其他单选按钮会正确显示其值,但带有文本框的单选按钮不会。似乎我没有正确地将文本框的值分配给单选按钮的值。我做错了什么?

这里是javascript:

<script LANGUAGE="JavaScript" type="text/javascript">

function display() {
  for (var i=0; i < document.form2.paymenttype.length; i++)
   {
   if (document.form2.paymenttype[i].checked)
      {
      var radio_paymenttype_val = document.form2.paymenttype[i].value;
      }
   }

  for (var i=0; i < document.form2.contracts.length; i++)
   {
   if (document.form2.contracts[i].checked)
      {
      var radio_contracts_val = document.form2.contracts[i].value;
      }
   }

  DispWin = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600')

  message = "<h2>Royalty Advance Payment Letter</h2>";
  message += "<hr />";
  message += "<span STYLE=\'font-family: Garamond\'>";
  message += "<p>" + document.form2.agentfirstname.value + "&nbsp;" + document.form2.agentlastname.value + "<br />";
  message += document.form2.agencyname.value + "<br />";
  message += document.form2.agentaddress1.value + "<br />";
  message += document.form2.agentaddress2.value + "<br />";
  message += document.form2.agentcity.value + ",&nbsp;" + document.form2.agentstate.value + "&nbsp;" + document.form2.agentzip.value + "<br />";
  message += document.form2.agentcountry.value + "<br />";
  message += "</p>";
  message += "<p>Dear&nbsp;" + document.form2.agentfirstname.value + ",</p>";
  message += "<p>Please find enclosed a check in the amount of&nbsp;$";
  message += document.form2.paymentamount.value + "&nbsp;representing the amount due upon&nbsp;";
  message += radio_paymenttype_val + "&nbsp;";
  message += document.form2.authorfirstname.value + "&nbsp;";
  message += document.form2.authorlastname.value + "'s&nbsp;<em>";
  message += document.form2.booktitle.value + "</em>.";
  message += radio_contracts_val + "</p>";
  message += "<p>Regards,<br /><br /><br /><br />My Name<br />Associate Editor</p>";
  message += "</span>";

  DispWin.document.write(message);
}
</script>

这是该部分的 HTML:

  <div class="required">
    <fieldset>

    <legend>Payment Type:</legend>
      <label for="payment_sig" class="labelRadio"><input type="radio" name="paymenttype" id="payment_sig" class="inputRadio" value="signature for" /> Signature</label>
      <label for="payment_danda" class="labelRadio"><input type="radio" name="paymenttype" id="payment_danda" class="inputRadio" value="delivery and acceptance of" /> Delivery & Acceptance</label>
      <label for="payment_pub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pub" class="inputRadio" value="publication of" /> Publication</label>
      <label for="payment_pbpub" class="labelRadio"><input type="radio" name="paymenttype" id="payment_pbpub" class="inputRadio" value="paperback publication of" /> Paperback Publication</label>

      <label for="payment_otherlabel" class="labelRadio"><input type="radio" name="paymenttype" id="payment_otherlabel" class="inputRadio" onclick="this.form.payment_other.focus()" onfocus="this.form.payment_other.focus()" value="" checked="checked"  /> Other:</label>
      <input type="text" name="payment_other" id="payment_other" class="inputText" value="" />
      <small>Remember, this text will be in the middle of a sentence. This text should always end in "of" or "for."</small>
    </fieldset>
  </div>

【问题讨论】:

    标签: javascript forms textbox radio-button


    【解决方案1】:

    您的第一个 for 循环通过并找到选择的正确无线电的值,但在“其他”的情况下,您不会分配值。您需要确定何时选择其他,然后将 radio_paymenttype_val 分配给文本框的值。大意是:

    for (var i=0; i < document.form2.paymenttype.length; i++)
    {
      if (document.form2.paymenttype[i].checked)
      {
        // assuming "other" is the only case where this radio's value property would be empty.
        var radio_paymenttype_val = (document.form2.paymenttype[i].value != ''
                                  ? document.form2.paymenttype[i].value
                                  : document.form2.payment_other.value);
      }
    

    }


    更新

    所以请原谅延迟(拿着你的表单域并用它运行)。这就是(我相信)你正在寻找的东西。需要注意的几点:

    • 我不进行任何表单验证。这是您可能想要修改的东西,并且可以非常简单。在.click() 事件中,只需检查以下内容(或者您可以更详细地了解):

      if($('#agentfirstname').val()==''){
      alert('缺少名字');
      返回;
      }

    • 另外,我使用了一些对 jQuery 来说相当新的东西,templates。这比var+='html html'+var+'html'; 更容易(您可以在 ID 为“FormTemplate”的&lt;script&gt; 标记中看到)。
    • 最后,我在 FF4、Chrome4 和 IE8 上对此进行了测试,它应该可以工作,但如果在您使用的任何环境下都不能正常工作,请告诉我。

    无论如何,这是代码,希望对您有所帮助!

    放在文档的 &lt;head&gt; 元素内

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <Script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
    <script type="text/javascript">
      $(function(){
        // bind to the "display" button ('.' means this is a class name reference)
        $('.inputSubmit').click(function(e){
          // build up the template values
          var tmplData = [{
            agentFirstName: $('#agentfirstname').val(),
            agentLastName: $('#agentlastname').val(),
    
            agencyName: $('#agencyname').val(),
            agentAddr1: $('#agentaddress1').val(),
            agentAddr2: $('#agentaddress2').val(),
            agentCity: $('#agentcity').val(),
            agentState: $('#agentstate').val(),
            agentZip: $('#agentzip').val(),
    
            paymentAmount: '$'+$('#paymentamount').val(),
            paymentType: $('input[name="paymenttype"]:checked').val() != '' ? $('input[name="paymenttype"]:checked').val() : $('#payment_other').val(),
    
            authorFirstName: $('#authorfirstname').val(),
            authorLastName: $('#authorlastname').val(),
            bookTitle: $('#booktitle').val(),
            contracts: $('input[name="contracts"]:checked').val()
          }];
    
          // create the template
          var template = $('#FormTemplate').template('letter');
    
          // Create a fake div we can push the template to and pass off to popup
          var tmplDiv = document.createElement('div');
          $(tmplDiv).attr('id','TemplateDiv').css('display','none');
    
          // Write the template and push it off
          $.tmpl('letter', tmplData).appendTo(tmplDiv);
    
          // create the window and populate it with the template
          var hWindow = window.open('','NewWin', 'toolbar=no,status=no,scrollbars=yes,width=800,height=600');
          hWindow.document.write(tmplDiv.innerHTML);
    
          // stop any further action
          e.preventDefault();
        });
      });
    </script>
    

    放置在文档的 &lt;body&gt; 元素内:

    <script id="FormTemplate" type="text/x-jquery-tmpl">
      <html>
        <head>
          <title>Letter</title>
        </head>
        <body>
          <h2>Royalty Advance Payment Letter</h2>
          <hr />
          <span type="font-family:Garamond;">
            <p>
              ${agentFirstName} ${agentLastName}<br />
              ${agencyName}<br />
              ${agentAddr1}<br />
              ${agentAddr2}<br />
              ${agentCity}, ${agentState} ${agentZip}<br />
            </p>
            <p>
              Dear ${agentFirstName},
            </p>
            <p>
              Please find enclosed a check in the amount of ${paymentAmount} representing the amount due upon ${paymentType}
              ${authorFirstName} ${authorLastName}'s <em>${bookTitle}</em>.
              ${contracts}
            </p>
            <p>
              Regards,<br />
              <br />
              <br />
              <br />
              Margaret Maloney<br />
              Associate Editor
            </p>
          </span>
        </body>
      </html>
    </script>
    

    【讨论】:

    • 这似乎对我不起作用。我看到了我现在缺少的东西(正确地将值分配给变量),但恐怕我对 javascript 的了解太少了,这让我看不出为什么该代码不起作用。
    • 你反对使用像jQuery这样的库吗?恕我直言,它使处理这样的事情变得更加容易,并且是跨浏览器兼容的。
    • 完全不反对,只是没用过。如果我使用 jQuery,在这种特定情况下我需要做什么? (我查看了该网站,并了解它的一般运作方式。)
    • @ocherdraco:现在制作一个模型,在我编写代码时让我裸露。 ;-)
    • 我再次尝试了 Arachnid 的方法,它奏效了。不过,我仍然对您如何使用 jQuery 进行操作很感兴趣,因此,如果您已经完成了,请不要犹豫,提出这个模型。
    【解决方案2】:

    您可以简单地为 payment_other 设置一个 onblur() 来设置单选选项的值吗?

    <input type="text" name="payment_other" id="payment_other" class="inputText" value="" onblur="document.getElementById('payment_otherlabel').value=this.value;" />
    

    如果它被设置,它会自动将值复制到单选选项中。然后当你的 Display() 函数被调用时,我会认为值会被设置。

    (意识到我错过了 onblur="" 语句末尾的分号。)
    你试过了吗?

    【讨论】:

    • 哦,以前没用,现在可以了!谢谢蜘蛛。
    • 很抱歉我之前没有对此发表评论——我不明白你的代码在做什么,所以我尝试了 Brad Christie's,因为我对它的变化有了更好的理解。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-04
    • 2020-05-12
    • 1970-01-01
    相关资源
    最近更新 更多