2013-03-25 5 views
1

Я хочу поставить условие для элемента jquery в одной части кода в функции. Идея заключается в том, что input.other [type = "checkbox"] не получает такую ​​же возможность, чтобы снять флажок, но получает возможность хорошо выполнять другие действия. вот FiddleПоложить условие для элемента jQuery, внутри функции изменения

HTML

<input type="checkbox" name="accs" icost="5000" class="arms" />Arm 1: $5000 
<br/> 
<input type="checkbox" name="accs" icost="6000" class="arms" />Arm 2: $6000 
<br/> 
<input type="checkbox" name="accs" icost="7000" class="neck" />Neck 1: $7000 
<br/> 
<input type="checkbox" name="accs" icost="8000" class="neck" />Neck 2: $8000 
<br/> 
<input type="checkbox" name="accs" icost="12000" class="other" />Other 1: $12000 
<br /> 
<input type="checkbox" name="accs" icost="8000" class="other" />Other 2: $20000 
<br /> 
<div id="total">$5000</div> 

Javascript код:

var items = $('input.arms[type="checkbox"], input.neck[type="checkbox"], input.other[type="checkbox"]'); 
// get the initial total and store in a data for use later (resets as needed) 
var total = $('#total'); 
total.data("currentvalue", parseFloat(total.text().replace(/[^0-9\,]+/g, ""))); 
items.change(function() { 
var currenttotal = total.data("currentvalue"); 
//exlude input.other[type="checkbox"] from here 
var myClass = $(this).attr('class'); 
var thisGroup = $('.' + myClass); 
var notme = $('.' + myClass + ':checked').not(this); 
var notmeCost = (notme.length ? notme.attr('icost') : ($(this).is(':checked') ? 0 : $(this).attr('icost'))); 

notme.prop('checked', false); 
//ends here 
//include input.other[type="checkbox"] from here 
currenttotal = currenttotal - notmeCost; 
total.fadeOut(300); 
thisGroup.filter(':checked').each(function (i) { 
    var cost = $(this).attr('icost'); 
    currenttotal = currenttotal + parseFloat(cost); 
}); 
total.data("currentvalue", currenttotal); 
total.text("$" + currenttotal.formatMoney(0, ',', '.')); // fix your format here as needed 
total.fadeIn(300); 
}); 
+0

Что вы хотите? я не понимаю. просьба уточнить. – Sangeeta

+0

Вы хотите, чтобы сумма проверенных товаров была результатом, не так ли? – Sharun

+0

Если вы можете открыть Fiddle, вы сможете увидеть, как он реагирует. В основном, вы можете просто выбрать один флажок из группы, а не два. Мне нужно, чтобы одна из этих групп имела возможность выбирать несколько флажков @Sangeeta –

ответ

1

Я хотел бы добавить класс «likeRadio» для тех, кого вы хотите рассматривать как набор переключателей, а затем управлять этим:

модифицирована Markup: (последний пункт измененное значение для сопоставления текста - вы можете это исправить, если он отличается)

<input type="checkbox" name="accs" icost="5000" class="arms likeRadio" />Arm 1: $5000 
<br/> 
<input type="checkbox" name="accs" icost="6000" class="arms likeRadio" />Arm 2: $6000 
<br/> 
<input type="checkbox" name="accs" icost="7000" class="neck likeRadio" />Neck 1: $7000 
<br/> 
<input type="checkbox" name="accs" icost="8000" class="neck likeRadio" />Neck 2: $8000 
<br/> 
<input type="checkbox" name="accs" icost="12000" class="other" />Other 1: $12000 
<br /> 
<input type="checkbox" name="accs" icost="20000" class="other" />Other 2: $20000 
<br /> 
<div id="total">$5000</div> 

КОД: это не имеет строгую зависимость в том, что если у вас есть несколько классов, то первые из них является один вы " группировка "для радио, как функция кнопки. (см. функцию разделения)

