2017-04-17 1 views
-1

하나의 필드에 입력 된 버튼으로 6 개의 값을 합산해야합니다.JS의 변수 안에 얼마나 많은 값이 있는지 확인할 수 있습니까?

변수 안에 얼마나 많은 값이 들어 있는지 확인하는 방법을 알아야합니다. 단, 6 개의 항목에 도달하면 버튼을 비활성화하고 해당 값을 합쳐서 단락에 표시 할 수 있습니다. 내가 합계를 얻을 방법을 줄일 JQuery와

+1

이 카운터 될 것입니다 다른 변수를 확인하십시오! –

+2

실제 코드는 어떻게 생겼습니까? 당신은 클릭 수를 셀 수 있고 클릭 할 때마다 '++'를 클릭 할 수 있습니다. – DaniP

+0

필드의 구조는 무엇입니까, 구분 기호가 있습니까? 예제를 제공해 주시겠습니까? – DaveCoast

답변

0

밀어을 다른 모든 후 배열 하나에 제공하는 번호와 사용 사용하고

. 합계를 찾기 전에 yourArray.length를 사용하여 숫자의 양을 찾을 수 있습니다. 그런 경우

0

는 I, 당신이 값 배열로 작업 가정.

if (values.length > 5) { 
    // disable your button 

    var i, len = values.length, total = 0; 
    for (i = 0; i < len; i++) { 

     // add up total 
     total += values[i]; 
    } 

    // display your total 
} 
0

사용 $('p').each(function(a,b) {... 또는 .find ('P'), 각 (함수 (a, b) '의지 그것은 더 페이지의 실제 사용하는 것보다 반복을 의미 않지만,

1

이 시도 그 비용은 최소화 단락의 인덱스 번호 수. 그래서

if (a < 6) { 
    ... 
} 

같은 검사를 추가

let pressCounter = 0, 
 
total = 0, 
 
inputVal = 0; 
 
$("#add").click(function() { 
 
    if(pressCounter >= 6){ 
 
     $(this).attr('disabled', 'disabled'); 
 
    }else { 
 
    pressCounter += 1; 
 
    inputVal = $("#my-input").val(); 
 
    inputVal = Number(inputVal); 
 
    total += inputVal; 
 
    console.log(total); // print total. just for test 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 

 
<input id="my-input"> 
 
<input type="button" id="add" value="Add">

0

이 시도 :

<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script> 
 
$(document).ready(function(){ 
 
    $("#aadd").click(function() { 
 
    var arrayy = JSON.parse("[" + $("#my-input").val() + "]"); 
 
    console.log("Length of array = "+arrayy.length) 
 
    if(arrayy.length<6 ||arrayy.length>6) 
 
    { 
 
     alert("Please enter 6 values"); 
 
    } 
 
    /*Write your logic to add 6 numbers in array*/ 
 
    }); 
 
    }); 
 
</script> 
 
</head> 
 
<body> 
 
    <input type="text" id="my-input" value="1,2,3,4,5,6"> 
 
    <input type="button" id="aadd" value="Add"> 
 
</body> 
 
</html>

관련 문제