【问题标题】:Insert an attribute to input field when user selects a radio用户选择单选时向输入字段插入属性
【发布时间】:2012-09-24 00:54:05
【问题描述】:

我需要一个可以在字段中插入属性并在用户取消选择字段时将其删除的 JavaScript。

这是我用于无线电选择的代码:

<script>
$(document).ready(function() {
    $("input[name$='sel']").click(function() {
        var test = $(this).val();

        $("div.desc").hide();
        $("#sel" + test).show();
    });

    if (test == "CreditCard") {
        $("#card").addClass("validate[custom[card]] text-input");
    } else {
        $("#card).removeClass("validate[custom[card]] text-input");
    }
});
</script>

字段代码:

<table><tr><td>

<p>
Credit/Debit Card<lable  style="margin-right:1px;"></lable><input type="radio" name="sel" id="sel"  value="CreditCard" />
</p> 
<p>
Paypal<input type="radio" id="sel"  name="sel" value="Paypal"   />
</p>
<p>
Wire Transfer<input type="radio" id="sel"  name="sel" value="WireTransfer"  />
</p>
<!====================================================================================>
</td><td>
<!====================================================================================>
<div id="selCreditCard" class="desc">

<label for="card"><strong>Card Number<font color=red size=3> *</font></strong></label>
        <input name="card"   type="text"  id="card" value=""  style="width:85px;" />  
</div>
<!====================================================================================>
<div id="selPaypal" class="desc" style="display: none;margin-left:20px;margin-top:1px;margin-bottom:1px;">
    paypal
</div>
<!====================================================================================>
<div id="selWireTransfer" class="desc" style="display: none;margin-left:20px;margin-top:0px;margin-bottom:-5px;">

Transfer

</div>
<!====================================================================================>
</td></tr></table>
​

这是需要插入“卡片”输入字段的属性:

class="validate[custom[card]] text-input"

当用户选择值为CreditCard的收音机时,该属性将插入到输入字段中,当用户取消选择值为CreditCard的收音机时,该属性将被删除。

小提琴链接: FIDDLE

【问题讨论】:

  • 您似乎在使用 jQuery。你可以使用.addClass.removeClass

标签: javascript input attributes insert field


【解决方案1】:

telexper,你的代码中有很多错误的地方,很遗憾我现在没有时间解释。

但我会在这里为你留下一个工作代码:http://jsfiddle.net/RASG/DSrLS/

只需点击“信用卡/借记卡”,nowitsadded 类就会添加到输入字段中,该字段将变为红色。

HTML

<input type="radio" id="sel1" name="sel"> Credit/Debit Card

<br>

<input type="radio" id="sel2" name="sel"> Paypal

<br>

<input type="radio" id="sel3" name="sel"> Wire Transfer

<br>
<br>

<div id="selCreditCard" class="desc">
    Card Number <input name="card" type="text" id="card" value="">
</div>

JS

$('#sel1').click(function() { $('#card').addClass('nowitsadded') })

CSS

.nowitsadded {background-color: red}

【讨论】:

  • 如何将这个 class="validate[custom[card]] text-input" 添加到输入字段
  • 我刚刚向您展示了如何添加课程!将 nowitsadded 替换为您的班级名称。
猜你喜欢
  • 2016-09-14
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2016-10-01
  • 2021-09-10
  • 2015-03-24
相关资源
最近更新 更多