Number.prototype.formatMoney = function (c, d, t) { 
    c = isNaN(c = Math.abs(c)) ? 2 : c; 
    d = d === undefined ? "." : d; 
    t = t === undefined ? "," : t; 
    var n = this, 
     s = n < 0 ? "-" : "", 
     i = parseInt(n = Math.abs(+n || 0).toFixed(c), 10) + "", 
     j = (j = i.length) > 3 ? j % 3 : 0; 
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); 
}; 
// get the initial total and store in a data for use later (resets as needed) 
var total = $('#total'); 
var originalValue = parseFloat(total.text().replace(/[^0-9\,]+/g, "")); 
total.data("currentvalue", originalValue); 
total.data("originalvalue", originalValue); 

var items = $('input.arms[type="checkbox"], input.neck[type="checkbox"], input.other[type="checkbox"]'); 
items.change(function() { 
    var currenttotal = total.data("originalvalue"); 
    var arrayOfClasses = $(this).attr('class').split(' '); 
    var myClass = arrayOfClasses[0]; 
    var thisGroup = $('.' + myClass); 
    if ($(this).hasClass('likeRadio')) { 
     var notme = $('.' + myClass + ':checked').not(this); 
     var notmeCost = (notme.length ? notme.attr('icost') : ($(this).is(':checked') ? 0 : $(this).attr('icost'))); 
     notme.prop('checked', false); 
     currenttotal = total.data("currentvalue"); 
     currenttotal = currenttotal - notmeCost; 
    } else { 
     thisGroup = items; 
    } 
    total.fadeOut(300); 
    thisGroup.filter(':checked').each(function (i) { 
     var cost = $(this).attr('icost'); 
     currenttotal = currenttotal + parseFloat(cost); 
    }); 
    total.data("currentvalue", currenttotal); 
    total.text("$" + currenttotal.formatMoney(0, ',', '.')); // fix your format here as needed 
    total.fadeIn(300); 
}); 
1

Я внес изменения в jsfiddle:

Number.prototype.formatMoney = function(c, d, t){ 
     var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0; 
      return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ""); 
     }; 

     var items = $('input.arms[type="checkbox"], input.neck[type="checkbox"], input.other[type="checkbox"]'); 
     // get the initial total and store in a data for use later (resets as needed) 
     var total = $('#total'); 
     total.data("currentvalue", parseFloat(total.text().replace(/[^0-9\,]+/g, ""))); 
     items.change(function() { 
      var currenttotal = total.data("currentvalue"); 
      var myClass = $(this).attr('class'); 
      if(myClass=='other') 
      { 
        var notmeCost=$(this).attr('icost'); 

        if($(this).is(':checked')==false) 
         notmeCost=0-parseFloat(notmeCost); 
       currenttotal = currenttotal + parseFloat(notmeCost); 

     total.fadeOut(300); 
      } 
      else 
      { 
      var thisGroup = $('.' + myClass); 
      var notme = $('.' + myClass + ':checked').not(this); 
      var notmeCost = (notme.length ? notme.attr('icost') : ($(this).is(':checked') ? 0 : $(this).attr('icost'))); 

      notme.prop('checked', false); 


      currenttotal = currenttotal - notmeCost; 
      total.fadeOut(300); 
      thisGroup.filter(':checked').each(function (i) { 
       var cost = $(this).attr('icost'); 
       currenttotal = currenttotal + parseFloat(cost); 
      }); 
      } 

      total.data("currentvalue", currenttotal); 
      total.text("$" + currenttotal.formatMoney(0, ',', '.')); // fix your format here as needed 

     }); 

И здесь, я думаю, что вы сделали неправильно запись:

<input type="checkbox" name="accs" icost="8000" class="other" />Other 2: $20000;// icost is incorrect 

изменить его

<input type="checkbox" name="accs" icost="20000" class="other" />Other 2: $20000; 
Смежные вопросы