javascript
  • html
  • increment
  • decrement
  • 2014-06-18 3 views 0 likes 
    0

    기본적으로 저는 startTime에 하나, endTime에 하나씩 네 개의 timepicker가 있습니다. 시작 시간은 startHour와 startMin으로 구분되며 endTime에도 동일하게 적용됩니다.여러 개의 증가 및 감소 버튼

    htmlStr += "<tr><td><input type='button' id='startHourPlus' value='+' class='qtyplus' field='quantity' onClick='plusHour();' /><input type='button' id='startMinPlus' value='+' class='qtyplus' field='quantity' onClick='plusMin();' /><br/>"; 
    htmlStr += "<input type='text' id='startHour' name='quantity' value='0' class='qty' /><input type='text' id='startMin' name='quantity' value='0' class='qty' /><br/>"; 
    htmlStr += "<input type='button' id='startHourMinus' value='-' class='qtyminus' field='quantity' onClick='minusHour();'/><input type='button' id='startMinMinus' value='-' class='qtyminus' field='quantity' onClick='minusMin();' /></td>"; 
    

    그리고 endTime- 사용자의 경우 :

    htmlStr += "<td><input type='button' id='endHourPlus' value='+' class='qtyplus' field='quantity' onClick='plusHour();' /><input type='button' id='endMinPlus' value='+' class='qtyplus' field='quantity' onClick='plusMin();' /><br/>"; 
    htmlStr += "<input type='text' id='endHour' name='quantity' value='0' class='qty' /><input type='text' id='endMin' name='quantity' value='0' class='qty' /><br/>"; 
    htmlStr += "<input type='button' id='endHourMinus' value='-' class='qtyminus' field='quantity' onClick='minusHour();' /><input type='button' id='endMinMinus' value='-' class='qtyminus' field='quantity' onClick='minusMin();' /></td></tr>"; 
    

    플러스와 마이너스가 클릭하면,이 같은 기능을 공유 여기에 내가 내 startTime을 설정하는 방법입니다. 여기 내 자바 스크립트입니다 :

    function plusHour() { 
    e.preventDefault(); 
    // Get the field name 
    fieldName = $(this).attr('field'); 
    // Get its current value 
    var currentVal = parseInt($('input[name=' + fieldName + ']').val()); 
    // If is not undefined 
    if (!isNaN(currentVal)) { 
        // Increment 
        if (currentVal < 24) { 
         $('input[name=' + fieldName + ']').val(currentVal + 1); 
        } 
    } 
    // Otherwise put a 0 there 
    $('input[name=' + fieldName + ']').val(0); 
    } 
    function plusMin() { 
        e.preventDefault(); 
        // Get the field name 
        fieldName = $(this).attr('field'); 
        // Get its current value 
        var currentVal = parseInt($('input[name=' + fieldName + ']').val()); 
        // If is not undefined 
        if (!isNaN(currentVal)) { 
         // Increment 
         if (currentVal < 60) { 
          $('input[name=' + fieldName + ']').val(currentVal + 1); 
         } 
        } 
        // Otherwise put a 0 there 
        $('input[name=' + fieldName + ']').val(0); 
    } 
    function minusHour() { 
        // Stop acting like a button 
        e.preventDefault(); 
        // Get the field name 
        fieldName = $(this).attr('field'); 
        // Get its current value 
        var currentVal = parseInt($('input[name=' + fieldName + ']').val()); 
        // If it isn't undefined or its greater than 0 
        if (!isNaN(currentVal) && currentVal > 0) { 
         // Decrement one 
         $('input[name=' + fieldName + ']').val(currentVal - 1); 
        } else { 
         // Otherwise put a 0 there 
         $('input[name=' + fieldName + ']').val(0); 
        } 
    } 
    function minusMin() { 
        // Stop acting like a button 
        e.preventDefault(); 
        // Get the field name 
        fieldName = $(this).attr('field'); 
        // Get its current value 
        var currentVal = parseInt($('input[name=' + fieldName + ']').val()); 
        // If it isn't undefined or its greater than 0 
        if (!isNaN(currentVal) && currentVal > 0) { 
         // Decrement one 
         $('input[name=' + fieldName + ']').val(currentVal - 1); 
        } else { 
         // Otherwise put a 0 there 
         $('input[name=' + fieldName + ']').val(0); 
        } 
    } 
    

    여기 내 바이올린입니다 : Fiddle 첫 번째와 두 번째는 마지막 두 사람은 endTime- 사용자위한, startTime을위한이.

    그러나 시작 또는 종료 시간에 증가 및 감소 버튼을 클릭하면 텍스트 상자에 값이 표시되지 않습니다. 내가 잘못한 부분이 궁금합니다.

    미리 감사드립니다. 당신이 e.preventDefault();를 사용하고 있기 때문에

    +0

    당신은 단순히 'var (current) = parseInt ($ ('input [name = '+ fieldName +'] ') 대신'$ (this))); –

    +0

    바이올린이 실제로 도움이됩니다. – Yaje

    +0

    다음은 바이올린입니다. http://jsfiddle.net/BPEC2/ –

    답변

    1
    • 당신은, thiswindow 객체를 참조 핸들러 내부 그래서 당신은 클릭 핸들러 인라인을 부착하고, 또한 e

      function plusHour() { 
      e= window.event; 
      
    • 선언해야합니다. 당신이있어, 각 기능의 끝에서 - 당신은 그런 논리에 문제가있을

      <input type='button' id='startHourPlus' value='+' class='qtyplus' field='quantity' onClick='plusHour(this);' /> 
      

      이있는 당신이

      function plusHour(elm) { //elm now refers to clicked element 
      e= window.event; 
      e.preventDefault(); 
      // Get the field name 
      fieldName = $(elm).attr('field'); 
      
    • 같은 기능에 액세스 할 수 있습니다 다음과 같이 명시 적 요소의 참조를 전달해야 단순히 0으로 else 조건 안에 있어야

      $('input[name=' + fieldName + ']').val(0); 
      

      를 텍스트 박스 값을 설정.

    JSFiddle

    +0

    하지만 하나씩 설정해야합니다. 한 번에 모든 것이 아닙니다. 그래서 저는 4 대신에 8 가지 방법을 만들어야 만합니까? –

    +0

    @ 9Dollars99Cents "그러나 시작 또는 종료 시간에 증가 및 감소 버튼을 클릭하면 텍스트 상자에 값이 표시되지 않습니다. 내가 잘못한 부분이 궁금합니다." 그 대답이 그 질문을 다루기를 바랍니다. 우리는 당신을 위해 전체 응용 프로그램을 작성하는 것이 아닙니다 ... 현재의 문제를 해결 한 답변에서 얻은 결과를 바탕으로 새로운 질문을하는 것입니다. 투표를하지 않고도 ... 당신을 도우려는 것이 전혀 아닙니다. 어떤 추가 ... –

    +0

    그래, 정말 고마워! 나는 그것을 풀었다. –

    1

    1) e.preventDefault 제거(); 객체가 없으므로 오류가있는 스크립트 실행을 막고 있습니다.

    2) 모든 텍스트 상자의 이름이 "수량"입니다. 코드에서 입력 이름을 사용하여 요소에 액세스하고 있습니다. 그게 모호하지 않습니까? 어떤 입력 값을 사용할 것입니까? 텍스트 상자에 고유 한 입력 ID로 변경하십시오.

    +0

    그래, 정말 고마워! 그게 내게 계몽. –

    1

    시도해보십시오.

    http://jsfiddle.net/puJ6G/849/

    난 그냥 실제로 이전 게시물을 편집하고 나는 당신을 도울 것입니다 생각합니다.

    이이 내 두 번째 형태 내 첫 번째 양식

    <form id='myform1' method='POST' action='#'> 
        <input type='button' value='-' class='qtyminus' field='quantity' /> 
        <input type='text' name='quantity' value='0' class='qty' /> 
        <input type='button' value='+' class='qtyplus' field='quantity' /> 
    </form> 
    

    이다는

    <form id='myform2' method='POST' action='#'> 
        <input type='button' value='-' class='qtyminus' field='quantity1' /> 
        <input type='text' name='quantity1' value='0' class='qty' /> 
        <input type='button' value='+' class='qtyplus' field='quantity1' /> 
    </form> 
    

    나는 사용자가 필드 패스가 될 것입니다 클릭 이제까지 버튼 입력의 이름 그래서 필드를 변경 값을 변경하려는 위치를 입력하십시오.

    도움이되기를 바랍니다. 샘플 코드를보고 분석하십시오. 모든 작업에 하나의 함수를 만들기 위해 jQuery를 사용하여

    +0

    자, 고마워. 나는 그것을 풀어 보았지만 시작과 끝 시간 동안 함수를 반복 할 때 최상의 솔루션이라고 생각하지 않는다. –

    +0

    같은 개념입니다. 중요한 것은 다른 입력에서 동일한 함수를 사용하고 원하는 결과를 제공한다는 것입니다. –

    1

    :

    $(document).ready(function(){ 
    
          $("#startHourPlus,#startMinPlus,#endHourPlus,#endMinPlus,#startHourMinus,#startMinMinus,#endHourMinus,#endMinMinus").click(function() 
          { 
           var operation = $(this).val(); // + or - 
           var currentField = $("#" + $(this).attr("field"));    
           var currValue = parseInt(currentField.val()); 
           // Determine whether its PLUS or MINUS operation 
           if(operation == "+") 
           {    
            if (!isNaN(currValue)) 
            { 
             // If its hours, limit it to 24 as max 
             if($(this).attr("field").contains("Hour")) 
             { 
              if(currValue < 24) 
               $(currentField).val(currValue+1); 
              else 
               $(currentField).val(0); 
             } 
             // If its mins, limit it to 60 as max 
             else if($(this).attr("field").contains("Min")) 
             { 
              if(currValue < 60) 
               $(currentField).val(currValue+1); 
              else 
               $(currentField).val(0); 
             } 
    
            } 
           } 
           else if(operation == "-") 
           { 
            if (!isNaN(currValue) && currValue > 0) 
             $(currentField).val(currValue-1); 
            else 
             $(currentField).val(0); 
           } 
    
          }); 
         }); 
    

    을 ============================ =========================

    그리고 다음과 같이 보일 것이다 HTML은 (몇 이드가 제거 onClicks 추가) :

    <table> 
        <tr> 
         <td> 
          <input type='button' id='startHourPlus' value='+' class='qtyplus' field='txtstartHour'/> 
          <input type='button' id='startMinPlus' value='+' class='qtyplus' field='txtstartMin' /> 
          <br/> 
          <input type='text' id='txtstartHour' name='quantity' value='0' class='qty' /> 
          <input type='text' id='txtstartMin' name='quantity' value='0' class='qty' /> 
          <br/> 
          <input type='button' id='startHourMinus' value='-' class='qtyminus' field='txtstartHour' /> 
          <input type='button' id='startMinMinus' value='-' class='qtyminus' field='txtstartMin' /> 
         </td> 
    
         <td> 
          <input type='button' id='endHourPlus' value='+' class='qtyplus' field='txtendHour' /> 
          <input type='button' id='endMinPlus' value='+' class='qtyplus' field='txtendMin' /> 
          <br/> 
          <input type='text' id='txtendHour' name='quantity' value='0' class='qty' /> 
          <input type='text' id='txtendMin' name='quantity' value='0' class='qty' /> 
          <br/> 
          <input type='button' id='endHourMinus' value='-' class='qtyminus' field='txtendHour' /> 
          <input type='button' id='endMinMinus' value='-' class='qtyminus' field='txtendMin' /> 
         </td> 
        </tr> 
    </table> 
    

    그것이 효과가 있는지 알려주세요. 데모 here

    +0

    하지만 바이올린이 작동하지 않습니다. –

    +0

    왜 작동하지 않는지 잘 모름. 여기에 게시하기 전에 확인했습니다. 이것을 시도하십시오 http://jsfiddle.net/r5LL3/1/ – Ronnie

    +0

    어떻게 9 @ Dollars99Cents가 되었습니까? 당신은 그것을 시험 할 수 있었습니까? 바이올린을 통해서가 아니라면, 위의 코드를 로컬 HTML 사본에 복사하여 볼 수 있습니다. – Ronnie

     관련 문제

    • 관련 문제 없음^_^