[英]How do i grab HTML Checkbox Form Values and check if the Value of the ID is the same as the User_id to auto increment Votes
[英]Toggle a attribute with id 'user'+i with a checkbox with id 'checkbox'+i
首先感謝您的幫助。 我是jquery和javascript的新手,我不會說英語,所以我在研究中沒有發現什么。
這是我的HTML
<li></li>
<li></li>
<li id="user1"></li>
<input type="checkbox" id="checkbox1">
<li></li>
<li></li>
<li id="user2"></li>
<input type="checkbox" id="checkbox2">
我希望每次都選中一個帶有id(“checkbox”+ i)的復選框我在(“user”+ i)中切換一個類來推入一個列表然后用post請求發送。
我試過這個
for(i = 1; i < 3; i++) {
document.getElementById('checkbox' + i).addEventListener('change', function() {
document.getElementById('user' + i).setAttribute("class", "passInterestIds");
});
}
但它只給我user3獨立的復選框
我該怎么做才能做到這一點?
所以只要id包含一位數就會導致我們從匹配函數中獲取的內容,這將始終有效。 然后,如果復選框被選中,則添加類hello
else刪除類hello
var elements = $('input[type^=checkbox'); elements.on('click', function(){ var idNr = $(this).attr('id').match(/\\d+/)[0]; if($(this).is(':checked')) { $('#user' + idNr).addClass('hello'); } else { $('#user' + idNr).removeClass('hello'); } });
.hello { background-color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li id="user1"></li> <input type="checkbox" id="checkbox1"> <li id="user2"></li> <input type="checkbox" id="checkbox2">
如果可能的話,更改HTML ..更好的方法是使用包含數字的input元素的value屬性。 如果您不能使用value屬性,請使用data-user-id
屬性。
var elements = $('input[type^=checkbox'); elements.on('click', function(){ var idNr = $(this).val(); if($(this).is(':checked')) { $('#user' + idNr).addClass('hello'); } else { $('#user' + idNr).removeClass('hello'); } });
.hello { background-color: orange; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <li id="user1"></li> <input type="checkbox" id="checkbox1" value="1"> <li id="user2"></li> <input type="checkbox" id="checkbox2" value="2">
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.