使用复选框来控制 Input.value (有一个恼人的扭曲.) [英] Using Checkboxes to contol an Input.value (With an annoying twist.)

查看:35
本文介绍了使用复选框来控制 Input.value (有一个恼人的扭曲.)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天来,我一直在研究使用复选框控制 UI 的方法,并在 Stack 上的一些成员的帮助下,我已经走了很远.但我的秃顶还没有完全停止.我一直试图通过在我的 UI 控制器旁边包含一个数值来进一步调整我的代码片段.(此值稍后将在 web-java 小程序中使用.)

<块引用>例如,当检查复选框时<代码> var total 从 0 30 .如果复选框未选中,则值返回0".

(主构建 JS 小提琴)(复选框示例).

第二个小提琴允许使用数据属性,但是这些需要通过JS注入到HTML中.和以前一样,我对 CSS 或 HTML 源文件具有NO"访问权限.

<块引用>

(原帖)- 由于问题的性质发生了变化,并且评论变得相当混乱,我被要求打开一个新线程.

下面我将发布两个片段,一个是原始版本,在用户 @acontell 的帮助下构建.另一个是我所追求的结果类型的示例,它是在用户 @Rajesh 的帮助下构建的.链接到(示例来源).

<小时>

基础构建

//控制 UI...(功能(domElements,cbState){//数字递增var 总计 = 0 + 'mm';document.getElementById('adjvar').value = total;函数 clickCallback() {切换元素(this.className);}功能切换元素(类名,initialShow){var checkNumber = ((/editoropt(\d*)/).exec(className))[1],checkBox = document.getElementById('checkboxopt' + checkNumber),Division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],isShown = initialShow === 未定义?window.getComputedStyle(division).display === 'none' : initialShow;Division.style.display = isShown ?'块':'无';checkBox.checked = isShown;//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//增加计数...瓦尔瓦尔= 30;总计 += (+val * (checkBox.checked ? 1 : -1));document.getElementById('adjvar').value = total + 'mm';document.getElementsByClassName('adjvar').value = checkBox.checked ?价值:0 +毫米";//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++}dom元素.filter(function(el) {返回 el.className.indexOf('editoropt') !== -1;}).forEach(function(el, index) {el.addEventListener('click', clickCallback, false);toggleElements(el.className, cbState[index]);});})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);//默认检查...如果 (document.getElementById('checkboxopt').checked) {//没做什么} 别的 {document.getElementById('checkboxopt').click();}//注入样式函数 ctSe() {var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",head = document.head ||document.getElementsByTagName('head')[0],style = document.createElement('style');style.type = 'text/css';如果(style.styleSheet){style.styleSheet.cssText = css;} 别的 {style.appendChild(document.createTextNode(css));}head.appendChild(style);控制台日志(头)控制台日志(样式)控制台日志(CSS)};ctSe();

