简体   繁体   English

在 javascript 中将输入设置为只读

[英]set input as readonly in javascript

I am currently trying to create a JS method which sets a specific input field as readonly if another field contains a value inside it but i am having issues with getting it to work.我目前正在尝试创建一个 JS 方法,如果另一个字段在其中包含一个值,则该方法将特定的输入字段设置为只读,但我在让它工作时遇到问题。

   $(document).ready(function(){
    const priceInputs = $('.price input');
    priceInputs.change(function(){
        if($(this).val() === ''){
            $(this).parents('.price').find('input').attr('readonly', false);
            $(this).attr('readonly', false);
        }else{
            $(this).parents('.price').find('input').attr('readonly', true);
        }
    });
});

but when i load a record which contains a value inside it the other field isn't automatically set to readonly但是当我加载其中包含一个值的记录时,另一个字段不会自动设置为只读

anyone got any ideas?有人有什么想法吗?

Use each loop for class elements.将每个循环用于 class 元素。

 $('.price').each(function() { $(this).change(function() { console.log(this.value) if (this.value === '') { $('input[type="text"], textarea').attr('readonly', false); } else { $('input[type="text"], textarea').attr('readonly', 'readonly'); this.readOnly = false; } }); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" name="input1" class="price" /> <input type="text" name="input2" class="price" />

For changing the readonly property you should use prop() like below:要更改只读属性,您应该使用 prop(),如下所示:

$("#name").prop('readonly', false);

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

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