Answer the question
In order to leave comments, you need to log in
How to optimize jquery code?
hello everyone i have html code
<ul class="list-group services_check">
<form method="POST">
<li class="list-group-item">
<input id="text2" type="hidden" name="id_service[2]" value="0">
<button id="but2" class="btn btn-default" type="button">
<i class="icon-list-add"></i>
</button>
Услуга 1
</li>
<li class="list-group-item">
<input id="text3" type="hidden" name="id_service[3]" value="0">
<button id="but3" class="btn btn-default" type="button">
<i class="icon-list-add"></i>
</button>
Услуга 2
</li>
<li class="list-group-item"> -//- -// -//</li>
<li class="list-group-item"> -//- -// -//</li>
и тд вплоть до 15 штук
</form>
</ul>
$(document).ready(function() {
$('.services_check button').click(function(){
var my = $(this).find('i');
if(my.hasClass('icon-check')){
my.removeClass('icon-check').addClass('icon-list-add');
$("#but2").click(function(){$("#text2").val("1");});
$("#but3").click(function(){$("#text3").val("1");});
$("#but4").click(function(){$("#text4").val("1");});
}
else{
my.addClass('icon-check').removeClass('icon-list-add');
$("#but2").click(function(){$("#text2").val("0");});
$("#but3").click(function(){$("#text3").val("0");});
$("#but4").click(function(){$("#text4").val("0");});
}
$(this).toggleClass('btn-primary').toggleClass('btn-default');
$(this).blur();
});
});
Answer the question
In order to leave comments, you need to log in
$(document).ready(function() {
$('.services_check button').click(function(){
var my = $(this).find('i');
if(my.hasClass('icon-check')){
my.removeClass('icon-check').addClass('icon-list-add');
$(this).prev().val("1");
}
else{
my.addClass('icon-check').removeClass('icon-list-add');
$(this).prev().val("0");
}
$(this).toggleClass('btn-primary').toggleClass('btn-default');
$(this).blur();
});
});
Well, you can return an object when clicking ,
and look for the necessary "children" whose val needs to be changed.
$(document).ready(function() {
$('.services_check button').click(function(){
var my = $(this).find('i');
if(my.hasClass('icon-check')){
my.removeClass('icon-check').addClass('icon-list-add');
$('.services_check .list-group-item input').val("1");
}
else{
my.addClass('icon-check').removeClass('icon-list-add');
$('.services_check .list-group-item input').val("0");
}
$(this).toggleClass('btn-primary').toggleClass('btn-default');
$(this).blur();
});
});
...
if(my.hasClass('icon-check')){
my.removeClass('icon-check').addClass('icon-list-add');
$(this).closest('.list-group-item').find('input').val("1");
}
...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question