选中单选框时将属性添加到输入字段

Add attribute to input field when radio box is selected

本文关键字:添加 输入 字段 属性 单选框      更新时间:2023-09-26

当选择单选按钮时,我需要为输入框设置onkeyup属性。所以这是我的输入字段:

<input type="text" name="searchval" value="<?php echo $search; ?>"  >

单选按钮:

<form action="">
<input type="radio" name="merchant" value="merchant"> Merchant<br>
<input type="radio" name="brand" value="brand"> Merchant<br>
</form>

例如,当选择"商家"单选时,我希望输入字段将onkeyup="searchmerchant()"添加到输入框中,因此它应如下所示:

<input type="text" name="searchval" value="<?php echo $search; ?>" onkeyup="searchmerchant()" >

我该怎么做这个JavaScript?


编辑:使用Jayesh Chitroda答案中的代码,我创建了一个小提琴:JS小提琴

试试这个:

Jquery:

 $('input[name="searchval"]').keyup(function(){
        console.log($('input[name=selection]:checked').val())
        var val = $('input[name=selection]:checked').val();
        if(val == 'merchant') { // check if selected radio is 'merchant' set onkeyup attribute
            $(this).attr("onkeyup","searchmerchant()")
        } else {
            $(this).removeAttr("onkeyup"); // Remove if not merchant selected
        }
  });

目录:

为单选按钮和更新单选按钮的值分配相同的名称。

<form action="">
  <input type="radio" name="selection" value="merchant"> Merchant<br>
  <input type="radio" name="selection" value="brand"> Brand<br>
</form>