简体   繁体   English

如何使用jQuery onchange事件在HTML中添加和删除属性?

[英]How to add and remove attribute in HTML using jquery onchange event?

Hello guys I just want to ask how can i create a jquery that can detect the user input and assign an attribute or remove an attribute based on the user input. 大家好,我只想问一下如何创建一个可以检测用户输入并根据用户输入分配属性或删除属性的jQuery。 My scenario is I have a table with 4 columns. 我的情况是我有一个包含4列的表。 First is a dropdown. 首先是一个下拉菜单。 And the rest are textboxes which are readonly. 其余的是只读的文本框。 The default option for dropdown is NULL or empty. 下拉菜单的默认选项为NULL或为空。 If the user choose from the dropdown, the 2 texboxes should not be readonly. 如果用户从下拉菜单中选择,则2个texbox不应为只读。 On that process I don't have an error but if the user set back again to NULL. 在该过程中,我没有错误,但是如果用户再次将其设置为NULL。 The 2 textboxes won't go back to readonly again. 2个文本框不会再次回到只读状态。 I don't know where's my error. 我不知道我的错误在哪里。

Here's my jquery code: 这是我的jQuery代码:

$("[id^=code]").on('change',function(){
    var index = this.id.match(/\d+/)[0];
    var validate = $('#code'+index).val();

    if(validate != ''){
        $("#qty"+index).removeAttr('readonly');
        $("#price"+index).removeAttr('readonly');
    }        
});

$("[id^=code]").on('change',function(){
    var index = this.id.match(/\d+/)[0];
    var validate = $('#code'+index).val();

    if(validate == ''){
        $("#qty"+index).attr('readonly');
        $("#price"+index).attr('readonly');
    }        
});

And this is my table 这是我的桌子

for($i = 1; $i < 16; $i++){
    echo "<!-- ITEM {$i} -->";
    echo "<tr>";
    echo "<td>";
    echo "<select name='code[]' id='code{$i}' style='width:100'>";
    echo "<option value=''><label>--CHOOSE ITEMS--</label></option>";
    foreach($resultGetCode->result_array() as $list){
        echo "<option value='".$list['itemid']."'>".$list['itemcode']." --- ".$list['itemname']."</option>";  
    }
    echo "</select>";
    echo "</td>";
    //echo "<td><input type='text' name='item[]' class='k-textbox' id='item{$i}' value='' /></td>";
    echo "<td><input type='text' name='qty[]' id='qty{$i}' style='text-align: center' readonly='readonly' /></td>";
    echo "<td><input type='text' name='price[]' id='price{$i}' style='text-align: right;' onblur='' readonly='readonly' /></td>";
    echo "<td><input type='text' name='total[]' id='total{$i}' style='font-family: courier; text-align: right; background-color: lightgray; color: red' readonly='readonly' value='' /></td>";
    echo "<tr>";
}

Here's the fiddle: http://jsfiddle.net/rochellecanale/jnkc3/5/ 这是小提琴: http : //jsfiddle.net/rochellecanale/jnkc3/5/

Would be easier to help you if you create a fiddle, but try this 如果您制作小提琴会更容易为您提供帮助,但是请尝试这样做

if(validate == ''){
     $("#qty"+index).prop('readonly', true);
     $("#price"+index).prop('readonly', true);
 }

Update . 更新 FIDDLE 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM