如何使用jquery切换所有子元素的readonly属性

时间:2017-03-03 13:58:10

标签: javascript jquery html

描述

所以我有一个带有一个按钮的表单,当我点击它时,我想切换一个字段集的所有子元素的readonly属性。

HTML:

<form>
    <fieldset id="F1">
        <textarea id="T1" rows="5" cols="50" readonly required></textarea><br>
        <textarea id="T2" rows="5" cols="50" readonly required></textarea><br>
        <textarea id="T3" rows="5" cols="50" readonly required></textarea><br>
    </fieldset>
    <button type="button" id="button" onclick="togglerequire('#F1')">
        Click Me
        </button>
</form>

jquery:

function togglerequire(id){
    $(id).children().each(function(){
        var re = $(this).prop('required');
        $(this).prop('required', !re);
    });
}

回到问题:

我可以通过id为单个元素工作,但是一旦我尝试对父ID定义的子元素执行切换,它就会停止工作,我无法弄清楚原因。

5 个答案:

答案 0 :(得分:2)

您需要将该功能更新为以下

function togglerequire(id){
    $(id).children("textarea").each(function(){
        var re = $(this).prop('readonly'); 
        $(this).prop('readonly', !re);
    });
}

请注意你正在切换错误的财产。另外,我们可以提供特定的选择器,例如textarea或类等。

答案 1 :(得分:1)

当您使用jquery时,您可以找到一个元素并让其所有孩子都拥有readonly,然后像下面的代码段一样调用.toggle: -

&#13;
&#13;
$('#button').click(function(){
   $('#F1').children('[readonly]').toggle();
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="F1">
    <textarea id="T1" rows="5" cols="50" readonly required></textarea><br>
    <textarea id="T2" rows="5" cols="50" readonly required></textarea><br>
    <textarea id="T3" rows="5" cols="50" readonly required></textarea><br>
</fieldset>
<button type="button" id="button">Click Me</button>
&#13;
&#13;
&#13;

同样的情况是必需的,或者只读和需要的情况如下:

$('#F1').children('[required]').toggle();// Correct
$('#F1').children('[readonly]').toggle();// Correct
$('#F1').children('[readonly][required]').toggle();// Correct

$('#F1').children('readonly').toggle();// incorrect

注意:如果您尝试在[] readonly $('#F1').children('readonly').toggle();之后没有[]的情况下使用Childerns,则不会切换。您需要将readonly放在requiredreadonly或两者之间。

更新1

正如你想要的那样required。以下是使readonly click event所有子元素具有$('#button').click(function(){ $('#F1').children('[required]').prop('readonly', true); });属性,<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset id="F1"> <textarea id="T1" rows="5" cols="50" required></textarea><br> <textarea id="T2" rows="5" cols="50" required></textarea><br> <textarea id="T3" rows="5" cols="50" required></textarea><br> </fieldset> <button type="button" id="button">Click Me</button>的代码段。

&#13;
&#13;
namespace PartyInvitesInProASPNETMVC5.Models
{
    public class MyAsyncMethods
    {
        public static Task<long?> GetPageLength()
        {
            HttpClient client = new HttpClient();
            var httpTask = client.GetAsync("http://www.google.com");
            return httpTask.ContinueWith((Task<HttpResponseMessage> antecedent) => {
                return antecedent.Result.Content.Headers.ContentLength;
            });
        }
    }
}
&#13;
public ActionResult GooglePageLength()
{
    var content = MyAsyncMethods.GetPageLength();
    return View(content);
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

虽然您已经接受了答案,但我建议如果目的是阻止用户与<textarea> / {{1}中的:disabled元素互动} state,然后更容易避免迭代这些子项,而是将readonly属性分配给父disabled

<fieldset>

&#13;
&#13;
// named function to call:
function toggleActiveStatus() {

  // I'm using native DOM approaches here simply because
  // they're 'cheaper' (premature optimisation, however)
  // than invoking jQuery unnecessarily.

  // here we use let statement to assign the element found
  // by 'document.querySelector()' (which returns the first
  // element matching the supplied CSS selector, or null if
  // there is no matching element) to the 'parent' variable:
  let parent = document.querySelector(

    // here we retrieve the CSS selector held in the
    // <button> element's 'data-affects' custom
    // (and valid) data-* attribute:
    this.dataset.affects
  ),

    // here we find the current state of the
    // element, returned as a Boolean true
    // if the <fieldset> is disabled or
    // false if the <fieldset> is not
    // disabled:
    currentState = parent.disabled;

  // here we simply set the disabled property
  // of the <fieldset> to the inverse of its
  // current state:
  parent.disabled = !currentState;

}

// binding the named function (note the deliberate
// lack of parentheses) using jQuery, rather than
// in-line event-handlers, to avoid the use of
// difficult-to-maintain JavaScript, and switching
// to the 'unobtrusive' JavaScript approach:
$('#button').on('click', toggleActiveStatus);
&#13;
function toggleActiveStatus() {
  let parent = document.querySelector(this.dataset.affects),
    currentState = parent.disabled;

  parent.disabled = !currentState;

}

$('#button').on('click', toggleActiveStatus);
&#13;
body {
  margin-bottom: 5em;
}

textarea {
  display: block;
}

button {
  text-transform: sentence;
}

#F1:disabled+button::before {
  content: "enable";
}

#F1:not(:disabled)+button::before {
  content: "disable";
}

#F1+button::after {
  content: ' textarea elements';
}
&#13;
&#13;
&#13;

此外,由于jQuery对于此方法没有必要,因此以下显示了使用本机DOM API的纯JavaScript方法:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <fieldset id="F1">
    <textarea id="T1" rows="5" cols="50" readonly required></textarea>
    <textarea id="T2" rows="5" cols="50" readonly required></textarea>
    <textarea id="T3" rows="5" cols="50" readonly required></textarea>
  </fieldset>
  <button type="button" id="button" data-affects="#F1"></button>
</form>

&#13;
&#13;
function toggleActiveStatus() {
  let parent = document.querySelector(this.dataset.affects),
    currentState = parent.disabled;

  parent.disabled = !currentState;

}

// here we use document.querySelector(), as above, to find
// the first element matching the supplied CSS selector:
document.querySelector('#button')

  // and then use EventTarget.addEventListener() to bind
  // the named function (again: note the deliberate lack
  // of parentheses) as the event-handler for the 'click'
  // event:
  .addEventListener('click', toggleActiveStatus);
&#13;
function toggleActiveStatus() {
  let parent = document.querySelector(this.dataset.affects),
    currentState = parent.disabled;

  parent.disabled = !currentState;

}

document.querySelector('#button').addEventListener('click', toggleActiveStatus);
&#13;
body {
  margin-bottom: 5em;
}

textarea {
  display: block;
}

button {
  text-transform: sentence;
}

#F1:disabled+button::before {
  content: "enable";
}

#F1:not(:disabled)+button::before {
  content: "disable";
}

#F1+button::after {
  content: ' textarea elements';
}
&#13;
&#13;
&#13;

参考文献:

答案 3 :(得分:0)

试试这个:

&#13;
&#13;
function toggleAttributesOn(selector, elementSelector, attribute) {
   var container = document.querySelector(selector);
   if(!!container && !!attribute) {
     var elements = [].slice.call(container.querySelectorAll(elementSelector));
     elements.forEach(function(element) {
       if(['readonly', 'required'].indexOf(attribute) > -1) {
         element.getAttribute(attribute) !== null? element.removeAttribute(attribute): element.setAttribute(attribute, true); 
       }
       else {
         element.setAttribute(attribute, !element.getAttribute(attribute));
       }
     });
   }
}



// demo code
function togglerequire(selector) {
   toggleAttributesOn(selector, 'textarea', 'readonly');
}
&#13;
<form>
    <fieldset id="F1">
        <textarea id="T1" rows="5" cols="50" readonly required></textarea><br>
        <textarea id="T2" rows="5" cols="50" readonly required></textarea><br>
        <textarea id="T3" rows="5" cols="50" readonly required></textarea><br>
    </fieldset>
    <button type="button" id="button" onclick="togglerequire('#F1')">
        Click Me
        </button>
</form>
&#13;
&#13;
&#13;

答案 4 :(得分:0)

这应该可以解决问题。 抓取此div中的所有输入并将其标记为禁用。

$(“#divID:input”)。attr(“ disabled”,true);