.editoraccvar {宽度:300px;背景:#f0f;填充:.5em;}.editoropt {宽度:300px;背景:#0f0;填充:.5em;}.editoraccvar1 {宽度:300px;背景:#0ff;填充:0.5em;}.editoropt1 {宽度:300px;背景:#ff0;填充:.5em;}文本区域{显示:块;宽度:95%;调整大小:无;填充:.5em;}

<!-- 我试图隐藏 &显示整个部门... --><div class="seq-box-form-field field-summernote editoraccvar "><label for="accvar1">底层信息</label><div class="clearfix"></div><textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea><input type="hidden" name="accvar1" id="accvar1" value=""/>

<!-- 仅使用系统提供的内容.--><div class="seq-box-form-field editoropt"><label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span><input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true"/><input type="hidden" name="opt1" id="opt1" value="true"/>

<!-- 中学部--><div class="seq-box-form-field field-summernote editoraccvar1 "><label for="accvar1">一楼</label><div class="clearfix"></div><textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea><input type="hidden" name="accvar1" id="accvar1" value=""/>

<!-- 辅助复选框--><div class="seq-box-form-field editoropt1 "><label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span><input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true"/><input type="hidden" name="opt1" id="opt1" value="true"/>

<input name="adjvar" id="adjvar" readonly>

<小时>

例子

(function() {无功总计 = 0;函数计算(索引){var el = document.getElementsByClassName('checkbox-input')[index];var val = el.getAttribute("数据值");总计 += (+val * (el.checked ? 1 : -1));document.getElementById('pnvar').value = total;document.getElementsByClassName('pnvar')[index].value = el.checked ?价值:0;}函数 registerEvents() {var cbs = document.querySelectorAll('[type="checkbox"]');[].forEach.call(cbs, function(cb, i) {cb.addEventListener("点击", function() {计算(i);});});document.getElementById('pnvar').addEventListener('keydown', function(event) {如果(事件.keyCode == 13){event.preventDefault();返回假;}})}window.addEventListener('load', function() {注册事件();计算(0)})})()

.editoropt {字体系列:Calibri、无衬线字体;宽度:160px;背景:#f8f8ff;填充:0.5em;边框:实心 1px #ddd;}#checkboxopt {向左飘浮;右边距:1em;边距顶部:4px;}#checkboxopt1 {向左飘浮;右边距:1em;边距顶部:4px;}.pnvar {宽度:95%;}输入:-moz-只读{/* 对于火狐 */背景色:透明;边界:无;边框宽度:0px;}输入:只读{背景色:透明;边界:无;边框宽度:0px;}

<div class="seq-box-form-field editoropt"><label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">默认 80mm </span><input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" 选中/><input type="hidden" name="opt1" id="opt1" value="true"/>

<div class="seq-box-form-field editoropt"><label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">添加 30mm </span><input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true"/><input type="hidden" name="opt2" id="opt2" value="true"/>

<div class="editoropt"><input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text"><input name="adjvar" class="pnvar" id="adjvar" readonly value="0"><input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">

<小时>

正如我在上一篇文章中提到的,我不是 JS 高手,我只是找到了自己的脚,但是我乐于学习和进一步了解我的知识.任何帮助将不胜感激.

注意:为了与另一个应用程序保持一致,所有标签、类和名称必须保持不变.

解决方案

我可能错了,但我认为这两行代码:

//默认检查...如果 (document.getElementById('checkboxopt').checked) {//没做什么} 别的 {document.getElementById('checkboxopt').click();}

如果您将 [true, false] 作为复选框的初始状态传递,则可以避免:

([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);

我可能错了,您可能正在做其他事情,或者页面状态可能需要点击,我不知道.

回到问题,如果你想在复选框被选中/取消选中时增加/减少30,你可以这样做:

创建一个函数来检索输入的值,并用添加的数量更新它.输入的值是一个x mm"形式的字符串,因此需要稍加修改才能获得值的整数部分.

function updateInputValue(n) {var actual = +document.getElementById('adjvar').value.split('mm')[0] ||0;document.getElementById('adjvar').value = (actual + n) + 'mm';}

toggleElement 内部调用此函数以更新输入值.

var increment = isShown ?30 : -30;updateInputValue(initialShow === undefined ? increment : +initialShow * 30);

它变得有点复杂,因为您必须控制输入的初始状态,但这并不难:如果是初始状态,initialShow 与 undefined 不同,因此我们将值(它是布尔值)转换为数字乘以 30(选中时为 1 * 30,未选中时为 0 * 30).当它不是初始状态时,我们根据它是否被选中来增加/减少.

这里是 fiddle(我还注释掉了点击复选框的部分).希望有帮助.

I've been researching for a few days methods of controlling UI with checkboxes and with the help of some members on Stack' I've come really quite far. But my balding doesn't quite stop yet. I've been trying to further tweak my code snippet, by including a numeric value alongside my UI controller. (This value will be of use later inside the web-java applet.)

For example, when a checkbox is checked var total is ammended from 0 to 30. If a Checkbox is unchecked the value returns to '0'.

(Main Build JS Fiddle), (Checkbox Example).

The second fiddle allows the use of data attributes, however these will need to be injected into the HTML via, JS. As like before I have 'NO' access to the CSS or HTML source files.

(Original Post) - This post is a follow on from another question asked here on stack, due to the nature of the question changing, and the comments getting fairly confusing I was asked to open a new thread.

Below I'll post two snippets, one is of the original build, built with the aid of user @acontell. The other is an example of the type of result I am after, built with the aid of, user @Rajesh. Link to (Example Source).


The Base Build

// Control UI...
(function(domElements, cbState) {

  // Number increment
  var total = 0 + ' mm';
  document.getElementById('adjvar').value = total;

  function clickCallback() {
    toggleElements(this.className);
  }

  function toggleElements(className, initialShow) {
    var checkNumber = ((/ editoropt(\d*) /).exec(className))[1],
      checkBox = document.getElementById('checkboxopt' + checkNumber),
      division = document.querySelectorAll('.editoraccvar' + checkNumber)[0],
      isShown = initialShow === undefined ? window.getComputedStyle(division).display === 'none' : initialShow;

    division.style.display = isShown ? 'block' : 'none';
    checkBox.checked = isShown;


    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    // increment count...
    var val = 30;
    total += (+val * (checkBox.checked ? 1 : -1));
    document.getElementById('adjvar').value = total + ' mm';
    document.getElementsByClassName('adjvar').value = checkBox.checked ? val : 0 + ' mm';
    // ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++


  }

  domElements
    .filter(function(el) {
      return el.className.indexOf('editoropt') !== -1;
    })
    .forEach(function(el, index) {
      el.addEventListener('click', clickCallback, false);
      toggleElements(el.className, cbState[index]);
    });

})([].slice.call(document.querySelectorAll('.seq-box-form-field')), [false, false]);

// Default Checked...

if (document.getElementById('checkboxopt').checked) {
  // do nothing
} else {
  document.getElementById('checkboxopt').click();
}

// inject style
function ctSe() {
  var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

  style.type = 'text/css';
  if (style.styleSheet) {
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }

  head.appendChild(style);
  console.log(head)
  console.log(style)
  console.log(css)
};

ctSe();

.editoraccvar {
  width: 300px;
  background: #f0f;
  padding: .5em;
}
.editoropt {
  width: 300px;
  background: #0f0;
  padding: .5em;
}
.editoraccvar1 {
  width: 300px;
  background: #0ff;
  padding: .5em;
}
.editoropt1 {
  width: 300px;
  background: #ff0;
  padding: .5em;
}
textarea {
  display: block;
  width: 95%;
  resize: none;
  padding: .5em;
}

<!-- I'm trying to hide & show this entire division... -->
<div class="seq-box-form-field  field-summernote editoraccvar  ">
  <label for="accvar1">Ground Floor Info</label>
  <div class="clearfix"></div>
  <textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
  <input type="hidden" name="accvar1" id="accvar1" value="" />
</div>

<!-- Using only what the system has supplied. -->
<div class="seq-box-form-field  editoropt  ">
  <label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
    <input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
    <input type="hidden" name="opt1" id="opt1" value="true" />
  </label>
</div>

<!-- Secondary Division -->
<div class="seq-box-form-field  field-summernote editoraccvar1  ">
  <label for="accvar1">First Floor</label>
  <div class="clearfix"></div>
  <textarea id="richaccvar1" name="richaccvar1" class="summernote"></textarea>
  <input type="hidden" name="accvar1" id="accvar1" value="" />
</div>

<!-- Secondary Checkbox -->
<div class="seq-box-form-field  editoropt1  ">
  <label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
    <input type="checkbox" name="checkboxopt1" id="checkboxopt1" value="true" checked="true" />
    <input type="hidden" name="opt1" id="opt1" value="true" />
  </label>
</div>
<input name="adjvar" id="adjvar" readonly>


The Example

(function() {
  var total = 0;

  function calculate(index) {
    var el = document.getElementsByClassName('checkbox-input')[index];
    var val = el.getAttribute("data-value");
    total += (+val * (el.checked ? 1 : -1));
    document.getElementById('pnvar').value = total;
    document.getElementsByClassName('pnvar')[index].value = el.checked ? val : 0;
  }

  function registerEvents() {
    var cbs = document.querySelectorAll('[type="checkbox"]');
    [].forEach.call(cbs, function(cb, i) {
      cb.addEventListener("click", function() {
        calculate(i);
      });
    });

    document.getElementById('pnvar').addEventListener('keydown', function(event) {
      if (event.keyCode == 13) {
        event.preventDefault();
        return false;
      }
    })
  }

  window.addEventListener('load', function() {
    registerEvents();
    calculate(0)
  })
})()

.editoropt {
  font-family: Calibri, sans-serif;
  width: 160px;
  background: #f8f8ff;
  padding: .5em;
  border: solid 1px #ddd;
}
#checkboxopt {
  float: left;
  margin-right: 1em;
  margin-top: 4px;
}
#checkboxopt1 {
  float: left;
  margin-right: 1em;
  margin-top: 4px;
}
.pnvar {
  width: 95%;
}
input:-moz-read-only {
  /* For Firefox */
  background-color: transparent;
  border: none;
  border-width: 0px;
}
input:read-only {
  background-color: transparent;
  border: none;
  border-width: 0px;
}

<div class="seq-box-form-field  editoropt  ">
  <label for="opt1">
    <span style="padding-right: 10px; vertical-align: 1px;">Default 80mm </span>
    <input type="checkbox" class="checkbox-input" data-value="80" name="checkboxopt" id="checkboxopt" value="true" checked />
    <input type="hidden" name="opt1" id="opt1" value="true" />
  </label>
</div>
<div class="seq-box-form-field  editoropt  ">
  <label for="opt1">
    <span style="padding-right: 10px; vertical-align: 1px;">Add 30mm </span>
    <input type="checkbox" class="checkbox-input" name="checkboxopt1" data-value="30" id="checkboxopt1" value="true" />
    <input type="hidden" name="opt2" id="opt2" value="true" />
  </label>
</div>
<div class="editoropt">
  <input id="pnvar" name="pnvar" placeholder="Null" onkeydown="" value="" class="required" type="text">
  <input name="adjvar" class="pnvar" id="adjvar" readonly value="0">
  <input name="adjvar" class="pnvar" id="adjvar2" readonly value="0">
</div>


As I mentioned in my previous post, I'm not a JS Whizz and I'm just finding my feet, however I am abitious to learn and further my knowledge. Any assistance would be greatly appreciated.

Note : All tags, classes and names, must remain the same for consistancy with another application.

解决方案

I might be mistaken but I think that this two lines of code:

// Default Checked...

if (document.getElementById('checkboxopt').checked) {
    // do nothing
} else {
    document.getElementById('checkboxopt').click();
}

Could be avoided if you passed [true, false] as the initial states of the checkboxes:

([].slice.call(document.querySelectorAll('.seq-box-form-field')), [true, false]);

I might be wrong, you might be doing something else or the state of the page could require that click, I don't know.

Going back to the issue, if you want to increase/decrease by 30 when the checkbox is checked/unchecked, you could do as follows:

Create a function that retrieves the value of the input an updates it with a quantity added to it. The value of the input is a string of the form 'x mm' so a bit of tinkering is necessary to get the integer part of the value.

function updateInputValue(n) {
    var actual = +document.getElementById('adjvar').value.split(' mm')[0] || 0;
    document.getElementById('adjvar').value = (actual + n) + ' mm';
}

Inside toggleElement call this function in order to update the input value.

var increment = isShown ? 30 : -30;
updateInputValue(initialShow === undefined ? increment : +initialShow * 30);

It gets a bit complicated because you have to control the initial state of the inputs, but it's not that hard: if it's the initial state, initialShow is different from undefined so we transform the value (it's a boolean) into a number a multiply it by 30 (when it's checked, it'd be 1 * 30, when it's unchecked it'd be 0 * 30). When it's not the initial state, we increment/decrement depending on whether it's checked or not.

And here's the fiddle (I also commented out the part that clicked the checkbox). Hope it helps.

这篇关于使用复选框来控制 Input.value (有一个恼人的扭曲.)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